This repository was archived by the owner on Mar 31, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
73 lines (62 loc) · 1.52 KB
/
server.js
File metadata and controls
73 lines (62 loc) · 1.52 KB
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
const express = require("express");
const graphqlHTTP = require("express-graphql");
const { buildSchema } = require("graphql");
// construct a schema, using graphql schema language
const schema = buildSchema(`
type RandomDie {
numSides: Int!
rollOnce: Int!
roll(numRolls: Int!): [Int]
message: String
}
type Query {
getDie(numSides: Int): RandomDie
quoteOfTheDay: String
random: Float!
rollThreeDice: [Int]
hello: String
}
`);
class RandomDie {
constructor(numSides) {
this.numSides = numSides;
}
rollOnce() {
return 1 + Math.floor(Math.random() * this.numSides);
}
roll({ numRolls }) {
const output = [];
for (let i = 0; i < numRolls; i++) {
output.push(this.rollOnce());
}
return output;
}
message() {
return "RollDie Class";
}
}
// the root providers a resolver function for each API endpoint
const root = {
quoteOfTheDay: () =>
Math.random() < 0.5 ? "Take it easy" : "Salvation lies within",
random: () => Math.random(),
rollThreeDice: () => {
return [1, 2, 3].map(_ => 1 + Math.floor(Math.random() * 6));
},
hello: () => "Hello, Wolrd",
getDie: ({ numSides }) => new RandomDie(numSides || 6)
};
// express server
const app = express();
app.use("/static/", express.static("public"));
app.use(
"/graphql",
graphqlHTTP({
schema,
rootValue: root,
graphiql: true
})
);
app.listen(4000, () =>
console.log("Running a graphql API server at http://localhost:4000/graphql")
);