-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathserver.js
More file actions
71 lines (60 loc) · 2.34 KB
/
server.js
File metadata and controls
71 lines (60 loc) · 2.34 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
const {ApolloServer, AuthenticationError} = require('apollo-server');
const {makeExecutableSchema} = require("graphql-tools");
const {initGlobalDataSync} = require('./data');
const typeDefs = require('./graphql/typedefs');
const resolvers = require('./graphql/resolvers');
const RequiresPersonalScope = require('./graphql/directives');
const config = require('./config');
const PORT = process.env.PORT || 4000;
/*
The ApolloServer is started by creating a schema that is
defined by the type definitions (typeDefs), the resolvers that
fetch the data for those types, and the subscriptions definition with
the behavior to execute upon the onConnect event. Authentication to the
API is handled by the function associated with the schema's
context field.
*/
const subscriptions = require('./graphql/subscriptions');
const schema = makeExecutableSchema({
typeDefs,
resolvers,
schemaDirectives: {
requiresPersonalScope: RequiresPersonalScope
}
});
const server = new ApolloServer({
subscriptions,
schema,
context: ({req, res}) => {
if(req){
const token = config.getToken(req);
if (req.body.operationName === 'IntrospectionQuery'){
const accessTime = new Date();
console.log({operation: req.body.operationName, token, accessTime});
return req;
}
if(!config.canAccess(token)){
const err = new AuthenticationError(token);
console.log(err);
throw err;
}else{
const accessTime = new Date();
console.log({operation: req.body.operationName, token, accessTime});
return req;
}
}
}
});
//Initialize the data collections globally by calling initGlobalDataSync()
//to load the data into the global environment variables
initGlobalDataSync();
// The server `listen` method launches a web-server and a
// subscription server
server.listen(PORT).then(({url, subscriptionsUrl}) => {
process.env.SERVER_CONFIG = JSON.stringify({serverUrl: url, subscriptionsUrl});
console.log(`Starting servers at ${new Date()}`);
console.log(`🚀 Server ready at ${url}`);
console.log(`🚀 Subscriptions ready at ${subscriptionsUrl}`)
});
//Export the server to make it available to unit and API tests
module.exports = {server};