-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
52 lines (48 loc) · 1.69 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
45
46
47
48
49
50
51
52
const CallType = require('@malijs/call-types')
/**
* Mali param middleware. If the request object has the specified property
* of specified type the middleware function is executed.
* Only applies for <code>UNARY</code> and <code>RESPONSE_STREAM</code> call types.
* @module @malijs/param
*
* @param {String} paramName The name of the request object property
* @param {Options} options
* @param {String} options.type Optional type of the param specified by <code>paramName</code> within the request.
* Has to be one of possible values as returned by <code>typeof</code>.
* @param {Boolean} options.truthy optional check for truthiness on the param value within the request.
* Default: <code>false</code>
* @param {Function} fn The middleware function to execute
*
* @example
* const param = require('@malijs/param')
*
* async function appendDocType (id, ctx, next) {
* ctx.req.id = 'user::'.concat(id)
* await next()
* }
*
* app.use(param('id', { type'string', truthy: true }, appendDocType))
*/
module.exports = function (paramName, options, fn) {
if (!fn && typeof options === 'function') {
fn = options
options = {}
}
return function param (ctx, next) {
if (ctx.type === CallType.REQUEST_STREAM || ctx.type === CallType.DUPLEX) {
return next()
}
let typeOk = options.type ? typeof ctx.req[paramName] === options.type : true
if (!typeOk) {
return next()
}
if (ctx.req.hasOwnProperty(paramName)) {
if (options.truthy && !ctx.req[paramName]) {
return next()
}
return fn(ctx.req[paramName], ctx, next)
} else {
return next()
}
}
}