forked from apollographql/meteor-integration
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain-server.js
78 lines (60 loc) · 2.1 KB
/
main-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
import './check-npm.js';
import { apolloExpress, graphiqlExpress } from 'apollo-server';
import bodyParser from 'body-parser';
import express from 'express';
import { Meteor } from 'meteor/meteor';
import { WebApp } from 'meteor/webapp';
import { check } from 'meteor/check';
import { Accounts } from 'meteor/accounts-base';
import { _ } from 'meteor/underscore';
const defaultConfig = {
path: '/graphql',
maxAccountsCacheSizeInMB: 1,
graphiql : Meteor.isDevelopment,
graphiqlPath : '/graphiql',
graphiqlOptions : {}
};
export const createApolloServer = (givenOptions, givenConfig) => {
let config = _.extend(defaultConfig, givenConfig);
const graphQLServer = express();
// GraphQL endpoint
graphQLServer.use(config.path, bodyParser.json(), apolloExpress(async (req) => {
let options,
user = null;
if (_.isFunction(givenOptions))
options = givenOptions(req);
else
options = givenOptions;
options = Object.assign({}, options);
// Get the token from the header
if (req.headers.authorization) {
const token = req.headers.authorization;
check(token, String);
const hashedToken = Accounts._hashLoginToken(token);
// Get the user from the database
user = await Meteor.users.findOne(
{"services.resume.loginTokens.hashedToken": hashedToken},
{fields: {
_id: 1,
'services.resume.loginTokens.$': 1
}});
if (user) {
const expiresAt = Accounts._tokenExpiration(user.services.resume.loginTokens[0].when);
const isExpired = expiresAt < new Date();
if (!isExpired) {
if (!options.context) {
options.context = {};
}
options.context.userId = user._id;
}
}
}
return options;
}));
// Start GraphiQL if enabled
if (config.graphiql) {
graphQLServer.use(config.graphiqlPath, graphiqlExpress(_.extend(config.graphiqlOptions, {endpointURL : config.path})));
}
// This binds the specified paths to the Express server running Apollo + GraphiQL
WebApp.connectHandlers.use(Meteor.bindEnvironment(graphQLServer));
};