2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Next.js App Router で route handlers でappollo graphql を利用する

Posted at

Next.js App Router で route handlers でgraphql を利用する

背景

Page Routerを利用した記事やTutorialはあるが、
App Routerを利用した場合の方法がなく軽く実装してみようと考えたため。

TL;DR

Page Routerと同じく、apollo-server-integration-nextをinstallして利用すれば動きます。

apollo-server-integration-next

0. 現状の想定しているdirectory

% npx create-next-app@latest

上記で生成したdirectoryを想定しています。

1. apollo server で依存関係をinstallする

apollo server get startedに記載通りの手順で依存関係をinstallする。

% npm install @apollo/server graphql

上記のみの場合だと、apollo serverからRoute Handlerの調整が必要になるため、apollo-server-integration-nextを追加でinstallします。

% npm i @as-integrations/next

2. route handlerに記載する

api/graphqlをgraphqlようのpathにして作成していきます。

% mkdir -r api/graphql
% touch api/graphql/route.ts

apollo server get startedの定義を追加していきます。

api/graphql/rotue.ts
import { ApolloServer } from '@apollo/server'

// A schema is a collection of type definitions (hence "typeDefs")
// that together define the "shape" of queries that are executed against
// your data.
const typeDefs = `#graphql
  # Comments in GraphQL strings (such as this one) start with the hash (#) symbol.

  # This "Book" type defines the queryable fields for every book in our data source.
  type Book {
    title: String
    author: String
  }

  # The "Query" type is special: it lists all of the available queries that
  # clients can execute, along with the return type for each. In this
  # case, the "books" query returns an array of zero or more Books (defined above).
  type Query {
    books: [Book]
  }
`

const books = [
  {
    title: 'The Awakening',
    author: 'Kate Chopin',
  },
  {
    title: 'City of Glass',
    author: 'Paul Auster',
  },
]

const resolvers = {
  Query: {
    books: () => books,
  },
}

const server = new ApolloServer({
  typeDefs,
  resolvers,
})

apollo-server-integrations/apollo-server-integration-nextの通りに、handlerを定義する。

api/graphql/rotue.ts
import { ApolloServer } from '@apollo/server'
import { startServerAndCreateNextHandler } from '@as-integrations/next' // 追記

// 省略

const handler = startServerAndCreateNextHandler(server)

export { handler as GET, handler as POST } // 追記

3. apollo server にアクセスしてQueryを利用する

localhostに接続して、Queryを試してみる。

スクリーンショット 2024-10-28 14.53.11.png

2
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
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?