-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy path2.apollo.js
More file actions
95 lines (79 loc) · 2.44 KB
/
2.apollo.js
File metadata and controls
95 lines (79 loc) · 2.44 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
import { ApolloServer } from '@apollo/server';
import { expressMiddleware } from '@apollo/server/express4';
import { ApolloServerPluginDrainHttpServer } from '@apollo/server/plugin/drainHttpServer'
import { ApolloServerPluginCacheControl } from '@apollo/server/plugin/cacheControl';
import express from 'express';
import http from 'http';
import cors from 'cors';
import bodyParser from 'body-parser';
const typeDefs = `#graphql
type Query {
hello: String
"""
Chosen by fair dice roll
**Guaranteed** to be [random](https://xkcd.com/221/)!
"""
rollDice(
"Amount of sides of the die"
numSides: Int
): Int
}
`;
const resolvers = {
Query: {
hello: () => 'Apollo, touchdown',
rollDice: (parent, args, contextValue, info) => {
console.log('Roll Dice:');
console.log('parent', parent);
console.log('args', args);
console.log('context', contextValue);
// The info object can be parsed to select only those fields from mongo:
// https://github.com/robrichard/graphql-fields
// https://github.com/du5rte/graphql-mongodb-projection
console.log('info', info);
return 4;
}
},
};
const app = express();
const httpServer = http.createServer(app);
const server = new ApolloServer({
typeDefs,
resolvers,
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
ApolloServerPluginCacheControl({
// Cache everything for 1 second by default.
defaultMaxAge: 1,
// Don't send the `cache-control` response header.
calculateHttpHeaders: false,
}),
// Custom Plugin
{
// More server lifecycle events:
// https://www.apollographql.com/docs/apollo-server/v2/integrations/plugins/#apollo-server-event-reference
// requestDidStart, parsingDidStart, willSendResponse, didEncounterErrors, ...
async serverWillStart() {
console.log('Starting server!');
return {
async serverWillStop() {
console.log('Stopping server!');
},
};
},
},
],
});
await server.start();
app.use(
cors(),
bodyParser.json(),
expressMiddleware(server, {
context: async ({ req, res }) => {
return {lang: req.headers['accept-language'] || 'nl'}
},
}),
);
await new Promise(resolve => httpServer.listen({ port: 4000 }, resolve));
console.log('🚀 GraphQL Apollo server listening to port 4000');
console.log('Check http://localhost:4000 for the Apollo GUI');