forked from middyjs/middy
-
Notifications
You must be signed in to change notification settings - Fork 0
/
httpPartialResponse.js
64 lines (49 loc) · 1.34 KB
/
httpPartialResponse.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
const jsonMask = require('json-mask')
const compile = jsonMask.compile
const filter = jsonMask.filter
const defaults = {
filteringKeyName: 'fields'
}
const getFilterParams = (handler, filteringKeyName) => {
const { body } = handler.response
const { queryStringParameters } = handler.event
const fields = queryStringParameters
? queryStringParameters[filteringKeyName]
: undefined
return {
body,
fields
}
}
const isJson = str => {
try {
return JSON.parse(str) && true
} catch (err) {
return false
}
}
const isResponseFilterable = params => {
const { body, fields } = params
if (!body) return false
if (!isJson(body) && typeof body !== 'object') return false
if (!fields) return false
return true
}
module.exports = opts => {
const options = Object.assign({}, defaults, opts)
const { filteringKeyName } = options
return {
after: (handler, next) => {
const params = getFilterParams(handler, filteringKeyName)
if (!isResponseFilterable(params)) return next()
let { body, fields } = params
const isBodyStringified = isJson(body)
body = isBodyStringified ? JSON.parse(body) : body
const filteredBody = filter(body, compile(fields))
handler.response.body = isBodyStringified
? JSON.stringify(filteredBody)
: filteredBody
next()
}
}
}