GraphQL

上部読み込み

const express = require('express');
const {graphqlHTTP} = require('express-graphql');
const {buildSchema} = require('graphql');

取得

スキーマ

const schema = buildSchema(`
  type Hoge{
    param1:Int!
    param2:Int!
    action(param3:Int!):[Int]
  }
  type Query{
    getHoge(param1:Int):Hoge
  }
`);

※スカラー型
String … 文字列型
Int … 整数型
Float … 浮動小数点型
Boolean … 論理型
ID … ID型(実態はStringだがユニークなもの)
配列は [] で囲む
!がつくとフィールドがnull にならない
[String] … リストも値もnullの可能性がある
[String!] … リストはnullの可能性があるが、値はnullではない
[String]! … 値はnullの可能性があるが、リストはnullではない
[String!]! … リストも値もnullではない

リゾルバ関数

class Hoge {
  constructor(param1){
    this.param1 = param1;
  }
  param2(){
    return 1 + Math.floor(Math.random() * this.param1);
  }
  action({param3}){
    let output = [];
    for(let i = 0; i<param3;i++){
      output.push(2);
    }
    retrun output;
  }
}
const root = {
  getHoge:({param1})=>{
    return new Hoge(param1);
  }
};

Expressでサーバたてる

const app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));

app.listen(4000);

GraphQLをたたく

query{
  getHoge(param1:3){
    param1
    param2
    action(param3:5)
  }
}

↓ レスポンス

{
  "data":{
    "param1":3,
    "param2":3,
    "action":[2,2,2,2,2]
  }
}

更新

スキーマ

const schema = buildSchema(`
  type HogeInput{
    content:String
    user_name:String
  }
  type Hoge{
    id:ID!
    content:String
    user_name:String
  }
  type Query{
    getHoge(id:ID!):Hoge
  }
  type Mutaion{
    createHoge(input:HogeInput):Hoge
    updateHoge(id:ID!,input:HogeInput):Hoge
  }
`);

リゾルバ関数

class Hoge {
  constructor(id, {content,user_name}){
    this.id = id;
    this.content = content;
    this.user_name = user_name
  }
}
let kariDb={};
const root = {
  getHoge:({id})=>{
    if(!kariDb[id]){
      throw new Error('IDないよ')
    }
    return new Hoge(id, kariDb[id]);
  },
  createHoge:({input}) => {
    const id = require('crypto').randomBytes(10).toString('hex');
    kariDb[id]=input;
    return new Hoge(id,input);
  },
  updateHoge:({id,input})=>{
    if(!kariDb[id]){
      throw new Error('IDないよ')
    }
    kariDb[id]=input;
    return new Hoge(id,input);
  }
};

Expressでサーバたてる

const app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));

app.listen(4000);

GraphQLをたたく

mutation{
  createHoge(input:{
    content:'aa'
    user_name:'namae'
  }){
    id
    content
    user_name
  }
}

↓ レスポンス

{
  "data":{
    createHoge:{
      "id":"dasfdasfasdfasd",
      "content":"aa",
      "user_name":"namae"
  }
}