Node.js + ExpressでGraphQLを試す
この記事では、以下を参考にGraphQL.jsを試してみます。
- Getting Started With GraphQL.js | GraphQL.js Tutorial
- Running an Express GraphQL Server | GraphQL.js Tutorial
実行環境
$ 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); });
- buildSchema
- GraphQLSchemaオブジェクトを生成
- buildschema
- graphql
- 定義されたschemaに対して、'{ hello }' をリクエスト
- APIルートにマッピングされたresolverで 'Hello World'を返す
- graphql
※ スキーマ言語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
- http://localhost:4000/graphqlにアクセス
- GraphiQLで
{ hello }
をリクエストすると以下の結果が得られたことを確認。