-
Notifications
You must be signed in to change notification settings - Fork 13
/
server.js
125 lines (115 loc) · 2.42 KB
/
server.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
var express = require('express');
var express_graphql = require('express-graphql');
var {
buildSchema
} = require('graphql');
var path = require('path');
// GraphQL schema
var schema = buildSchema(`
type Query {
hello: String
restaurant(id: Int!): Restaurant
restaurants(type: String, stars: Int): [Restaurant]
},
type Restaurant {
id: Int
name: String
type: String
map: String
stars: Int
}
`);
var restaurantData = [
{
id: 1,
name: 'Le Bernardin',
type: 'French',
stars: 3,
map: 'https://goo.gl/maps/BoBB89qhUtH2',
},
{
id: 2,
name: 'Masa',
type: 'Japanese',
stars: 3,
map: 'https://goo.gl/maps/XaQKVwjgfsR2',
},
{
id: 3,
name: 'Aquavit',
type: 'European',
stars: 2,
map: 'https://goo.gl/maps/DVL1jGi5zD82',
},
{
id: 4,
name: 'Gabriel Kreuther',
type: 'French',
stars: 2,
map: 'https://goo.gl/maps/RQiTLZGGSdB2',
},
{
id: 5,
name: 'Babbo',
type: 'Italian',
stars: 1,
map: 'https://goo.gl/maps/TsbD8Z3WoRo',
},
{
id: 6,
name: 'Bouley at Home',
type: 'American',
stars: 1,
map: 'https://goo.gl/maps/LyGNUW2gbtk',
},
{
id: 7,
name: 'Hirohisa',
type: 'Japanese',
stars: 1,
map: 'https://goo.gl/maps/RpA3ahYrf9T2',
},
{
id: 8,
name: 'Junoon',
type: 'Indian',
stars: 1,
map: 'https://goo.gl/maps/MCqxKiApEQS2',
}
]
function sleep(ms){
return new Promise(resolve => {
setTimeout(resolve,ms)
})
}
// The root provides a resolver function for each API endpoint
var root = {
restaurant: (args) => {
var id = args.id;
return restaurantData.filter(restaurant => {
return restaurant.id == id;
})[0];
},
restaurants: async (args) => {
var result = restaurantData;
if (args.type) {
result = result.filter(restaurant => restaurant.type === args.type);
}
if (args.stars) {
result = result.filter(restaurant => restaurant.stars === args.stars);
}
// Simulated long latency of complex queries.
await sleep(3000)
return result;
}
};
// Create an express server and a GraphQL endpoint
var app = express();
app.use('/graphql', express_graphql({
schema: schema,
rootValue: root,
graphiql: true
}));
app.use(express.static('public'))
app.listen(4000, () => console.log(
'Serving localhost:4000/ for web, /graphql for GraphQL API endpoint.'));