forked from electerious/Ackee
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathserverless.js
63 lines (51 loc) · 1.59 KB
/
serverless.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
'use strict'
const { ApolloServer } = require('apollo-server-lambda')
const config = require('./utils/config')
const connect = require('./utils/connect')
const fullyQualifiedDomainNames = require('./utils/fullyQualifiedDomainNames')
const createApolloServer = require('./utils/createApolloServer')
const { createServerlessContext } = require('./utils/createContext')
if (config.dbUrl == null) {
throw new Error('MongoDB connection URI missing in environment')
}
connect(config.dbUrl)
const apolloServer = createApolloServer(ApolloServer, {
context: createServerlessContext,
})
const origin = (origin, callback) => {
if (config.autoOrigin === true) {
fullyQualifiedDomainNames()
.then((names) => callback(
null,
names.flatMap((name) => [ `http://${ name }`, `https://${ name }`, name ]),
))
.catch((error) => callback(error, false))
return
}
if (config.allowOrigin === '*') {
callback(null, true)
return
}
if (config.allowOrigin != null) {
callback(null, config.allowOrigin.split(','))
return
}
callback(null, false)
return
}
exports.handler = (event, context) => {
// Set request context which is missing on Vercel:
// https://stackoverflow.com/questions/71360059/apollo-server-lambda-unable-to-determine-event-source-based-on-event
if (event.requestContext == null) event.requestContext = context
const handler = apolloServer.createHandler({
expressGetMiddlewareOptions: {
cors: {
origin,
credentials: true,
methods: 'GET,POST,PATCH,OPTIONS',
allowedHeaders: 'Content-Type, Authorization, Time-Zone',
},
},
})
return handler(event, context)
}