LoginSignup
0
0

More than 1 year has passed since last update.

GraphQL サーバー構築(その6. prismaとgraphql(apollo)サーバーの連携)

Last updated at Posted at 2022-12-31

id: 91eea4d1

この記事のリポジトリ

前回

今回やること

  • resolver で使用するためのcontextを用いて、prisma と接続
  • クエリをなげて、prismaと接続できていることを確認

resolver で使用するためのcontextを用いて、prisma と接続

  • contextの型定義
index.ts
interface Context {  
    dbsource: {
        prisma: PrismaClient;
    }
}
  • contextにdbsourceを追加
index.ts
  const { url } = await startStandaloneServer(server, {
    listen: { port: 4000 },
    context: async () => ({
      dbsource: {
        prisma: prisma
      }
    })
  });

  console.log(`🚀  Server ready at: ${url}`);
}
  • context を用いてprismaにクエリをなげることができるようにresolver を 修正
index.ts
  const resolvers: Resolvers = {
    Query: {
      books: async (parent, args, context: Context) => await context.dbsource.prisma.book.findMany(),
    },
    Mutation: {
      addBook: async (parent, args, context: Context) => {
        await prisma.book.create({
          data: {
            title: args.title,
            author: args.author
          }
        });
        return await context.dbsource.prisma.book.findMany()
      }
    }
  };

クエリをなげて、prismaと接続できていることを確認

bash
$ yarn start

オッケーです。
2022-12-31_23h58_25.png

次回以降

  • next.js でgraphql サーバーにクエリをなげる
  • sqlite -> mysql に変更。dokcer 使用する。
  • nestjsを用いたgraphqlの導入
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0