主题
GraphQL Apollo 插件
¥GraphQL Apollo Plugin
用于使用 GraphQL Apollo 的 elysia 插件。
¥Plugin for elysia for using GraphQL Apollo.
使用以下工具安装:
¥Install with:
bash
bun add graphql @elysiajs/apollo @apollo/server
然后使用它:
¥Then use it:
typescript
import { Elysia } from 'elysia'
import { apollo, gql } from '@elysiajs/apollo'
const app = new Elysia()
.use(
apollo({
typeDefs: gql`
type Book {
title: String
author: String
}
type Query {
books: [Book]
}
`,
resolvers: {
Query: {
books: () => {
return [
{
title: 'Elysia',
author: 'saltyAom'
}
]
}
}
}
})
)
.listen(3000)
访问 /graphql
应该会显示 Apollo GraphQL Playground 的运行情况。
¥Accessing /graphql
should show Apollo GraphQL playground work with.
上下文
¥Context
由于 Elysia 基于 Web 标准请求和响应,这与 Express 使用的 Node 的 HttpRequest
和 HttpResponse
不同,导致 req, res
在上下文中未定义。
¥Because Elysia is based on Web Standard Request and Response which is different from Node's HttpRequest
and HttpResponse
that Express uses, results in req, res
being undefined in context.
因此,Elysia 将两者都替换为类似 context
的路由参数。
¥Because of this, Elysia replaces both with context
like route parameters.
typescript
const app = new Elysia()
.use(
apollo({
typeDefs,
resolvers,
context: async ({ request }) => {
const authorization = request.headers.get('Authorization')
return {
authorization
}
}
})
)
.listen(3000)
配置
¥Config
此插件扩展了 Apollo 的 ServerRegistration(即 ApolloServer
's' 构造函数参数)。
¥This plugin extends Apollo's ServerRegistration (which is ApolloServer
's' constructor parameter).
以下是使用 Elysia 配置 Apollo 服务器的扩展参数。
¥Below are the extended parameters for configuring Apollo Server with Elysia.
path
@default "/graphql"
公开 Apollo 服务器的路径。
¥Path to expose Apollo Server.
enablePlayground
@default process.env.ENV !== 'production'
确定 Apollo 是否应提供 Apollo Playground。
¥Determine whether should Apollo should provide Apollo Playground.