-
Notifications
You must be signed in to change notification settings - Fork 6
/
index.js
86 lines (72 loc) · 2.1 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
const { ApolloServer } = require("apollo-server-express");
const { ApolloServerPluginDrainHttpServer } = require("apollo-server-core");
const { makeExecutableSchema } = require("@graphql-tools/schema");
const express = require("express");
const http = require("http");
const { WebSocketServer } = require("ws");
const { useServer } = require("graphql-ws/lib/use/ws");
const config = require("./utils/config");
const mongoose = require("mongoose");
const jwt = require("jsonwebtoken");
const User = require("./models/User");
const typeDefs = require("./schema");
const resolvers = require("./resolvers");
console.log("connecting to ", config.MONGOOSE_URI);
mongoose
.connect(config.MONGOOSE_URI)
.then(() => {
console.log("connected to MongoDB");
})
.catch((error) => {
console.log("error connection to MongoDB: ", error.message);
});
const start = async () => {
const app = express();
const httpServer = http.createServer(app);
const schema = makeExecutableSchema({ typeDefs, resolvers });
const wsServer = new WebSocketServer({
server: httpServer,
path: "/",
});
const serverCleanup = useServer({ schema }, wsServer);
const server = new ApolloServer({
schema,
context: async ({ req }) => {
const auth = req ? req.headers.authorization : null;
if (auth && auth.toLowerCase().startsWith("bearer ")) {
const decodedToken = jwt.verify(
auth.substring(7),
process.env.JWT_SECRET
);
const currentUser = await User.findById({
_id: decodedToken.id,
});
return {
currentUser,
};
}
},
plugins: [
ApolloServerPluginDrainHttpServer({ httpServer }),
{
async serverWillStart() {
return {
async drainServer() {
await serverCleanup.dispose();
},
};
},
},
],
});
await server.start();
server.applyMiddleware({
app,
path: "/",
});
const PORT = process.env.PORT;
httpServer.listen(PORT, () =>
console.log(`Server is now running on http://localhost:${PORT}`)
);
};
start();