-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.js
97 lines (85 loc) · 2.76 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
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
89
90
91
92
93
94
95
96
97
import express from 'express';
import helmet from 'helmet'
import bodyParser from 'body-parser';
import { graphqlExpress } from 'apollo-server-express';
import compression from 'compression'
import next from 'next'
import cookieParser from 'cookie-parser'
import { makeSchema } from "graphql-spotify";
import { APOLLO_ENGINE_API_KEY } from './spotify-config'
import { Engine } from 'apollo-engine'
import { mergeSchemas } from 'graphql-tools';
import { genreSchema, linkTypeDefs, linkTypeDef2nd, mergeResolvers, mergeResolvers2nd } from './graphql/genre-noises'
const dev = process.env.NODE_ENV !== 'production'
const app = next({ dev })
const handle = app.getRequestHandler()
const port = parseInt(process.env.PORT, 10) || 3000
function middlewareRedirectToHTTPS (req, res, next) {
const protocol= req.headers['x-forwarded-proto']
const isNotSecure = protocol !== 'https'
const host = req.get('host')
if (isNotSecure && !host.startsWith('localhost')) {
return res.redirect('https://' + req.get('host') + req.url)
}
next()
}
function attachEngine(server) {
const engine = new Engine({
engineConfig: {
apiKey: APOLLO_ENGINE_API_KEY
},
graphqlPort: port
});
engine.start();
server.use(engine.expressMiddleware())
}
async function start() {
await app.prepare()
const server = express();
if (!dev) {
server.use(helmet({
hsts : {
maxAge: 31536000,
includeSubDomains: true,
preload: true
}
}))
server.use(middlewareRedirectToHTTPS)
}
server.use(compression())
server.use(cookieParser())
if (APOLLO_ENGINE_API_KEY) {
attachEngine(server)
}
// bodyParser is needed just for POST.
server.use(
'/graphql',
bodyParser.json(),
graphqlExpress(req => {
// this is set the client side via the the implicit Spotify Auth flow
const token = req.query['token']
const schema = makeSchema(token)
let mergedSchema = mergeSchemas({
schemas: [schema, genreSchema, linkTypeDefs],
resolvers: mergeResolvers
})
mergedSchema = mergeSchemas({
schemas: [mergedSchema, linkTypeDef2nd],
resolvers: mergeResolvers2nd
})
// the whole execution takes about 20ms
return {
schema: mergedSchema,
tracing: true,
cacheControl: true
}
}));
server.get('*', (req, res) => {
return handle(req, res)
})
server.listen(port, (err) => {
if (err) throw err
if (dev) console.log(`> Ready on http://localhost:${port}`)
})
}
start()