diff --git a/.gitignore b/.gitignore index 6903f3f..da3cb55 100644 --- a/.gitignore +++ b/.gitignore @@ -1,44 +1,22 @@ -# Logs -logs -*.log -npm-debug.log* - -# Runtime data -pids -*.pid -*.seed - -# Directory for instrumented libs generated by jscoverage/JSCover -lib-cov - -# Coverage directory used by tools like istanbul -coverage - -# nyc test coverage -.nyc_output - -# Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) -.grunt - -# node-waf configuration -.lock-wscript +# OS # +################### +.DS_Store +.idea +Thumbs.db +tmp/ +temp/ -# Compiled binary addons (http://nodejs.org/api/addons.html) -build/Release -# Dependency directories +# Node.js # +################### node_modules -jspm_packages - package-lock.json yarn.lock +*.log -# Optional npm cache directory -.npm - -# Optional REPL history -.node_repl_history -.env* -!.env.test -.DS_Store +# NYC # +################### +coverage +*.lcov +.nyc_output \ No newline at end of file diff --git a/.npmrc b/.npmrc index 43c97e7..9cf9495 100644 --- a/.npmrc +++ b/.npmrc @@ -1 +1 @@ -package-lock=false +package-lock=false \ No newline at end of file diff --git a/.travis.yml b/.travis.yml index e2ac862..ae0b35d 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,10 +1,8 @@ language: node_js node_js: - - "8" - - "9" - - "10" - - "11" - - "12" -notifications: - email: - on_success: never + - 8 + - 10 + - 12 + - 'stable' +script: + - npm run coverage \ No newline at end of file diff --git a/LICENSE b/LICENSE index 01750af..a0a52cf 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,7 @@ The MIT License (MIT) Copyright (c) 2015 Alexander C. Mingoia +Copyright (c) 2019-present Nick Baugh and Koajs contributors Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal @@ -18,4 +19,4 @@ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN -THE SOFTWARE. +THE SOFTWARE. \ No newline at end of file diff --git a/README.md b/README.md index 88aed1c..47c0dd8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,6 @@ -# @koa/router +# [@koa/router](https://github.com/koajs/router) -Router middleware for [koa](https://github.com/koajs/koa) +> Router middleware for [Koa](https://github.com/koajs/koa). [![NPM version](https://img.shields.io/npm/v/@koa/router.svg?style=flat)](https://npmjs.org/package/@koa/router) [![NPM Downloads](https://img.shields.io/npm/dm/@koa/router.svg?style=flat)](https://npmjs.org/package/@koa/router) @@ -20,18 +20,18 @@ Router middleware for [koa](https://github.com/koajs/koa) ## Migrating to 7 / Koa 2 - The API has changed to match the new promise-based middleware - signature of koa 2. See the - [koa 2.x readme](https://github.com/koajs/koa/tree/2.0.0-alpha.3) for more + signature of koa 2. See the [koa 2.x readme](https://github.com/koajs/koa/tree/2.0.0-alpha.3) for more information. - Middleware is now always run in the order declared by `.use()` (or `.get()`, etc.), which matches Express 4 API. ## Installation -Install using [npm](https://www.npmjs.org/): - -```sh -npm install @koa/router +```bash +# npm .. +npm i @koa/router +# yarn .. +yarn add @koa/router ``` ## [API Reference](./API.md) @@ -40,10 +40,6 @@ npm install @koa/router Please submit all issues and pull requests to the [koajs/router](http://github.com/koajs/router) repository! -## Tests - -Run tests using `npm test`. - ## Support If you have any problem or suggestion please open an issue [here](https://github.com/koajs/router/issues). @@ -54,3 +50,6 @@ This module is forked from the original [koa-router](https://github.com/ZijianHe Thanks to the original authors @alexmingoia and the original team for their great work. +### License + +[MIT](LICENSE) \ No newline at end of file diff --git a/lib/layer.js b/lib/layer.js index 3fbc5d7..92178bf 100644 --- a/lib/layer.js +++ b/lib/layer.js @@ -27,27 +27,23 @@ function Layer(path, methods, middleware, opts) { for(let i = 0; i < methods.length; i++) { const l = this.methods.push(methods[i].toUpperCase()); - if (this.methods[l-1] === 'GET') { - this.methods.unshift('HEAD'); - } + if (this.methods[l-1] === 'GET') this.methods.unshift('HEAD'); } // ensure middleware is a function for (let i = 0; i < this.stack.length; i++) { const fn = this.stack[i]; const type = (typeof fn); - if (type !== 'function') { + if (type !== 'function') throw new Error( - methods.toString() + " `" + (this.opts.name || path) +"`: `middleware` " - + "must be a function, not `" + type + "`" + `${methods.toString()} \`${this.opts.name || path}\`: \`middleware\` must be a function, not \`${type}\`` ); - } } this.path = path; this.regexp = pathToRegexp(path, this.paramNames, this.opts); - debug('defined route %s %s', this.methods, this.opts.prefix + this.path); + debug('defined route %s %s', this.methods, `${this.opts.prefix}${this.path}`); }; /** @@ -94,8 +90,7 @@ Layer.prototype.params = function (path, captures, existingParams) { */ Layer.prototype.captures = function (path) { - if (this.opts.ignoreCaptures) return []; - return path.match(this.regexp).slice(1); + return this.opts.ignoreCaptures ? [] : path.match(this.regexp).slice(1); }; /** @@ -220,11 +215,7 @@ Layer.prototype.param = function (param, fn) { Layer.prototype.setPrefix = function (prefix) { if (this.path) { - if (this.path !== '/' || this.opts.strict === true) { - this.path = prefix + this.path; - } else { - this.path = prefix; - } + this.path = (this.path !== '/' || this.opts.strict === true) ? `${prefix}${this.path}` : prefix this.paramNames = []; this.regexp = pathToRegexp(this.path, this.paramNames, this.opts); } diff --git a/lib/router.js b/lib/router.js index 70a4774..1c18098 100644 --- a/lib/router.js +++ b/lib/router.js @@ -47,9 +47,7 @@ module.exports = Router; */ function Router(opts) { - if (!(this instanceof Router)) { - return new Router(opts); - } + if (!(this instanceof Router)) return new Router(opts); this.opts = opts || {}; this.methods = this.opts.methods || [ @@ -253,13 +251,12 @@ Router.prototype.use = function () { const p = arrPaths[i]; router.use.apply(router, [p].concat(middleware.slice(1))); } + return this; } const hasPath = typeof middleware[0] === 'string'; - if (hasPath) { - path = middleware.shift(); - } + if (hasPath) path = middleware.shift(); for (let i = 0; i < middleware.length; i++) { const m = middleware[i]; @@ -440,12 +437,10 @@ Router.prototype.allowedMethods = function (options) { if (!~implemented.indexOf(ctx.method)) { if (options.throw) { - let notImplementedThrowable; - if (typeof options.notImplemented === 'function') { - notImplementedThrowable = options.notImplemented(); // set whatever the user returns from their function - } else { - notImplementedThrowable = new HttpError.NotImplemented(); - } + let notImplementedThrowable = (typeof options.notImplemented === 'function') + ? options.notImplemented() // set whatever the user returns from their function + : new HttpError.NotImplemented(); + throw notImplementedThrowable; } else { ctx.status = 501; @@ -458,12 +453,10 @@ Router.prototype.allowedMethods = function (options) { ctx.set('Allow', allowedArr.join(', ')); } else if (!allowed[ctx.method]) { if (options.throw) { - let notAllowedThrowable; - if (typeof options.methodNotAllowed === 'function') { - notAllowedThrowable = options.methodNotAllowed(); // set whatever the user returns from their function - } else { - notAllowedThrowable = new HttpError.MethodNotAllowed(); - } + let notAllowedThrowable = (typeof options.methodNotAllowed === 'function') + ? options.methodNotAllowed() // set whatever the user returns from their function + : new HttpError.MethodNotAllowed(); + throw notAllowedThrowable; } else { ctx.status = 405; @@ -496,9 +489,7 @@ Router.prototype.all = function (name, path, middleware) { name = null; } - this.register(path, methods, middleware, { - name: name - }); + this.register(path, methods, middleware, { name }); return this; }; @@ -529,14 +520,10 @@ Router.prototype.all = function (name, path, middleware) { Router.prototype.redirect = function (source, destination, code) { // lookup source route by name - if (source[0] !== '/') { - source = this.url(source); - } + if (source[0] !== '/') source = this.url(source); // lookup destination route by name - if (destination[0] !== '/') { - destination = this.url(destination); - } + if (destination[0] !== '/') destination = this.url(destination); return this.all(source, ctx => { ctx.redirect(destination); @@ -606,9 +593,7 @@ Router.prototype.route = function (name) { const routes = this.stack; for (let len = routes.length, i=0; i", "bugs": { "url": "https://github.com/koajs/router/issues", @@ -46,8 +46,8 @@ }, "scripts": { "docs": "NODE_ENV=test jsdoc2md -t ./lib/API_tpl.hbs --src ./lib/*.js >| API.md", - "test": "NODE_ENV=test mocha test/**/*.js", - "test:cov": "NODE_ENV=test nyc mocha test/**/*.js", + "test": "mocha test/**/*.js", + "coverage": "nyc npm run test", "bench": "make -C bench" } } diff --git a/test/lib/layer.js b/test/lib/layer.js index b829bce..fe1ef24 100644 --- a/test/lib/layer.js +++ b/test/lib/layer.js @@ -245,11 +245,28 @@ describe('Layer', function() { ); url.should.equal('/programming/how%20to%20node'); }); + it('setPrefix method checks Layer for path', function () { const route = new Layer('/category', ['get'], [function () {}], {name: 'books'}); route.path = '/hunter2' const prefix = route.setPrefix('TEST') prefix.path.should.equal('TEST/hunter2') - }) + }); + }); + + describe('Layer#prefix', () => { + it('setPrefix method passes check Layer for path', function () { + const route = new Layer('/category', ['get'], [function () {}], {name: 'books'}); + route.path = '/hunter2' + const prefix = route.setPrefix('/TEST') + prefix.path.should.equal('/TEST/hunter2') + }); + + it('setPrefix method fails check Layer for path', function () { + const route = new Layer(false, ['get'], [function () {}], {name: 'books'}); + route.path = false + const prefix = route.setPrefix('/TEST') + prefix.path.should.equal(false) + }); }); -}); +}); \ No newline at end of file diff --git a/test/lib/router.js b/test/lib/router.js index bd4f598..772a178 100644 --- a/test/lib/router.js +++ b/test/lib/router.js @@ -779,6 +779,19 @@ describe('Router', function () { }); + it("allowedMethods check if flow (allowedArr.length)", function (done) { + const app = new Koa(); + const router = new Router(); + app.use(router.routes()); + app.use(router.allowedMethods()); + + router.get(''); + + request(http.createServer(app.callback())) + .get('/users') + .end(() => done()); + }); + it('supports custom routing detect path: ctx.routerPath', function (done) { const app = new Koa(); const router = new Router();