Skip to content

Instantly share code, notes, and snippets.

@xorus
Created March 8, 2023 16:16
Show Gist options
  • Save xorus/1e63571cfb6040c876c303f8ccdd0b66 to your computer and use it in GitHub Desktop.
Save xorus/1e63571cfb6040c876c303f8ccdd0b66 to your computer and use it in GitHub Desktop.
graphql yoga in Hono server
import {Env, Hono, HonoRequest} from "hono";
import {createSchema, createYoga} from "graphql-yoga";
const schema = createSchema({
typeDefs: `...graphql schema...`,
resolvers: {
Query: {
hello: () => 'Hello wolrd :)',
},
Subscription: {
countdown: {
subscribe: async function* (_, {from}) {
for (let i = from; i >= 0; i--) {
await new Promise((resolve) => setTimeout(resolve, 1000))
yield {countdown: i}
}
}
}
}
}
})
const yoga = createYoga({
schema,
graphqlEndpoint: '/api/graphql',
});
// adapted from https://github.com/hagishi/hono-graphql-yoga that was not updated
app.use('/api/graphql', async (c) => {
const ctx = Object.prototype.hasOwnProperty.call(c, 'executionCtx') ? c.executionCtx : {}
return yoga.handleRequest(c.req, {
env: c.env,
ctx,
})
})
@o-az
Copy link

o-az commented Oct 27, 2024

This should work if you're deploying to Cloudflare Workers:

import { Hono } from 'hono'
import { createSchema, createYoga } from 'graphql-yoga'

const schema = createSchema({
  typeDefs: () => /* graphql */`
    type Query {
      health: String
    }
  `,
  resolvers: {
    Query: {
      health: () => `OK`
    },
  }
})

const yoga = createYoga({
  schema,
  graphqlEndpoint: '/graphql'
})

const app = new Hono()

export default {
  app,
  fetch: yoga.fetch
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment