🦖

DenoでPothos GraphQL

2025/02/19に公開

動機

  • GraphQLサーバーを軽量なバックエンドで実現したい
  • Code firstなGraphQLであるPothosを使ってみたい

公式

Pothosの公式をみると
https://pothos-graphql.dev/docs/guide/deno
Denoには対応してそうですがversion1に対してのみのようでした(2025.2.19時点)↓

今回は最新のDeno version2で実装してみたいので色々試行錯誤しました。

結論

deno.json

{
  "tasks": {
    "dev": "deno run --watch --allow-net main.ts"
  },
  "imports": {
    "@std/assert": "jsr:@std/assert@1",
    "graphql": "npm:graphql@16.10.0",  
    "@pothos/core": "npm:@pothos/core@3.23.1",
    "graphql-yoga": "https://esm.sh/graphql-yoga?external=graphql"
  }
}

main.ts

import { createYoga } from 'graphql-yoga'
import SchemaBuilder from '@pothos/core';

const builder = new SchemaBuilder({});
 
builder.queryType({
  fields: (t) => ({
    hello: t.string({
      args: {
        name: t.arg.string({}),
      },
      resolve: (_, { name }) => `hello, ${name || 'World'}`,
    }),
  }),
});
 
const yoga = createYoga({
  schema: builder.toSchema(),
});

Deno.serve(async (req) => {
  const url = new URL(req.url);
  if (url.pathname === "/graphql") {
    try {
      const response = await yoga.handleRequest(req,{});
      return response;
    } catch (error) {
      console.error("GraphQL Error:", error);
      return new Response("GraphQL Error", { status: 500 });
    }
  }
  return new Response("Not Found", { status: 404 });
});

で以下のようにGraphQLサーバー立ち上げることができました。

Discussion