-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
53 lines (43 loc) · 1.2 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
const express = require('express');
const mongoose = require('mongoose');
const passport = require('passport');
const passportJwt = require('passport-jwt');
const {
ApolloServer,
} = require('apollo-server-express');
const typeDefs = require('./schema');
const resolvers = require('./resolvers');
const { JWT_SECRET, MONGODB_URI, SERVER_PORT } = process.env;
const { Strategy, ExtractJwt } = passportJwt;
const params = {
secretOrKey: JWT_SECRET,
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
};
const strategy = new Strategy(params, (payload, done) => done(null, payload));
passport.use(strategy);
const app = express();
passport.initialize();
app.use('/graphql', (req, res, next) => {
passport.authenticate('jwt', { session: false }, (err, user, info) => {
if (user) {
req.user = user;
}
next();
})(req, res, next);
});
const context = ({ req }) => {
const user = req.user || null;
return { user };
};
const server = new ApolloServer({ typeDefs, resolvers, context });
server.applyMiddleware({ app });
mongoose.connect(MONGODB_URI, {
useCreateIndex: true,
useNewUrlParser: true,
})
.then(() => {
app.listen(SERVER_PORT);
})
.catch(err => {
console.log(err);
});