GraphQLはFacebookが開発しているクライアントとサーバー間のデータのやり取りを容易に記述するためのクエリ言語です。Reactでの開発にRelayを使いたいなと思っていますが、GraphQL周りの知識が乏しすぎるので、勉強がてらGraphQLのドキュメントのGetting Startedの部分を和訳してみました。せっかくなのでブログにもアップしておきます。誤訳などもあるかと思いますが、Google翻訳よりはマシだと参考にしていただければと思います。

当記事は以下のページを日本語に翻訳したものとなります。
Getting Started
Let’s build a basic GraphQL server from scratch using graphql-js.
graphql−jsを使って一から初歩的なGraphQLサーバーを構築しましょう。
Our server’s schema will be simple: it will have one type, a User, with two fields, id and name. (For an example of a more complex server, check out the Walkthrough.)
サーバーのスキーマはシンプルです。Userという1つのtypeと、idとnameの2つのフィールドを持ちます。(より複雑なサーバーの例は、Walkthroughをチェックしてください。)
Setup
Start by making a folder for your demo server:
デモサーバー用のフォルダを作成してスタートしましょう。
mkdir graphql-demo
cd graphql-demo
The example server requires Node.js and three additional packages for our server:
1. graphql, the reference implementation of GraphQL in JavaScript.
2. express, a basic web framework.
3. express-graphql, an express middleware that exposes a GraphQL server.
この事例のサーバーはNode.jsと3つの追加パッケージが必要となります。
- graphql: JavaScriptにおけるGraphQLのリファレンス実装
- express: 基本的なWebフレームワーク
- express-graphql: GraphQLサーバーを利用するためのexpressのミドルウェア
Install these three packages using npm:
npmを使って3つのパッケージをインストールします。
npm init -f
npm install graphql express express-graphql --save
Data
Our server will consist of two files, data.json and index.js. To create these files, run
このサーバーはdata.jsonとindex.jsの2つのファイルからなります。以下のコマンドを実行して、これらのファイルを作成しましょう。
touch data.json
touch index.js
Now define the user data in data.json:
まず、data.jsonの中にユーザーデータを定義しましょう。
{
"1": {
"id": "1",
"name": "Dan"
},
"2": {
"id": "2",
"name": "Marie"
},
"3": {
"id": "3",
"name": "Jessie"
}
}
Server
Next you’ll create a very basic GraphQL schema to describe the data; you can then allow this schema to be queried over HTTP.
次に、データを記述するためにとても初歩的なGraphQLスキーマを作成しましょう。そうすることで、HTTPを通してこのスキーマにクエリを投げることができるようになります。
Insert the following into index.js (and be sure to read the comments!):
以下をindex.jsに記述します。(必ずコメントを読んでください。)
// Import the required libraries
// 必要なライブラリをインポートする
var graphql = require('graphql');
var graphqlHTTP = require('express-graphql');
var express = require('express');
// Import the data you created above
// 上で作成したデータをインポートする
var data = require('./data.json');
// Define the User type with two string fields: `id` and `name`.
// The type of User is GraphQLObjectType, which has child fields
// with their own types (in this case, GraphQLString).
// 2つの文字列フィールド(`id`と`name`)を持ったUser型を定義します。
// Userの型は、自分の型(今回の場合はGraphQLString)を持つ子フィールドを
// 持ったGraphQLObjectTypeとなります。
var userType = new graphql.GraphQLObjectType({
name: 'User',
fields: {
id: { type: graphql.GraphQLString },
name: { type: graphql.GraphQLString },
}
});
// Define the schema with one top-level field, `user`, that
// takes an `id` argument and returns the User with that ID.
// Note that the `query` is a GraphQLObjectType, just like User.
// The `user` field, however, is a userType, which we defined above.
// ひとつのtop-levelのフィールド`user`を持ったスキーマを定義します。
// それは引数`id`を取り、そのIDを持ったUserを返します。
// `query`はUserと同じようにGraphQLObjectTypeとなることに注意してください。
// しかしながら`user`フィールドは、上で定義したuserTypeとなります。
var schema = new graphql.GraphQLSchema({
query: new graphql.GraphQLObjectType({
name: 'Query',
fields: {
user: {
type: userType,
// `args` describes the arguments that the `user` query accepts
// `args`は`user`クエリが許可する引数を記述します。
args: {
id: { type: graphql.GraphQLString }
},
// The resolve function describes how to "resolve" or fulfill
// the incoming query.
// In this case we use the `id` argument from above as a key
// to get the User from `data`
// resolve関数は受け取ったクエリの解決方法
// または実行方法を記述します。
// 今回は、`data`からUserをゲットするために、
// keyとして上記の引数`id`を使います。
resolve: function (_, args) {
return data[args.id];
}
}
}
})
});
express()
.use('/graphql', graphqlHTTP({ schema: schema, pretty: true }))
.listen(3000);
console.log('GraphQL server running on http://localhost:3000/graphql');
That’s it – your basic GraphQL server is done! Start it by running
以上で、初歩的なGraphQLサーバーは完成です。起動してみましょう。
node index.js
The server should announce that it is running at localhost:3000/graphql. If you navigate to this address you will receive this notice:
サーバーはlocalhost:3000/graphqlで起動していると通知するようになっています。あなたがこのアドレスを入力したら、まず以下の警告が出るでしょう。
{
"errors": [
{
"message": "Must provide query string."
}
]
}
We know our server is running – now we just need to send it a query!
サーバーが起動しているということがわかりまた。さっそくクエリを送ってみましょう。
Queries
Below is a very simple query you can make against your schema. To the right is the result your server should deliver. Take a moment to read the query and the result. Note that the result and query have the same basic “shape”: whereas the result is JSON key-value pairs, the query is the just the keys.
以下は、スキーマに対して作ったとてもシンプルなクエリです。下側はサーバーが返す結果となります。クエリと結果をじっくり眺めてみましょう。結果とクエリはどちらも同じ基本的な「形」となっていることに注目してください。結果の方はkeyとvalueを持ったJSONですが、クエリの方はkeyだけとなっています。
{
user(id: "1") {
name
}
}
{
"data": {
"user": {
"name": "Dan"
}
}
}
You can edit the above query; the result will automatically update when you do. If you make a syntax mistake it will be underlined in red. Try replacing id: “1” with id: “2”; replace name with id or with name id.
上のクエリを変更可能です。変更すると結果は自動的にアップデートされます。構文にミスがあった場合は、赤いアンダーラインがつきます。実際にid: “1”をid: “2”に置き換えてみましょう。nameをidまたはname idに置き換えましょう。
Now that you know what a GraphQL query looks like you can query your own server. Let’s start with the simple query
GraphQLのクエリが自分のサーバーでクエリを投げるのと同じようなものだとわかったことでしょう。さっそくシンプルなクエリを投げてみましょう。
{
user(id: "1") {
name
}
}
Remove all the whitespace in the query: {user(id:”1″){name}} (whitespace is optional in GraphQL). You can send this to your server via a GET request with a URL query string: http://localhost:3000/graphql?query={user(id:”1″){name}} – the server should respond with
{user(id:”1″){name}}のようにクエリのすべてのホワイトスペースを取り除きます(ホワイトスペースはGraphQLでは任意となります)。http://localhost:3000/graphql?query={user(id:”1″){name}}のようにURLにクエリ文字列をつけてGETリクエストを通してサーバーに送ります。サーバーは以下のようにレスポンスを返します。{
"data": {
"user": {
"name": "Dan"
}
}
}
To be standards compliant, the query itself should be URL-encoded. If you received a GraphQL Syntax Error from the above query, try replacing it with the URL-encoded version: %7Buser(id:%221%22)%7Bname%7D%7D. (You can URL-encode any string in JavaScript with the global encodeURI function.)
標準に準拠するために、クエリ自身はエンコードされたURLであるべきです。上記のクエリからGraphQLの構文エラーが返ってきた際は、エンコードされたURL: %7Buser(id:%221%22)%7Bname%7D%7Dに置き換えてみてください。(JavaScriptの文字列はグローバルのencodeURI関数でURLエンコードが可能です。)
Congratulations! You’ve built your first GraphQL server. Try different queries, or changing the data, or even adding new fields to the schema.
おめでとうございます!初めてのGraphQLサーバーを構築できました。他のクエリにしたり、データを変えたり、スキーマに新しいフィールドを追加したりしてお試しください。
まとめ
以上、GraphQLのGetting Startedの日本語訳となります。
馴染みのないクエリ、GraphQLサーバーの構築など、GraphQLを扱うのは難しそうなイメージがありましたが、実際にこの「Getting Started」の内容通りにやってみると、基本的な部分はそれなりに理解できるかなと思います。
自分としては、Relayを使ったReactとの連携や、データベースとの連携など、その辺りがまだ詳しくわかっていなかったりします。他のドキュメントなどにも目を通して、もうちょっと勉強してから、またこちらのブログで紹介できたらと思っています。
コメント