-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
44 lines (42 loc) · 1.23 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
const CallType = require('@malijs/call-types')
/**
* Mali payload transform middleware. If the response object has a specified function
* that function it's executed upon payload. Only applies for <code>UNARY</code> and
* <code>REQUEST_STREAM</code> call types.
* @module @malijs/transform
*
* @param {String} fn The name of the function property to check against in the response object
* @return {Function} the middleware function
* @example
* const xform = require('@malijs/transform')
*
* function handler(ctx) {
* const obj = {
* email: '[email protected]',
* password: 'mysecret'
* }
*
* obj.xform = function() {
* return {
* email: this.email
* }
* }
*
* ctx.res = obj // password will not be in the payload to client
* }
*
* app.use('fn', xform('xform'), handler)
*/
module.exports = function (fn) {
return function transform (ctx, next) {
if (ctx.type === CallType.RESPONSE_STREAM || ctx.type === CallType.DUPLEX) {
return next()
}
return next().then(() => {
if (ctx.res && typeof ctx.res === 'object' &&
(typeof ctx.res[fn] === 'function' || typeof Object.getPrototypeOf(ctx.res)[fn] === 'function')) {
ctx.res = ctx.res[fn]()
}
})
}
}