-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
46 lines (38 loc) 路 1.29 KB
/
Copy pathserver.js
File metadata and controls
46 lines (38 loc) 路 1.29 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
const { ApolloServer, AuthenticationError } = require('apollo-server')
const mongoose = require('mongoose')
require('dotenv').config({ path: 'dev.env' })
const fs = require('fs')
const path = require('path')
const jwt = require('jsonwebtoken')
const filePath = path.join(__dirname, 'typeDefs.graphql')
const typeDefs = fs.readFileSync(filePath, 'utf-8')
const resolvers = require('./resolvers')
const User = require('./models/User')
const Post = require('./models/Post')
mongoose.connect(process.env.MONGO_URI, { useNewUrlParser: true, useUnifiedTopology: true, useCreateIndex: true, })
.then(() => console.log('DB connected'))
.catch(e => console.log(e))
const getUser = async (token) => {
if (token) {
try {
return await jwt.verify(token, process.env.SECRET)
} catch (e) {
throw new AuthenticationError('Your session has ended. Please sign in again.')
}
}
}
const server = new ApolloServer({
typeDefs,
resolvers,
formatError: error => ({
name: error.name,
message: error.message.replace('Context creation failed: ', '')
}),
context: async ({ req }) => {
const token = req.headers['authorization'] || ''
return { User, Post, currentUser: await getUser(token) }
},
})
server.listen().then(({ url }) => {
console.log(`馃殌 Server ready at ${url}`)
})