Apollo
使い方
サーバの立ち上げ
一瞬で GraphQL サーバの立ち上げ & GraphQL 実行環境を作成できる。
code:shell
npm init -y
npm install --save apollo-server graphql
下記のような index.js を作成する。
code:javascript
const { ApolloServer, gql } = require('apollo-server');
/*** 型定義 ***/
// 型定義でデータの形式、形を定義する
const typeDefs = gql`
type Book {
title: String
author: String
}
# GraphQL クエリのルートは Query 型
type Query {
books: Book
}
`;
/*** リゾルバ ***/
// サンプルデータとして、単純な配列を用意する
const books = [
{
title: 'Harry Potter and the Chamber of Secrets',
author: 'J.K. Rowling',
},
{
title: 'Jurassic Park',
author: 'Michael Crichton',
},
];
const resolvers = {
Query: {
books: () => books,
},
};
/*** GraphQL サーバの起動 ***/
// 基本的には、ApolloServer の構築に必要なのは以下の2つ
// - 型定義 (typeDefs)
// - リゾルバ (resolvers)
const server = new ApolloServer({ typeDefs, resolvers });
server.listen().then(({ url }) => {
console.log(🚀 Server ready at ${url});
});
node で実行する。
code:shell
$ node index.js
🚀 Server ready at http://localhost:4000/
https://www.apollographql.com/docs/apollo-server/getting-started.html
アクセス
via GUI
Apollo サーバには GUI ツールが備わっており、起動後、http://localhost:4000/graphql にアクセスすると、GUI から GraphQL クエリを叩くことができる。
https://gyazo.com/0576a536d3750c96c438097ea0efc8ab
via HTTP
クエリを用意して encodeURI() あたりでエンコードし、クエリパラメータ query としてわたせばよい。
code:shell
$ curl http://localhost:4000/graphql\?query\=%7B%0A%20%20books%20%7B%0A%20%20%20%20title%0A%20%20%20%20author%0A%20%20%7D%0A%7D
{"data":{"books":{"title":"Harry Potter and the Chamber of Secrets","author":"J.K. Rowling"},{"title":"Jurassic Park","author":"Michael Crichton"}}}
https://www.apollographql.com/docs/apollo-server/requests.html
via Library
GraphQL Client 等を利用するのが良さそう。
https://www.apollographql.com/docs/react/#other-platforms
MySQL との連携
DataSurces としては REST API が存在するが、MySQL へのサポートはないようだ。
https://blog.apollographql.com/how-to-build-graphql-servers-87587591ded5
MySQL 特化の DataSource を作成する予定も今の所はないらしく、基本的には、既存の DataSource オブジェクトを独自に拡張するのが正攻法らしい。以下で議論されており、サンプルコードも存在する。
https://github.com/apollographql/apollo-server/issues/1458
気になるやつ。WebSocket 通信とか
http://lightbulbcat.hatenablog.com/entry/2018/02/06/025135
#GraphQL