Skip to content

GraphQL Apollo 中间件

用于 vafast 的中间件,可以使用 GraphQL Apollo。

使用以下命令安装:

bash
bun add graphql @vafastjs/apollo @apollo/server

然后使用它:

typescript
import { Vafast } from 'vafast'
import { apollo, gql } from '@vafastjs/apollo'

const app = new Vafast()
	.use(
		apollo({
			typeDefs: gql`
				type Book {
					title: String
					author: String
				}

				type Query {
					books: [Book]
				}
			`,
			resolvers: {
				Query: {
					books: () => {
						return [
							{
								title: 'Vafast',
								author: 'saltyAom'
							}
						]
					}
				}
			}
		})
	)
	.listen(3000)

访问 /graphql 应该会显示 Apollo GraphQL playground 工作情况。

背景

由于 Vafast 基于 Web 标准请求和响应,这与 Express 使用的 Node 的 HttpRequestHttpResponse 不同,导致 req, res 在上下文中为未定义。

因此,Vafast 用 context 替代两者,类似于路由参数。

typescript
const app = new Vafast()
	.use(
		apollo({
			typeDefs,
			resolvers,
			context: async ({ request }) => {
				const authorization = request.headers.get('Authorization')

				return {
					authorization
				}
			}
		})
	)
	.listen(3000)

配置

该中间件扩展了 Apollo 的 ServerRegistration(即 ApolloServer 的构造参数)。

以下是用于使用 Vafast 配置 Apollo Server 的扩展参数。

path

@default "/graphql"

暴露 Apollo Server 的路径。

enablePlayground

@default process.env.ENV !== 'production'

确定 Apollo 是否应提供 Apollo Playground。