-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
117 lines (103 loc) · 3.53 KB
/
index.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
/* **************************************************************************************
WARNING: DO NOT EDIT this file except from inside the graphql-starter-template repository.
Changes made to this file inside child repos will NOT be reflected in the parent source
template repository, and will interfere with the ability to upgrade common code from
the template repository.
***************************************************************************************** */
const { ApolloServer } = require('apollo-server-express');
const express = require('express');
const session = require('express-session');
const cors = require('cors');
const cache = require('coa-web-cache');
const { checkLogin, initializeContext, getUserInfo } = require('coa-web-login');
const MemoryStore = require('memorystore')(session);
const PgSession = require('connect-pg-simple')(session);
require('dotenv').config();
const apiConfig = require('./api/config');
const getDbConnection = require('./common/db');
const GRAPHQL_PORT = process.env.PORT || 4000;
if (apiConfig.enableEmployeeLogins) {
getDbConnection('mds'); // Initialize the connection.
}
const app = express();
let sessionCache = null;
const prunePeriod = 86400000; // prune expired entries every 24h
const sessionCacheMethod = process.env.session_cache_method || 'memory';
if (sessionCacheMethod === 'memory') {
sessionCache = new MemoryStore({
checkPeriod: prunePeriod,
});
} else if (sessionCacheMethod === 'pg') {
sessionCache = new PgSession({
pool: getDbConnection('mds'),
schemaName: 'aux',
ttl: prunePeriod,
});
} else {
throw new Error(`Unknown caching method ${sessionCacheMethod}`);
}
// Initialize session management
app.use(session({
name: process.env.sessionName,
secret: process.env.sessionSecret,
resave: false,
saveUninitialized: true,
store: sessionCache,
cookie: {
httpOnly: true,
secure: 'auto',
maxAge: 1000 * 60 * 60 * 24 * process.env.maxSessionDays,
},
}));
// Set up CORS
const origin = true;
const corsOptions = {
origin,
credentials: true,
};
app.use(cors(corsOptions));
// Check whether the user is logged in
app.use((req, res, next) => {
const sessionId = req.session.id;
cache.get(sessionId)
.then((cData) => {
let ensureInCache = Promise.resolve(null);
const cachedContext = cData || initializeContext();
if (!cData) {
ensureInCache = cache.store(sessionId, cachedContext);
}
ensureInCache.then(() => {
checkLogin(sessionId, cachedContext, cache)
.then(() => getUserInfo(sessionId, cachedContext, apiConfig, cache, getDbConnection('mds')))
.then((uinfo) => {
req.session.employee_id = uinfo.id;
return next();
})
.catch((err) => {
const error = new Error(err.toString().substring(6));
error.httpStatusCode = 403;
error.stack = null;
return next(error);
});
});
});
});
// Add in any middleware defined by the API
require('./api').middlewares.forEach((m) => { app.use(m); });
// Now configure and apply the GraphQL server
const typeDefs = require('./schema');
const resolvers = require('./resolvers');
const server = new ApolloServer({
typeDefs,
resolvers,
context: ({ req }) => ({
sessionId: req.session.id,
session: req.session,
cache,
}),
});
server.applyMiddleware({ app, cors: corsOptions });
// And off we go!
app.listen({ port: GRAPHQL_PORT }, () => {
console.log(`Server ready at http://localhost:${GRAPHQL_PORT}${server.graphqlPath}`);
});