前言

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

使用dependabot帮助更新版本

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

  1. version: 2
  2. updates:
  3. - package-ecosystem: npm
  4. directory: '/'
  5. schedule:
  6. interval: weekly
  7. open-pull-requests-limit: 10

升级Apollo Server所需要依赖

nodejs

Apollo Server 3仅仅支持nodejs v12以上版本(Apollo Server 2则只需要nodejs v6以上的支持)。 因此需要升级到nodejs12,推荐使用node14和node16。
我十分推荐使用Linux/MAC用户使用nvm,Windows用户使用nvm-windows安装、升级node版本。

graphql

Apollo Server有一个可选依赖GraphQL(GraphQL JS的核心实现),Apollo Server 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,那么可以

  1. import { ApolloServerPluginLandingPageGraphQLPlayground,
  2. ApolloServerPluginLandingPageDisabled } from 'apollo-server-core';
  3. new ApolloServer({
  4. plugins: [
  5. process.env.NODE_ENV === 'production'
  6. ? ApolloServerPluginLandingPageDisabled()
  7. : ApolloServerPluginLandingPageGraphQLPlayground(),
  8. ],
  9. });

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

  1. import { ApolloServerPluginLandingPageGraphQLPlayground } from 'apollo-server-core';
  2. const playgroundOptions = {
  3. // 仅做参考
  4. settings: {
  5. 'editor.theme': 'dark',
  6. 'editor.cursorShape': 'line'
  7. }
  8. }
  9. new ApolloServer({
  10. plugins: [
  11. ApolloServerPluginLandingPageGraphQLPlayground(playgroundOptions),
  12. ],
  13. });

tracing

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

  1. new ApolloServer({
  2. plugins: [
  3. require('apollo-tracing').plugin()
  4. ]
  5. });

不过值得注意的是,该解决方案没有经过严格测试,可能存在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服务。

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

结束

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

参考资料

[1] https://damingerdai.github.io/front-end/log-migrate-apollo-server-v3/
[2] https://zhuanlan.zhihu.com/p/445688077