-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
73 lines (68 loc) · 1.7 KB
/
Copy pathserver.js
File metadata and controls
73 lines (68 loc) · 1.7 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
67
68
69
70
71
72
73
const {
ApolloServer,
AuthenticationError
} = require("apollo-server")
const mongoose = require('mongoose')
const path = require('path')
const fs = require('fs')
const User = require("./models/User")
const Post = require("./models/Post")
require("dotenv").config({
path: "variables.env"
})
const jwt = require('jsonwebtoken')
// Import typeDefs.gql & resolver.js
const filePath = path.join(__dirname, "typeDefs.gql")
const typeDefs = fs.readFileSync(filePath, "utf-8")
const resolvers = require('./resolvers')
// Connect to MongoDb Atlas cluster
mongoose.connect(process.env.MONGO_URI, {
useNewUrlParser: true,
}).then(() => console.log("MongoDB connected"))
.catch(err => console.error(err));
mongoose.set('useCreateIndex', true)
// 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')
}
}
}
// Initialize Apollo/GraphQL Server
const server = new ApolloServer({
typeDefs,
resolvers,
// format authentication errors for ui notifications
formatError: error => ({
name: error.name,
message: error.message
}),
context: async ({
req
}) => {
const token = req.headers["authorization"]
return {
User,
Post,
currentUser: await getUser(token)
}
},
playground: {
endpoint: '/playground',
settings: {
'editor.theme': 'light',
"editor.cursorShape": "block",
},
}
});
// Start the HTTP server to listen for connections
server.listen({
port: process.env.PORT || 4000
}).then(({
url
}) => {
console.log(` 🚀 Server live at ${url}`);
});