GraphQL.jsでMutation

2018-07-27T00:00:00+09:00 JavaScript GraphQL

graphql.jsを使ってMutationをやってみる

そもそもMutationってなんぞ?

雑にいうとGraphQL上での更新系を扱うクエリーみたいなものっぽい

graphql.schema

schema {
  query: PostSchema
  mutation: PostMutations
}

type Post {
  title: String
  permalink: String
}

type PostMutations {
  createPost(title: String): Post
}

type PostSchema {
  posts: [Post]
}

このスキーマ定義を読み取ってGraphQLSchemaを生成するのに使う

script.js

import { buildSchema, graphql } from "graphql";
import fs from "fs";

const postsList = [
  { title: "A" },
  { title: "B" },
  { title: "C" }
];

const query = {
  posts: () => { return postsList; }
};

const mutation = {
  createPost: (args) => {
    const data = { title: args.title };
    postsList.push(data);
    return data;
  }
};

const schemaData = fs.readFileSync("graphql.schema").toString();
const schema = buildSchema(schemaData);
const root = { ...query, ...mutation };

graphql(schema, 'mutation { createPost(title: "hoge") { title }}', root).then(res => {
  console.log(res.data);
});

graphql(schema, "{ posts { title }}", root).then(res => {
  for (var data of res.data.posts) {
    console.log(data);
  }
});

でスキーマ定義からcreatePostとなる実体の処理はrootValue(graphqlの第3引数?)に入れればいいらしい。あとはgraphqlを使って

mutation { createPost(省略) }

で呼び出せばいい

めんどくさいのでとりあえずやれば分かるんじゃね

備考: スキーマ定義を使わずにgraphql.jsだけでやる方法

import {
  GraphQLObjectType,
  GraphQLString,
  GraphQLList,
  GraphQLInt,
  GraphQLSchema,
  graphql
} from "graphql";

const Post = new GraphQLObjectType({
  name: "Post",
  fields: () => ({
    title: { type: GraphQLString },
    permalink: { type: GraphQLString }
  })
});


const Query = new GraphQLObjectType({
  name: "PostSchema",
  fields: () => ({
    posts: { type: new GraphQLList(Post) }
  })
});

const postsList = [
  { title: "A" },
  { title: "B" },
  { title: "C" }
];

const root = {
  posts: () => { return postsList; }
};

const Mutation = new GraphQLObjectType({
  name: "PostMutations",
  fields: () => ({
    createPost: {
      type: Post,
      args: {
        title: { type: GraphQLString }
      },
      resolve: (_, args) => {
        const data = { title: args.title };
        postsList.push(data);
        return data;
      }
    }
  })
});

const schema = new GraphQLSchema({
  query: Query,
  mutation: Mutation
});

graphql(schema, 'mutation { createPost(title: "hoge") { title }}', root).then(res => {
  console.log(res);
});

graphql(schema, "{ posts {title} }", root).then(res => {
  for (var data of res.data.posts) {
    console.log(data);
  }
});

終わり

GraphQLスキーマを定義して利用する方法