-
Notifications
You must be signed in to change notification settings - Fork 11
/
mount.js
69 lines (57 loc) · 2.03 KB
/
mount.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
const { compose, curry, identity, merge, is, when, tap, tryCatch } = require('ramda')
const { bufferStreams } = require('./bufferStreams')
const { cleanRequest } = require('./cleanRequest')
const { error } = require('./error')
const { eventToRequest } = require('./eventToRequest')
const { logger: defaultLogger } = require('./logger')
const { parseCookies } = require('./parseCookies')
const { parseUrl } = require('./parseUrl')
const { passThruBody } = require('./passThruBody')
const { wrap } = require('./wrap')
const { writeHTTP } = require('./writeHTTP')
const { writeLambda } = require('./writeLambda')
const keepOriginal = curry((response, request) => merge(request, {
original: request, // legacy
request,
response
}))
exports.mount = (opts={}) => {
const {
app = identity,
cry = defaultLogger,
lambda = false,
logger = defaultLogger,
middleware = []
} = opts
const handler =
middleware.length ? wrap(middleware, app) : app
const httpListener = (req, res) =>
Promise.resolve(req)
.then(keepOriginal(res))
.then(passThruBody)
.then(parseUrl)
.then(parseCookies)
.then(cleanRequest)
.then(handler)
.catch(wrapError(req))
.then(writeHTTP(req, res))
.then(() => logger({ req, res }))
const lambdaHandler = req =>
Promise.resolve(req)
.then(parseCookies)
.then(handler)
.then(bufferStreams)
.catch(wrapError(req))
.then(writeLambda(req))
.then(tap(res => logger({ req, res })))
const ignoreRejected = obj => Promise.resolve(obj).catch(identity)
const ignoreIfThrows = fn => tryCatch(fn, identity)
const safeCry = compose(ignoreRejected, ignoreIfThrows(cry))
const sob = req => err =>
safeCry(Object.assign(err, { req }))
const wrapError = req =>
when(is(Error), compose(error, tap(sob(req))))
return lambda
? compose(lambdaHandler, eventToRequest)
: httpListener
}