记录一次迁移Apollo Server V3的过程

前言

Apollo Server V3出来也快半年了,是时候把express-postgres-ts-starter的graphql部分升级了。

使用dependabot帮助更新版本

dependabot是一个github的工具(似乎也支持gitlab,但是我不确定),用于检测repo依赖安全性,同时也可以帮助我定期更新repo的依赖版本。

这是我的dependabot的配置文件:

version: 2
updates:
 - package-ecosystem: npm
   directory: '/'
   schedule:
    interval: weekly
   open-pull-requests-limit: 10

升级Apollo Servier所需要依赖

nodejs

Apollo Servier 3仅仅支持nodejsv12以上版本(Apollo Servier 2则只需要nodejsv6以上的支持)。 因此需要升级到nodejs12,推荐使用node14和node16。

我十分推荐使用Linux/MAC用户使用nvm,Windows用户使用nvm-windows安装、升级node版本。

graphql

Apollo Servier有一个可选依赖graphql(GraphQL JS的核心实现),Apollo Servier 3需要graphql v15.3.0以上的支持。

问题记录

GraphQL Playground

Apollo Server 2是默认支持GraphQL Playground,我们只需要在构造函数里配置好playground这个字段就好了,但是Apollo Server 3删除了对GraphQL Playgroun的默认支持,转而推荐在非生产环境中使用Apollo Sandbox

不过我们还是可以重新配置GraphQL Playground的。

如果之前是使用new ApolloServer({playground: boolean})的类似方式配置GraphQL Playground,那么可以

import { ApolloServerPluginLandingPageGraphQLPlayground,
         ApolloServerPluginLandingPageDisabled } from 'apollo-server-core';
new ApolloServer({
  plugins: [
    process.env.NODE_ENV === 'production'
      ? ApolloServerPluginLandingPageDisabled()
      : ApolloServerPluginLandingPageGraphQLPlayground(),
  ],
});

如果之前是使用new ApolloServer({playground: playgroundOptions})的类似方式配置GraphQL Playground,那么可以使用:

import { ApolloServerPluginLandingPageGraphQLPlayground } from 'apollo-server-core';

const playgroundOptions = {
    // 仅做参考
    settings: {
        'editor.theme': 'dark',
        'editor.cursorShape': 'line'
    }
}

new ApolloServer({
  plugins: [
    ApolloServerPluginLandingPageGraphQLPlayground(playgroundOptions),
  ],
});

tracing

Apollo Server 2中,构造函数的参数提供tracing布尔字段,用于开启基于(apollo-tracing)[https://www.npmjs.com/package/apollo-tracing]跟踪机制,但是很遗憾,在Apollo Server 3中,tracing已经被删除了,,,apollo-tracing也已经被废弃了,如果一定要使用,可以:

new ApolloServer({
  plugins: [
    require('apollo-tracing').plugin()
  ]
});

不过值得注意的是,该解决方案没有经过严格测试,可能存在bug。

You must await server.start() before calling server.applyMiddleware()

Apollo Server v2.22中提供了_server.start()_的方法,其目的是为了方便集成非serverless的框架(Express、Fastify、Hapi、Koa、Micro 和 Cloudflare)。因此这些框架的使用者使用在创建ApolloServer对象之后立刻启动graphql服务。

const app = express();
const server = new ApolloServer({...});
await server.start();
server.applyMiddleware({ app });

结束

现在可以在浏览器打开GraphQL Playground, 以express-postgres-ts-starter为例,使用http://127.0.0.1:3000/graphql就可以看到效果了。

声明

原文链接

原文地址:https://www.cnblogs.com/xiao2/p/15692903.html