Quantcast
Channel: Node.jsタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8909

Node.js × Expressで始めるGraphQL入門

$
0
0

概要

GraphQLを初めて実装してみた時の手順と、サンプルソースコードを記載しています。

環境

  • macOS Big Sur 11.1
  • node v14.12.0
  • yarn 1.22.10
  • express 4.16.1
  • Docker version 19.03.13
  • docker-compose version 1.27.4

サンプルソースコード

hayatoiwashita/express-graphql

手順

1. プロジェクトの雛形を作成

express-generatorを使用した。
--gitオプションは.gitignoreを追加するためのオプション。

$ express --view=pug --git express-graphql

参考: Express のアプリケーション生成プログラム

2. ライブラリのインストール

GraphQL関連のライブラリは最低限下記があればOK。

$ yarn add graphql
$ yarn add express-graphql

サンプルでは下記も追加している(本題から逸れるので割愛)

# ホットリロード
$ yarn add --dev nodemon
# コード整形
$ yarn add prettier --dev --exact
$ yarn add eslint --dev
$ yarn add --dev eslint-config-prettier
$ yarn add --dev eslint-plugin-prettier
# commit時にコード整形を実行
$ yarn add --dev lint-staged
$ yarn add --dev husky

3. サンプルデータの用意

/data/users.jsを追加して、DBの代わりに使用した。
(内容はサンプルソースコードのusers.jsを参照)

4. schemaを定義

/schema/schema.graphqlを作成してschemaを定義。
今回は参照系クエリのみ実装した。
データ構造は、ユーザとそれに紐づく投稿といった形。

schema.graphql
const{buildSchema}=require("graphql");constschema=buildSchema(`typeQuery{users:[User!]!,user(id:Int!):User!}typeUser{id:ID!name:String!email:Stringposts:[Post!]}typePost{id:ID!title:String!published:Boolean!link:Stringauthor:User!}`);module.exports=schema;

5. リゾルバを作成

データ操作を行う/src/resolvers.jsを作成。
上述の通り、今回は参照系のみ。

resolvers.js
const{Users}=require('../data/users');constresolvers={users:async(_)=>{console.log('come here');returnUsers;},user:async({id},context)=>{returnUsers.find((user)=>user.id==id);},};module.exports=resolvers;

6. app.js を修正

エンドポイント/graphqlを定義。

app.js
// var createError = require('http-errors');varexpress=require('express');var{graphqlHTTP}=require('express-graphql');varresolvers=require('./src/resolvers');varschema=require('./schema/schema.graphql');varpath=require('path');varcookieParser=require('cookie-parser');varlogger=require('morgan');varapp=express();// view engine setupapp.set('views',path.join(__dirname,'views'));app.set('view engine','pug');app.use(logger('dev'));app.use(express.json());app.use(express.urlencoded({extended:false}));app.use(cookieParser());app.use(express.static(path.join(__dirname,'public')));app.use('/graphql',graphqlHTTP({schema,rootValue:resolvers,graphiql:true,}));module.exports=app;

7. [参考] コンテナ化

Dockerfiledocker-compose.ymlを追加。

FROM node:14.15.4-slimWORKDIR /usr/local/src/express-graphqlADD . .RUN yarn installCMD [ "yarn", "start" ]
docker-compose.yml
version:'3'services:graphql:build:.container_name:graphql-containerports:-"3000:3000"

8. Expressの起動

起動コマンドを実行。

# コンテナで実行
$ docker-compose up

# コンテナを使用せず実行
$ yarn start

9. クエリを実行

http://localhost:3000/graphqlをブラウザで開く。
screencapture-localhost-3000-graphql-2021-01-16-16_08_50.png

サンプルクエリ
内容としては、ユーザID=1のユーザの名前と、そのユーザの投稿(posts)のIDとタイトルを取得するというもの。

{
  user(id:1) {
    name
    posts {
      id
      title
    }
  }
}

実行結果

{
  "data": {
    "user": {
      "name": "Fikayo Adepoju",
      "posts": [
        {
          "id": "1",
          "title": "Debugging an Ionic Android App Using Chrome Dev Tools"
        },
        {
          "id": "2",
          "title": "Hosting a Laravel Application on Azure Web App"
        }
      ]
    }
  }
}

screencapture-localhost-3000-graphql-2021-01-17-15_09_38.png

参考


Viewing all articles
Browse latest Browse all 8909

Trending Articles