GraphQLを触ってみる

2020/05/16

勉強メモです。

GraphQLについて

  • APIのための型付けされたクエリ言語
  • 分かりやすいクエリで必要なデータを正確に入手
  • RESTの置き換えではない
  • エンドポイントが1つ

  • Query: GraphQLサーバーに要求される読み取り専用操作
  • Mutation: GraphQLサーバーに要求される読み書き操作

tutorial

JavaScriptを使ったチュートリアルをやってみる
次ページにあるlocalhostでサーバー起動して試すやつから始めてみる。

準備

作業ディレクトリを作成、npm init

mkdir gql-server
cd gql-server
npm init

パッケージのインストール

  • graphql
  • express
  • express-graphql
npm install graphql express express-graphql --save

サーバを作る

var express = require('express');
var express_graphql = require('express-graphql');
var {
  buildSchema
} = require('graphql');

// GraphQLスキーマ言語を用いてスキーマを作成
var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// rootは各APIエンドポイントにresolver関数を提供
var root = {
  hello: () => 'Hello World!'
};

// create an express server add a GraphQL endpoint
var app = express();
app.use('/graphql', express_graphql({
  schema: schema,
  rootValue: root,
  graphiql: true
}));

app.listen(4000, () => console.log('Express GraphQL Server Now Running on localhost:4000/graphql'));

スキーマは、GraphQLの型を定義している。 messageというクエリに対して、Hello World!を返す。

node server.js

localhost:4000/graphql にアクセスするとGraphiQLの画面がでてくる。

helloというGraphQLのクエリを投げると結果が返ってくる。

img01

なんとなく理解したのでクエリを増やしてみる。schemaとrootを次のように書き換えてみる

// GraphQLスキーマ言語を用いてスキーマを作成
var schema = buildSchema(`
  type Query {
    name: String
    age: Int
    school: String
  }
`);

//適当なデータ
var DB = {
  name: 'hoge',
  age: 30,
  school: 'papurika gakuen'
}

// rootは各APIエンドポイントにresolver関数を提供
var root = {
  name: () => DB.name,
  age: () => DB.age,
  school: () => DB.school
};

img02

必要なクエリを書いて叩けば、必要なだけ返ってくる(日本語難しい)。

ブラウザで表示する

上でやっていたことはGraphiQLのエディタ上でデータを見ていたので、htmlで静的サイトを作ってデータを見てみる。

publicディレクトリを作成してその中にindex.htmlを作成

index.html

<!DOCTYPE html>
<html lang="ja">
<head>
    <meta charset="UTF-8">
    <title>localhost:4000</title>
</head>
<body>
<div id="response"></div>
<script>
    fetch('/graphql', {
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Accept': 'application/json',
        },
        body: JSON.stringify({
            query: '{ name\n age\n school }'
        })
    }).then(function(res){
        return res.json();
    }).then(function(data){
        console.log('returned data: ', JSON.stringify(data));
        const h1 = document.getElementById('response');
        h1.textContent = JSON.stringify(data);
    })
</script>
</body>
</html>

Expressでhtmlを表示できるようにする

app.use(express.static('public'))    //add
app.listen(4000, () => console.log('localhost:4000'));

サーバーを再起動してlocalhost:4000にアクセスすると、レスポンスが表示されていることが確認できる。

img03

参考サイト


Profile picture

Written by ktpi2000.
ソフトウェアエンジニアをしています Twitter