前言
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.uj5u.com/qiye/381869.html
標籤:JavaScript
