-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
82 lines (78 loc) · 2.63 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
import { ApolloServer } from 'apollo-server-express';
import { ApolloServerPluginDrainHttpServer, AuthenticationError } from 'apollo-server-core';
import { mergeResolvers, mergeTypeDefs } from '@graphql-tools/merge';
import { loadFilesSync } from '@graphql-tools/load-files';
import path from 'path';
import express from 'express';
import http from 'http';
import jwt, { TokenExpiredError } from 'jsonwebtoken';
import cors from 'cors';
import models, { sequelize } from './models';
import './permissions';
import { refreshToken } from './auth';
async function assertDatabaseConnectionOk() {
console.log('Checking database connection...');
try {
await sequelize.authenticate();
console.log('Database connection OK!');
} catch (error) {
console.log('Unable to connect to the database:');
console.log(error.message);
process.exit(1);
}
}
const SECRET = 'asiodfhoi1hoi23jnl1kejd';
const SECRET2 = 'asiodfhoi1hoi23jnl1kejasdjlkfasdd';
const persistUser = async (req, res, next) => {
const token = req.headers.authorization || '';
const refreshtoken = req.headers.refreshtoken || '';
if (token) {
try {
const { userId } = jwt.verify(token, SECRET);
req.userId = userId;
} catch (error) {
if (error instanceof TokenExpiredError) {
const { token, newRefreshToken } = await refreshToken(refreshtoken, sequelize.models.User, SECRET, SECRET2);
res.set('Access-Control-Expose-Headers', 'authorization,refreshoken');
res.set({
authorization: token,
refreshoken: newRefreshToken,
});
}
}
}
next();
};
async function startApolloServer() {
await assertDatabaseConnectionOk();
const app = express();
const httpServer = http.createServer(app);
const server = new ApolloServer({
typeDefs: mergeTypeDefs(loadFilesSync(path.join(__dirname, './schema'))),
resolvers: mergeResolvers(loadFilesSync(path.join(__dirname, './resolvers'))),
csrfPrevention: true,
plugins: [ApolloServerPluginDrainHttpServer({ httpServer })],
context: ({ req, res }) =>
// console.log();
// res.set('Access-Control-Expose-Headers', 'authorization');
// res.setHeader('authorization', 'asd');
// console.log(res.headersSent);
({
models,
userId: req.userId,
secret: SECRET,
secret2: SECRET2,
res,
})
,
});
await server.start();
app.use(cors('*'));
app.use(persistUser);
server.applyMiddleware({ app });
models.sequelize.sync({}).then(() => {
httpServer.listen({ port: 4000 });
console.log(`🚀 Server ready at http://localhost:4000${server.graphqlPath}`);
});
}
startApolloServer();