forked from jbperry004/bootcamp-project
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
88 lines (77 loc) · 1.98 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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
const express = require('express')
const { createServer } = require('http')
const { graphqlExpress, graphiqlExpress } = require('apollo-server-express')
const { Model } = require('objection')
const Knex = require('knex')
const bodyParser = require('body-parser')
const jwt = require('jsonwebtoken')
const knexfile = require('./knexfile')
const User = require('./src/models/User')
const schema = require('./src/graphql')
const { tokenSecret, port } = require('./config')
const knex = Knex(knexfile.development)
Model.knex(knex)
knex.migrate.latest()
const app = express()
// Middleware to handle CORS
app.use((req, res, next) => {
let oneof = false
if (req.headers.origin) {
res.header('Access-Control-Allow-Origin', req.headers.origin)
oneof = true
}
if (req.headers['access-control-request-method']) {
res.header(
'Access-Control-Allow-Methods',
req.headers['access-control-request-method'],
)
oneof = true
}
if (req.headers['access-control-request-headers']) {
res.header(
'Access-Control-Allow-Headers',
req.headers['access-control-request-headers'],
)
oneof = true
}
if (oneof) {
res.header('Access-Control-Max-Age', 60 * 60 * 24 * 365)
}
if (oneof && req.method === 'OPTIONS') {
return res.sendStatus(200)
}
return next()
})
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
app.use(
'/graphql',
bodyParser.json(),
graphqlExpress(async req => {
const token = req.headers.authorization
if (token) {
const decoded = jwt.verify(token, tokenSecret)
const user = await User.query().findById(decoded.id)
return {
schema,
context: {
user,
},
}
}
return {
schema,
}
}),
)
app.use(
'/graphiql',
graphiqlExpress({
endpointURL: '/graphql',
}),
)
const server = createServer(app)
app.listen(port, () => {
console.log(`Apollo Server is now running on http://localhost:${port}`)
})
module.exports = app