| 66 | * @param options conditions (e.g. options) |
| 67 | */ |
| 68 | export function unless( |
| 69 | mw: Middleware, |
| 70 | options: UnlessMiddlewareOptions | CustomUnless |
| 71 | ): (req: Request, res: Response, next: NextFunction) => any { |
| 72 | let opts: UnlessMiddlewareOptions // options |
| 73 | let custom: CustomUnless // function |
| 74 | |
| 75 | if (typeof options === 'object') opts = options as UnlessMiddlewareOptions |
| 76 | else if (typeof options === 'function') custom = options as CustomUnless |
| 77 | |
| 78 | // Returned middleware with configuration |
| 79 | return function result(req: Request, res: Response, next: NextFunction): any { |
| 80 | if (custom == undefined && (opts === {} || opts == undefined)) next() |
| 81 | if (custom == undefined) { |
| 82 | const method: string[] = toArray(opts.method) // methods |
| 83 | const path: string[] | RegExp[] = toArray(opts.path) // full path |
| 84 | const ext: string[] = toArray(opts.ext) // last part of the endpoint |
| 85 | |
| 86 | const url: string[] = req.url.split('/') // splited endpoint array |
| 87 | |
| 88 | let skip = false // determine if should skip middleware |
| 89 | |
| 90 | if (method != undefined) skip = skip || method.indexOf(req.method) !== -1 |
| 91 | if (ext != undefined) skip = skip || ext.indexOf('/' + url[url.length - 1]) !== -1 |
| 92 | if (path != undefined) skip = skip || pathCheck(path, req.url, req.method) |
| 93 | |
| 94 | if (skip) next() |
| 95 | else mw.handler(req, res, next) |
| 96 | } else { |
| 97 | if (custom(req)) next() |
| 98 | else mw.handler(req, res, next) |
| 99 | } |
| 100 | } |
| 101 | } |