-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
99 lines (85 loc) · 2.53 KB
/
Copy pathserver.js
File metadata and controls
99 lines (85 loc) · 2.53 KB
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
const { createServer } = require('http');
const express = require('express');
const {ApolloServerPluginDrainHttpServer,ApolloServerPluginLandingPageLocalDefault, AuthenticationError,} = require("apollo-server-core");
const { makeExecutableSchema } = require('@graphql-tools/schema');
const { WebSocketServer } = require('ws');
const { useServer } = require('graphql-ws/lib/use/ws');
const { ApolloServer } = require('apollo-server-express');
const {sequelize} = require('./models')
const jwt = require('jsonwebtoken')
require('dotenv').config
const resolvers = require('./graphql/Resolvers')
const typeDefs = require('./graphql/typeDefs');
(async function() {
const app = express();
const httpServer = createServer(app);
const contextMiddleware = require('./util/contextMiddleware')
const schema = makeExecutableSchema({
typeDefs,
resolvers,
});
const wsServer = new WebSocketServer({
server: httpServer,
path: '/graphql',
});
const findUser = async (authToken) => {
const token = authToken.split('Bearer ')[1]
const verify = await jwt.verify(token, process.env.TOKEN_SECRET, (err, decodedToken) => {
if(err){
console.log('err')
}
return decodedToken
})
return verify
};
const getDynamicContext = async (ctx, msg, args) => {
if (ctx.connectionParams.Authorization) {
const currentUser = await findUser(ctx.connectionParams.Authorization);
return { currentUser };
}
// Let the resolvers know we don't have a current user so they can
// throw the appropriate error
return { currentUser: null };
};
const serverCleanup = useServer(
{
// Our GraphQL schema.
schema,
context: (ctx, msg, args) => {
return getDynamicContext(ctx, msg, args);
},
},
wsServer,
);
const server = new ApolloServer({
schema,
context: contextMiddleware,
csrfPrevention: true,
cache: "bounded",
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
{
async serverWillStart() {
return {
async drainServer() {
await serverCleanup.dispose();
},
};
},
},
ApolloServerPluginLandingPageLocalDefault({ embed: true }),
],
});
await server.start();
server.applyMiddleware({ app })
const PORT = process.env.PORT || 4000;
httpServer.listen(PORT,()=>{
console.log(`🚀 Server ready at ${PORT}`);
sequelize.authenticate()
.then(()=>{
console.log('database connected')
}).catch((err)=>{
console.log(err)
})
})
})(typeDefs, resolvers)