GraphQL Yoga

GraphQL Yoga is a GraphQL Server with great developer experience.

Setup

First, install the necessary dependencies:

bun add graphql graphql-yoga

Define Schema

Create a file named schema.ts with the following content to define your GraphQL schema:

import { createSchema } from 'graphql-yoga'

const typeDefinitions = /* GraphQL */ `
  type Query {
    hello: String!
  }
`

const resolvers = {
  Query: {
    hello: () => 'Hello World!'
  }
}

export const schema = createSchema({
  resolvers: [resolvers],
  typeDefs: [typeDefinitions]
})

Execute Query

Create a file named main.ts to run a sample query:

import { execute, parse } from 'graphql'
import { schema } from './schema'

const query = /* GraphQL */ `
  query {
    hello
  }
`

console.log(await execute({
  schema,
  document: parse(query)
}))

Run the query:

bun main.ts

Expected output:

{
  "data": {
    "hello": "Hello World!"
  }
}

Set Up GraphQL Server

Create a file named server.ts to set up a GraphQL server:

import { createServer } from 'node:http'
import { createYoga } from 'graphql-yoga'
import { schema } from './schema'

createServer(createYoga({ schema }))
  .listen(4000, () => {
    console.info('Server is running on http://localhost:4000/graphql')
  })

Start the server:

bun server.ts

Test the GraphQL API

Open your browser and go to http://localhost:4000/graphql. Use the following query in the GraphQL Playground:

query {
  hello
}

You should receive the following response:

{
  "data": {
    "hello": "Hello World!"
  }
}

Send a Request via Curl

You can also test the GraphQL API using curl:

curl -X POST http://localhost:4000/graphql \
 -H "Content-Type: application/json" \
 -d '{"query": "query { hello }"}'

Expected output:

{"data":{"hello":"Hello World!"}}

More on Schema

It's also possible to create GraphQL schemas in typescript with Pothos. So that you don't have to write them seperately.

import { createYoga } from 'graphql-yoga'
import { createServer } from 'node:http'
import SchemaBuilder from '@pothos/core'

const builder = new SchemaBuilder({})

builder.queryType({
  fields: (t) => ({
    hello: t.string({
      args: {
        name: t.arg.string(),
      },
      resolve: (parent, { name }) => `hello, ${name || 'World'}`,
    }),
  }),
})

const yoga = createYoga({
  schema: builder.toSchema(),
})