Skip to content

Instantly share code, notes, and snippets.

@teckl
Created July 13, 2017 19:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save teckl/ecb7d0f5feeda82becc079cc8155fc99 to your computer and use it in GitHub Desktop.
Save teckl/ecb7d0f5feeda82becc079cc8155fc99 to your computer and use it in GitHub Desktop.
GraphQL API Server sample. refs http://graphql.org/code/#javascript
// http://graphql.org/code/#javascript
var express = require('express');
var graphqlHTTP = require('express-graphql');
var { buildSchema } = require('graphql');
var schema = buildSchema(`
type Shop {
id: ID!
name: String!
station: String
score: Int
}
type Blog {
id: Int!
name: String!
url: String!
title: String!
}
type Query {
hello: String
game: [String]
shops: [Shop]!
blogs(id:Int, name:String): [Blog]!
}
`);
// The root provides a resolver function for each API endpoint
var root = {
hello: () => {
return 'Hello world!';
},
game: () => {
return ['ゲームならIngressをやりましょう!!', 'もしくはPokémon GOでもいいですよ!!'];
},
shops: () => {
return [
{id: 1, name:'吉村家', station:'横浜駅', score:100 },
{id: 2, name:'武蔵家 日吉店', station:'日吉駅',score:90 },
{id: 3, name:'桂家', station:'方南町駅',score:95 },
{id: 4, name:'ラーメン大桜 向ヶ丘遊園店', station:'向ヶ丘遊園駅',score:90 },
{id: 5, name:'横浜家系 侍 渋谷店', station:'渋谷駅',score:75 },
];
},
blogs: (params) => {
console.log(params);
var blogs = [
{id:1, name:'info', url:'http://info.seesaa.net/', title:'Seesaaからのお知らせ' },
{id:2, name:'faq', url:'http://faq.seesaa.net/', title:'Seesaaブログ ヘルプセンター' },
{id:3, name:'customrecipe', url:'http://customrecipe.seesaa.net/', title:'Seesaaブログカスタムレシピ' },
{id:4, name:'ramen-diary', url:'http://ramen-diary.seesaa.net/', title:'らーめん日記' },
];
if (Object.keys(params).length > 0) {
return blogs.filter(function(rec){
if (typeof params.id != 'undefined') return params.id == rec.id;
if (typeof params.name != 'undefined') return params.name == rec.name;
});
} else {
return blogs;
}
}
};
var app = express();
app.use('/graphql', graphqlHTTP({
schema: schema,
rootValue: root,
graphiql: true,
}));
app.listen(4000);
console.log('Running a GraphQL API server at localhost:4000/graphql');
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment