Node.js + ExpressでGraphQLを試す

この記事では、以下を参考にGraphQL.jsを試してみます。

実行環境

$ sw_vers
ProductName:    Mac OS X
ProductVersion: 10.15.2
BuildVersion:   19C57
$ node -v
v13.7.0
$ npm -v
6.13.4

プロジェクト作成 + graphqlインストール

$ npm init -y
$ npm install graphql --save

server.js作成

var { graphql, buildSchema } = require('graphql');

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// The root provides a resolver function for each API endpoint
var root = {
  hello: () => {
    return 'Hello world!';
  },
};

// Run the GraphQL query '{ hello }' and print out the response
graphql(schema, '{ hello }', root).then((response) => {
  console.log(response);
});

スキーマ言語docs

実行

$ node server.js 
{ data: [Object: null prototype] { hello: 'Hello world!' } }
  • Tutorial通りに実行してみたが、レスポンスにnull prototypeも含まれてしまった。(なにか必要なのだろうか..)

Expressインストール

$ npm install express express-graphql graphql --save

server.js更新

expressを使うようにserver.jsを更新していきます。

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

// Construct a schema, using GraphQL schema language
var schema = buildSchema(`
  type Query {
    hello: String
  }
`);

// The root provides a resolver function for each API endpoint
var root = {
  hello: () => {
    return 'Hello world!';
  },
};

var app = express();
app.use('/graphql', graphqlHTTP({
  schema: schema,
  rootValue: root,
  graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at http://localhost:4000/graphql');

GraphQLサーバー起動、リクエス

$ node server.js
Running a GraphQL API server at http://localhost:4000/graphql

f:id:kimai007:20200202001904p:plain