-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
54 lines (50 loc) · 2.39 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
53
54
const conditionTest = require('@malijs/condition-test')
/**
* Mali unless middleware. Attach to any middleware and configure it to prevent/permit the
* middleware in question to be executed.
* @module @malijs/unless
*
* @param {Object|String|RegExp|Function} options
* - If <code>string</code> and one of <code>Mali Call Types</code> do middleware
* unless it is the specified call type
* - If <code>string</code> and not a call type, assumed to be a call name, and
* middleware is executed unless the call name is the name specified. Call names checks are not case sensitive.
* - If <code>function</code> it's a test function that returns <code>true</code> / <code>false</code>.
* If the function returns <code>true</code> for the given request, the middleware will not run.
* The function will be passed the call context.
* - If <code>RegExp</code> instance, if call name matches the regexp the middleware is skipped.
* @param {String|Regex|Array} options.name A <code>string</code>, a <code>RegExp</code> or an array of any of those.
* If the call name matches, the middleware will not run.
* Call names checks are not case sensitive.
* @param {String|Array} options.type A <code>string</code> or an array of strings.
* If the call type matches, the middleware will not run.
* @param {Function} options.custom A test function that returns <code>true</code> / <code>false</code>.
* If the function returns <code>true</code> for the given request, the middleware will not run.
* The function will be passed the call context.
* @return {Function} middleware
*
* @example
* const requestId = require('@malijs/requestid')
* const unless = require('@malijs/unless')
* const CallType = require('@malijs/call-types')
* const toJSON = require('@malijs/tojson')()
*
* const rid = requestId()
* rid.unless = unless
* app.use(rid.unless({ name: 'SomeMethod' }))
*
* toJSON.unless = unless
* app.use(toJSON.unless({ type: [ CallType.DUPLEX, CallType.RESPONSE_STREAM ] }))
*
*/
function unlessMiddleware (options) {
const parent = this
return function unless (ctx, next) {
const skip = conditionTest(ctx, options)
if (skip) {
return next()
}
return parent(ctx, next)
}
}
module.exports = unlessMiddleware