GraphQL Yoga 2.0发布!
构建 GraphQL Yoga 服务器只需要一次导入和几行代码即可开始提供 API。Yoga v2 的主要目标是通过与大多数现有模式设计、HTTP 服务器库和部署环境兼容,允许您利用所有 GraphQL 生态系统。Yoga v2 构建在模块化和可扩展的 GraphQL 服务器之上,允许您使用自己喜欢的模式设计方法和 HTTP 服务器库

今天,我们非常兴奋地与您分享新的 GraphQL Yoga!
开源开发组织于 2021 年初从 Prisma 接管了 GraphQL Yoga 的开发,并且随着社区工具的不断增长(最近的 Envelop),我们在简单的设置、性能和开发人员的经验方面重写了GraphQL Yoga 2.0在核心。
GraphQL Yoga 继续推崇“约定优于配置”的方法以及自由使用您喜欢的库,从 HTTP 到模式构建。
您不再需要安装数十个依赖项来获得订阅、文件上传、CORS、错误屏蔽等特性。
构建 GraphQL Yoga 服务器只需要一次导入和几行代码即可开始提供 API。您还可以通过 GraphiQL,让开发更加轻松。
// 1. Import GraphQL Yoga
import { createServer } from '@graphql-yoga/node'
// 2. Create your server
const server = createServer({
schema: {
typeDefs: /* GraphQL */ `
type Query {
hello: String
}
`,
resolvers: {
Query: {
hello: () => 'Hello Hello Hello'
}
}
}
})
// 3. Serve the API and GraphiQL
server.start()
Yoga v2 体验
Yoga v2 的主要目标是通过与大多数现有模式设计、HTTP 服务器库和部署环境兼容,允许您利用所有 GraphQL 生态系统。
Yoga v2 构建在模块化和可扩展的 GraphQL 服务器之上,允许您使用自己喜欢的模式设计方法和 HTTP 服务器库。
例如,Yoga v2 与 Express 和 Nexus 完全兼容,无需额外的软件包:
import express from 'express'
import { makeSchema, queryType } from 'nexus'
import { createServer } from '@graphql-yoga/node'
const Query = queryType({
definition(t) {
t.string('hello', { resolve: () => 'hello world!' })
}
})
const schema = makeSchema({
types: [Query]
})
const graphQLServer = createServer({ schema })
const app = express()
// Bind GraphQL Yoga to the `/graphql` endpoint
// Here it takes the request and response objects and handles them internally
app.use('/graphql', graphQLServer)
app.listen(4000, () => {
console.log('Running a GraphQL API server at http://localhost:4000/graphql')
})
这同样适用于 GraphQL Tools、Pothos、Nexus、TypeGraphQL、SDL first schema-design methods、graphql-js、Apollo Tools、Fastify、Koa、Next.js、SvelteKit 和 Deno。
除了模式设计和 HTTP 服务器库的兼容性之外,Yoga v2 还可以无缝地将 GraphQL API 部署到任何环境(Vercel Functions、Cloudflare Workers、AWS Lambda 等)。
在这里,使用 GraphQL 模块构建的 GraphQL API 部署在 Cloudflare Workers 上:
import { createServer } from '@graphql-yoga/common'
import { createApplication } from 'graphql-modules'
import { helloWorldModule } from './helloWorld'
const application = createApplication({
modules: [helloWorldModule]
})
const server = createServer({ schema: application.schema })
server.start()
生产力触手可及
Yoga v2 带有合理的默认设置以加快开发速度,所有这些都具有完整的 TypeScript 支持。
Yoga 内置了现代 GraphQL API 的常见功能,例如文件上传、订阅支持、高级错误处理或 CORS:
import { createServer, GraphQLYogaError } from '@graphql-yoga/node'
// Provide your schema
const server = createServer({
schema: {
typeDefs: /* GraphQL */ `
# adding this custom scalar enables file upload support
scalar Upload
type Query {
hello: String
}
type Subscription {
countdown(from: Int!): Int!
}
type Mutation {
readTextFile(file: Upload!): String
}
`,
resolvers: {
Query: {
hello: () => 'world'
},
Subscription: {
countdown: {
// This will return the value on every 1 sec until it reaches 0
subscribe: async function* (_, { from }) {
for (let i = from; i >= 0; i--) {
await new Promise((resolve) => setTimeout(resolve, 1000))
yield { countdown: i }
}
}
}
},
Mutation: {
readTextFile: async (_, { file }: { file: File }) => {
let textContent = null
try {
textContent = await file.text()
} catch (e) {
// return an error visible by the client
throw new GraphQLYogaError(`Failed to parse file`)
}
return textContent
}
}
}
}
})
// We now serve a GraphQL API with Subscriptions (over SSE), CORS,
// and File uploads support!
server.start()
Yoga v2 还提供 API 来处理日志记录、高级订阅用例(通过 WS、Pub/Sub)、Apollo Federation 支持等。
使用 Envelop 插件轻松扩展您的 API
GraphQL Yoga 支持开箱即用的 Envelop,这使您可以更好地控制,并能够挂钩到 GraphQL 执行阶段。
在这里,我们正在构建一个功能齐全的 GraphQL API,其中包含安全规则、响应缓存和哨兵错误报告,只需几行代码:
import { createServer } from '@graphql-yoga/node'
import { useDepthLimit } from '@envelop/depth-limit'
import { useResponseCache } from '@envelop/response-cache'
import { useSentry } from '@envelop/sentry'
const server = createServer({
schema: {
typeDefs: /* GraphQL */ `
type Query {
hello: String
}
`,
resolvers: {
Query: {
hello: () => 'Hello Hello Hello'
}
}
},
plugins: [
useDepthLimit({
// set up some security rules
maxDepth: 10
}),
useResponseCache(), // speed up our server with a response cache
useSentry() // report unexpected errors to sentry
]
})
// Start the server and explore http://localhost:4000/graphql
server.start()
Envelop 插件目前提出了超过 35 多个插件,涵盖了您在生产中需要的大多数标准 GraphQL API 功能。
最终,您可以开发自定义 Envelop 插件来创建与 GraphQL 生命周期挂钩的可重用行为。
生产就绪
GraphQL Yoga v2 已在生产环境中构建以供生产使用。
我们的项目(例如 GraphQL Mesh)和我们的一些客户中内置的真实世界条件,性能是高度优先考虑的。Yoga的核心是尽可能高效,我们不断跟踪和改进它。
此外,Yoga V2 存储库对每个提交和拉取请求运行性能检查,因此我们始终可以捕获任何性能回归。
最后但同样重要的是,通过端到端测试套件确保每次提交都能在所有部署目标上运行,例如 AWS Lambda 或 Cloudflare worker!
我们继续努力将 GraphQL Yoga 推向更多的生产环境,即将发布的 Redwood 1.0 使用 Yoga 2.0 作为其默认的 GraphQL 服务器。