-
Notifications
You must be signed in to change notification settings - Fork 11
/
index.js
98 lines (84 loc) · 2.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/**
* Koa unless middleware. Attach to any middleware and configure it to prevent/permit the
* middleware in question to be executed.
*
* @module koa-unless
*/
var url = require('url');
/** Creates a wrapper middleware that verifies if the original middleware should be skipped. */
module.exports = function(options) {
var originalMiddleware = this;
// If a custom function was passed directly, creates a new object literal that holds it as a property called custom.
var opts = typeof options === 'function' ? { custom: options } : options;
// Returns the middleware that wraps the original one.
return function *(next) {
var requestedUrl = url.parse((opts.useOriginalUrl ? this.originalUrl : this.url) || '', true);
// any match means 'skip original middleware'
if (matchesCustom(this, opts) || matchesPath(requestedUrl, opts) ||
matchesExtension(requestedUrl, opts) || matchesMethod(this.method, opts)) {
return yield *next;
}
yield *originalMiddleware.call(this, next);
};
};
/**
* Returns boolean indicating whether the custom function returns true.
*
* @param ctx - Koa context
* @param opts - unless configuration
* @returns {boolean}
*/
function matchesCustom(ctx, opts) {
if (opts.custom) {
return opts.custom.call(ctx);
}
return false;
}
/**
* Returns boolean indicating whether the requestUrl matches against the paths configured.
*
* @param requestedUrl - url requested by user
* @param opts - unless configuration
* @returns {boolean}
*/
function matchesPath(requestedUrl, opts) {
var paths = !opts.path || Array.isArray(opts.path) ?
opts.path : [opts.path];
if (paths) {
return paths.some(function(p) {
return (typeof p === 'string' && p === requestedUrl.pathname) ||
(p instanceof RegExp && !! p.exec(requestedUrl.pathname));
});
}
return false;
}
/**
* Returns boolean indicating whether the requestUrl ends with the configured extensions.
*
* @param requestedUrl - url requested by user
* @param opts - unless configuration
* @returns {boolean}
*/
function matchesExtension(requestedUrl, opts) {
var exts = !opts.ext || Array.isArray(opts.ext) ?
opts.ext : [opts.ext];
if (exts) {
return exts.some(function(ext) {
return requestedUrl.pathname.substr(ext.length * -1) === ext;
});
}
}
/**
* Returns boolean indicating whether the request method matches the configured methods.
*
* @param requestedUrl - url requested by user
* @param opts - unless configuration
* @returns {boolean}
*/
function matchesMethod(method, opts) {
var methods = !opts.method || Array.isArray(opts.method) ?
opts.method : [opts.method];
if (methods) {
return !!~methods.indexOf(method);
}
}