-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
62 lines (56 loc) · 1.33 KB
/
app.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
import express from 'express';
import { ApolloServer } from 'apollo-server-express';
import { formatError } from 'apollo-errors';
import jwt from 'jsonwebtoken';
import 'dotenv/config';
import typeDefs from './src/schema';
import resolvers from './src/resolvers';
import directives from './src/directives';
const app = express();
const { PORT } = process.env;
const server = new ApolloServer({
typeDefs,
resolvers,
schemaDirectives: directives,
context: ({ req }) => {
let user = {};
let token = '';
if (req.headers.authorization) {
const splitToken = (req.headers.authorization || '').split(' ')[1];
if (splitToken) {
token = splitToken;
try {
user = jwt.verify(splitToken, 'Secret');
} catch (e) {
console.log('user verify error');
console.log(e);
}
}
}
return {
token,
user,
};
},
formatError,
introspection: true,
playground: true,
});
server.applyMiddleware({
app,
path: '/graphql',
cors: {
origin: '*',
credentials: true,
methods: ['GET', 'PUT', 'POST', 'DELETE', 'PATCH', 'OPTIONS'],
allowedHeaders: [
'Origin',
'Content-Type',
'Accept',
'Authorization',
],
},
});
app.listen({ port: PORT }, () => {
console.log('Apollo Server on http://localhost:8000/graphql');
});