2022-07-24 16:24:51 +08:00
|
|
|
# GraphQL Server Middleware
|
|
|
|
|
2025-03-19 16:53:11 +08:00
|
|
|
[](https://codecov.io/github/honojs/middleware)
|
|
|
|
|
2022-07-24 16:24:51 +08:00
|
|
|
## Requirements
|
|
|
|
|
|
|
|
This middleware depends on [GraphQL.js](https://www.npmjs.com/package/graphql).
|
|
|
|
|
2022-12-13 15:32:51 +08:00
|
|
|
```sh
|
2023-02-04 10:02:22 +08:00
|
|
|
npm i @hono/graphql-server
|
2022-07-24 16:24:51 +08:00
|
|
|
```
|
|
|
|
|
|
|
|
or
|
|
|
|
|
|
|
|
```plain
|
2023-02-04 10:02:22 +08:00
|
|
|
yarn add @hono/graphql-server
|
2022-07-24 16:24:51 +08:00
|
|
|
```
|
|
|
|
|
|
|
|
## Usage
|
|
|
|
|
2024-07-15 16:38:06 +08:00
|
|
|
index.ts:
|
2022-07-24 16:24:51 +08:00
|
|
|
|
2024-07-15 16:38:06 +08:00
|
|
|
```ts
|
2022-07-24 16:24:51 +08:00
|
|
|
import { Hono } from 'hono'
|
2024-07-15 16:38:06 +08:00
|
|
|
import { type RootResolver, graphqlServer } from '@hono/graphql-server'
|
2022-07-24 16:24:51 +08:00
|
|
|
import { buildSchema } from 'graphql'
|
|
|
|
|
|
|
|
export const app = new Hono()
|
|
|
|
|
|
|
|
const schema = buildSchema(`
|
|
|
|
type Query {
|
|
|
|
hello: String
|
|
|
|
}
|
|
|
|
`)
|
|
|
|
|
2024-07-15 16:38:06 +08:00
|
|
|
const rootResolver: RootResolver = (c) => {
|
2022-12-13 15:32:51 +08:00
|
|
|
return {
|
|
|
|
hello: () => 'Hello Hono!',
|
|
|
|
}
|
2022-07-24 16:24:51 +08:00
|
|
|
}
|
|
|
|
|
|
|
|
app.use(
|
|
|
|
'/graphql',
|
|
|
|
graphqlServer({
|
|
|
|
schema,
|
2022-12-13 15:32:51 +08:00
|
|
|
rootResolver,
|
2024-07-29 20:44:54 +08:00
|
|
|
graphiql: true, // if `true`, presents GraphiQL when the GraphQL endpoint is loaded in a browser.
|
2022-07-24 16:24:51 +08:00
|
|
|
})
|
|
|
|
)
|
|
|
|
|
|
|
|
app.fire()
|
|
|
|
```
|
2023-02-04 10:53:27 +08:00
|
|
|
|
|
|
|
## Author
|
|
|
|
|
|
|
|
Minghe Huang <h.minghe@gmail.com>
|