-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
53 lines (43 loc) · 1.47 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
const { ApolloServer, AuthenticationError } = require("apollo-server")
const mongoose = require('mongoose')
const fs = require('fs');
const path = require('path');
const jwt = require('jsonwebtoken')
// Importing typeDefs and resolvers
const filePath = path.join(__dirname, 'typeDefs.gql')
const typeDefs = fs.readFileSync(filePath, 'utf-8')
const resolvers = require('./resolvers')
// Importing env variables
require('dotenv').config({ path: '.env' })
// Importing models
const User = require('./models/User')
const Customer = require('./models/Customer')
mongoose.set('useCreateIndex', true);
// Connecting to MongoDB Atlas
mongoose.connect(
process.env.MONGO_URI,
{ useNewUrlParser: true, useUnifiedTopology: true }
).then(() => console.log("DB connected"))
.catch(err => console.error(err))
// Verify JWT token passed from client
const getUser = async token => {
if (token) {
try {
return await jwt.verify(token, process.env.SECRET);
} catch (err) {
throw new AuthenticationError('Your session has ended. Please sign in again')
}
}
}
const server = new ApolloServer({
typeDefs,
resolvers,
context: async ({ req }) => {
const token = req.headers["authorization"];
return { User, Customer, currentUser: await getUser(token) }
}
})
// Running server on port in env or 4000
server.listen({ port: process.env.PORT || 4000 }).then(({ url }) => {
console.log('Server listening on ${url}');
})