主题
GraphQL Yoga 插件
¥GraphQL Yoga Plugin
此插件将 GraphQL yoga 与 Elysia 集成。
¥This plugin integrates GraphQL yoga with Elysia
使用以下工具安装:
¥Install with:
bash
bun add @elysiajs/graphql-yoga
然后使用它:
¥Then use it:
typescript
import { Elysia } from 'elysia'
import { yoga } from '@elysiajs/graphql-yoga'
const app = new Elysia()
.use(
yoga({
typeDefs: /* GraphQL */ `
type Query {
hi: String
}
`,
resolvers: {
Query: {
hi: () => 'Hello from Elysia'
}
}
})
)
.listen(3000)
在浏览器中访问 /graphql
(GET 请求)将显示一个支持 GraphQL 的 Elysia 服务器的 GraphiQL 实例。
¥Accessing /graphql
in the browser (GET request) would show you a GraphiQL instance for the GraphQL-enabled Elysia server.
可选:你还可以安装自定义版本的可选对等依赖:
¥optional: you can install a custom version of optional peer dependencies as well:
bash
bun add graphql graphql-yoga
解析器
¥Resolver
Elysia 使用 Mobius 自动从 typeDefs 字段推断类型,使你在输入解析器类型时获得完全的类型安全性和自动补齐功能。
¥Elysia uses Mobius to infer type from typeDefs field automatically, allowing you to get full type-safety and auto-complete when typing resolver types.
上下文
¥Context
你可以通过添加 context 为解析器函数添加自定义上下文。
¥You can add custom context to the resolver function by adding context
ts
import { Elysia } from 'elysia'
import { yoga } from '@elysiajs/graphql-yoga'
const app = new Elysia()
.use(
yoga({
typeDefs: /* GraphQL */ `
type Query {
hi: String
}
`,
context: {
name: 'Mobius'
},
// If context is a function on this doesn't present
// for some reason it won't infer context type
useContext(_) {},
resolvers: {
Query: {
hi: async (parent, args, context) => context.name
}
}
})
)
.listen(3000)
配置
¥Config
此插件扩展了 GraphQL Yoga 的 createYoga 选项,请参阅 GraphQL Yoga 文档,并将 schema
配置内联到 root。
¥This plugin extends GraphQL Yoga's createYoga options, please refer to the GraphQL Yoga documentation with inlining schema
config to root.
以下是插件接受的配置。
¥Below is a config which is accepted by the plugin
path
@default /graphql
用于公开 GraphQL 处理程序的端点
¥Endpoint to expose GraphQL handler