-
Notifications
You must be signed in to change notification settings - Fork 7
/
index.js
90 lines (79 loc) · 2.12 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
import express from 'express';
import bodyParser from 'body-parser';
import { graphiqlExpress, graphqlExpress } from 'graphql-server-express';
import { makeExecutableSchema } from 'graphql-tools';
import cors from 'cors';
import jwt from 'jsonwebtoken';
import { createServer } from 'http';
import { execute, subscribe } from 'graphql';
import { SubscriptionServer } from 'subscriptions-transport-ws';
import joinMonsterAdapt from 'join-monster-graphql-tools-adapter';
import typeDefs from './schema';
import resolvers from './resolvers';
import models from './models';
import { refreshTokens } from './auth';
import joinMonsterMetadata from './joinMonsterMetadata';
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
joinMonsterAdapt(schema, joinMonsterMetadata);
const SECRET = 'aslkdjlkaj10830912039jlkoaiuwerasdjflkasd';
const app = express();
const addUser = async (req, res, next) => {
const token = req.headers['x-token'];
console.log(token);
if (token) {
try {
const { user } = jwt.verify(token, SECRET);
req.user = user;
} catch (err) {
const refreshToken = req.headers['x-refresh-token'];
const newTokens = await refreshTokens(token, refreshToken, models, SECRET);
if (newTokens.token && newTokens.refreshToken) {
res.set('Access-Control-Expose-Headers', 'x-token, x-refresh-token');
res.set('x-token', newTokens.token);
res.set('x-refresh-token', newTokens.refreshToken);
}
req.user = newTokens.user;
}
}
next();
};
app.use(cors('*'));
app.use(addUser);
app.use(
'/graphiql',
graphiqlExpress({
endpointURL: '/graphql',
subscriptionsEndpoint: 'ws://localhost:3030/subscriptions',
}),
);
app.use(
'/graphql',
bodyParser.json(),
graphqlExpress(req => ({
schema,
context: {
models,
SECRET,
user: req.user,
},
})),
);
const server = createServer(app);
models.sequelize.sync().then(() =>
server.listen(3030, () => {
new SubscriptionServer(
{
execute,
subscribe,
schema,
},
{
server,
path: '/subscriptions',
},
);
}),
);