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?

Webアプリ構築カレンダーAdvent Calendar 2023

Day 6

【Day 6】Web環境構築 - GraphQL モックサーバー

Last updated at Posted at 2023-12-05

はじめに

スライド7.PNG


2023年アドベントカレンダー6日目です。

前回の続きで「開発者はWebの開発を進めることができる」を進めていきます。

image.png

Apollo Server

Apollo Serverとは

  • Apollo Serverは、GraphQL APIを構築するためのオープンソースのWebサーバーです

Install & Start

ApolloServer + TypeScriptで起動していきたいと思います。

web/mock/
npm init --yes && npm pkg set type="module"
npm install @apollo/server graphql
npm install --save-dev typescript @types/node @graphql-tools/load
tsconfig.json
{
  "compilerOptions": {
    "rootDirs": ["src"],
    "outDir": "dist",
    "lib": ["es2020"],
    "target": "es2020",
    "module": "esnext",
    "moduleResolution": "node",
    "esModuleInterop": true,
    "types": ["node"]
  },
  "include": ["src"],
  "exclude": ["node_modules"]
}
package.json
  "scripts": {
-   "test": "echo \"Error: no test specified\" && exit 1",
+   "compile": "tsc",
+   "start": "npm run compile && node ./dist/index.js"
  }

Create Schema

Schemaファイルを設定していきます。

後々ここはGraphQL Code Generatorによって、自動生成に変更予定です。
動作確認のために設置しておきます

schema.graphql
type Blog {
  author: String!
  body: String!
  createdAt: String!
  title: String!
}

type Query {
  blogs: [Blog!]!
}

Create Index.ts

サーバー起動用のTSファイルを作成します。

src/index.ts
import { ApolloServer } from '@apollo/server'
import { loadSchemaSync } from '@graphql-tools/load'
import { GraphQLFileLoader } from '@graphql-tools/graphql-file-loader'
import { startStandaloneServer } from '@apollo/server/standalone'
import { join, dirname } from 'path'
import { fileURLToPath } from 'url'

const __filename = fileURLToPath(import.meta.url)
const __dirname = dirname(__filename)

const schema = loadSchemaSync(join(__dirname, '../schema.graphql'), {
  loaders: [new GraphQLFileLoader()],
})

const resolvers = {
  Query: {
    blogs: () => [],
  },
}

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

const { url } = await startStandaloneServer(server, { listen: { port: 4000 } })

console.log(`🚀 Server listening at: ${url}`)

Let's Start

起動してみましょう

npm run start

image.png

これでモックサーバーが立ち上がりました

明日はGraphQLの開発を進めやすくするためにGraphQL Code Generatorの設定をしていきます

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?