-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathserver.js
58 lines (50 loc) · 1.21 KB
/
server.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
import express from "express";
import { ApolloServer } from "apollo-server-express";
import { importSchema } from "graphql-import";
import mongoose from "mongoose";
import Token from "./helpers/token";
import dotenv from "dotenv";
dotenv.config();
//Connect MongoDB
mongoose.connect(
process.env.DB_URI,
{ useNewUrlParser: true }
);
// Models
import User from "./models/User";
import Post from "./models/Post";
//Resolvers
import resolvers from "./graphql/resolvers";
const server = new ApolloServer({
typeDefs: importSchema("./graphql/schema.graphql"),
resolvers,
context: ({ req }) => ({
User,
Post,
activeUser: req ? req.activeUser : null
})
});
const app = express();
//Public Dir
app.use(express.static("public"));
//Auth Middleware
app.use(async (req, res, next) => {
const token = req.headers["authorization"];
if (token && token !== "null") {
try {
req.activeUser = await Token.verify(token);
} catch (e) {
console.log(e);
throw new Error(e);
}
}
next();
});
server.applyMiddleware({ app });
app.listen({ port: process.env.PORT }, () =>
console.log(
`🚀 Server ready at http://localhost:${process.env.PORT}${
server.graphqlPath
}`
)
);