-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
66 lines (57 loc) · 1.4 KB
/
server.js
File metadata and controls
66 lines (57 loc) · 1.4 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
const express = require('express');
const mongoose = require('mongoose');
const bodyParser = require('body-parser');
const { ApolloServer } = require('apollo-server-express');
const jwt = require('jsonwebtoken');
const User = require('./models/User');
const Recipe = require('./models/Recipe');
const { resolvers } = require('./resolvers');
const { typeDefs } = require('./schema');
require('dotenv').config();
mongoose
.connect(
process.env.MONGO_URI,
{ useNewUrlParser: true }
)
.then(() => 'Mongo connected')
.catch(e => console.error(e));
const PORT = process.env.PORT || 3001;
const playground = {
settings: {
'editor.cursorShape': 'line'
}
};
const server = new ApolloServer({
typeDefs,
resolvers,
cache: false,
context: ({ req: { currentUser } }) => ({
User,
Recipe,
currentUser
}),
playground
});
const app = express();
/* authorization middleware */
app.use(async (req, res, next) => {
const token = req.headers.authorization;
if (token !== 'null') {
try {
const currentUser = await jwt.verify(token, process.env.SECRET);
req.currentUser = currentUser;
} catch (error) {
console.error(error);
}
}
next();
});
server.applyMiddleware({
app,
bodyParserConfig: bodyParser.json(),
cors: {
credentials: true,
origin: 'http://localhost:3000'
}
});
app.listen(PORT, () => `PORT on ${PORT} and ${server.graphqlPath}`);