* Responds to `OPTIONS` requests with allowed methods
* Support for `405 Method Not Allowed` and `501 Not Implemented`
* Multiple route middleware
* Multiple and nestable routers
*`async/await` support
## 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
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
```
## [API Reference](./API.md)
## Contributing
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).
## Call for Maintainers
This module is forked from the original [koa-router](https://github.com/ZijianHe/koa-router) due to its lack of activity. `koa-router` is the most widely used router module in the Koa community and we need maintainers. If you're interested in fixing bugs or implementing new features feel free to open a pull request. We'll be adding active contributors as collaborators.
Thanks to the original authors @alexmingoia and the original team for their great work.
*[[`b5dd5e8`](http://github.com/koajs/koa-router/commit/b5dd5e8f00e841b7061a62ab6228cbe96a999470)] - chore: rename to @koa/router (dead-horse <<dead_horse@qq.com>>)
-------------
# Changelogs inherit from koa-router.
## 7.4.0
- Fix router.url() for multiple nested routers [#407](https://github.com/alexmingoia/koa-router/pull/407)
-`layer.name` added to `ctx` at `ctx.routerName` during routing [#412](https://github.com/alexmingoia/koa-router/pull/412)
- Router.use() was erroneously settings `(.*)` as a prefix to all routers nested with .use that did not pass an explicit prefix string as the first argument. This resulted in routes being matched that should not have been, included the running of multiple route handlers in error. [#369](https://github.com/alexmingoia/koa-router/issues/369) and [#410](https://github.com/alexmingoia/koa-router/issues/410) include information on this issue.
## 7.3.0
- Router#url() now accepts query parameters to add to generated urls [#396](https://github.com/alexmingoia/koa-router/pull/396)
## 7.2.1
- Respond to CORS preflights with 200, 0 length body [#359](https://github.com/alexmingoia/koa-router/issues/359)
## 7.2.0
- Fix a bug in Router#url and append Router object to ctx. [#350](https://github.com/alexmingoia/koa-router/pull/350)
- Adds `_matchedRouteName` to context [#337](https://github.com/alexmingoia/koa-router/pull/337)
- Respond to CORS preflights with 200, 0 length body [#359](https://github.com/alexmingoia/koa-router/issues/359)
## 7.1.1
- Fix bug where param handlers were run out of order [#282](https://github.com/alexmingoia/koa-router/pull/282)
## 7.1.0
- Backports: merge 5.4 work into the 7.x upstream. See 5.4.0 updates for more details.
## 7.0.1
- Fix: allowedMethods should be ctx.method not this.method [#215](https://github.com/alexmingoia/koa-router/pull/215)
## 7.0.0
- 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
information.
- Middleware is now always run in the order declared by `.use()` (or `.get()`,
etc.), which matches Express 4 API.
## 5.4.0
- Expose matched route at `ctx._matchedRoute`.
## 5.3.0
- Register multiple routes with array of paths [#203](https://github.com/alexmingoia/koa-router/issue/143).
* in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.return()`
*
* Alias `.thenReturn();` for compatibility with earlier ECMAScript version.
*/
return():Bluebird<void>;
return<U>(value:U):Bluebird<U>;
thenReturn():Bluebird<void>;
thenReturn<U>(value:U):Bluebird<U>;
/**
* Convenience method for:
*
* <code>
* .then(function() {
* throw reason;
* });
* </code>
* Same limitations apply as with `.return()`.
*
* Alias `.thenThrow();` for compatibility with earlier ECMAScript version.
*/
throw(reason:Error):Bluebird<never>;
thenThrow(reason:Error):Bluebird<never>;
/**
* Convenience method for:
*
* <code>
* .catch(function() {
* return value;
* });
* </code>
*
* in the case where `value` doesn't change its value. That means `value` is bound at the time of calling `.catchReturn()`
*/
catchReturn<U>(value:U):Bluebird<R|U>;
// No need to be specific about Error types in these overrides, since there's no handler function
catchReturn<U>(
filter1:Constructor<Error>,
filter2:Constructor<Error>,
filter3:Constructor<Error>,
filter4:Constructor<Error>,
filter5:Constructor<Error>,
value:U,
):Bluebird<R|U>;
catchReturn<U>(
filter1:Constructor<Error>|CatchFilter<Error>,
filter2:Constructor<Error>|CatchFilter<Error>,
filter3:Constructor<Error>|CatchFilter<Error>,
filter4:Constructor<Error>|CatchFilter<Error>,
filter5:Constructor<Error>|CatchFilter<Error>,
value:U,
):Bluebird<R|U>;
catchReturn<U>(
filter1:Constructor<Error>,
filter2:Constructor<Error>,
filter3:Constructor<Error>,
filter4:Constructor<Error>,
value:U,
):Bluebird<R|U>;
catchReturn<U>(
filter1:Constructor<Error>|CatchFilter<Error>,
filter2:Constructor<Error>|CatchFilter<Error>,
filter3:Constructor<Error>|CatchFilter<Error>,
filter4:Constructor<Error>|CatchFilter<Error>,
value:U,
):Bluebird<R|U>;
catchReturn<U>(
filter1:Constructor<Error>,
filter2:Constructor<Error>,
filter3:Constructor<Error>,
value:U,
):Bluebird<R|U>;
catchReturn<U>(
filter1:Constructor<Error>|CatchFilter<Error>,
filter2:Constructor<Error>|CatchFilter<Error>,
filter3:Constructor<Error>|CatchFilter<Error>,
value:U,
):Bluebird<R|U>;
catchReturn<U>(
filter1:Constructor<Error>,
filter2:Constructor<Error>,
value:U,
):Bluebird<R|U>;
catchReturn<U>(
filter1:Constructor<Error>|CatchFilter<Error>,
filter2:Constructor<Error>|CatchFilter<Error>,
value:U,
):Bluebird<R|U>;
catchReturn<U>(
filter1:Constructor<Error>,
value:U,
):Bluebird<R|U>;
catchReturn<U>(
// tslint:disable-next-line:unified-signatures
filter1:Constructor<Error>|CatchFilter<Error>,
value:U,
):Bluebird<R|U>;
/**
* Convenience method for:
*
* <code>
* .catch(function() {
* throw reason;
* });
* </code>
* Same limitations apply as with `.catchReturn()`.
*/
catchThrow(reason:Error):Bluebird<R>;
// No need to be specific about Error types in these overrides, since there's no handler function
catchThrow(
filter1:Constructor<Error>,
filter2:Constructor<Error>,
filter3:Constructor<Error>,
filter4:Constructor<Error>,
filter5:Constructor<Error>,
reason:Error,
):Bluebird<R>;
catchThrow(
filter1:Constructor<Error>|CatchFilter<Error>,
filter2:Constructor<Error>|CatchFilter<Error>,
filter3:Constructor<Error>|CatchFilter<Error>,
filter4:Constructor<Error>|CatchFilter<Error>,
filter5:Constructor<Error>|CatchFilter<Error>,
reason:Error,
):Bluebird<R>;
catchThrow(
filter1:Constructor<Error>,
filter2:Constructor<Error>,
filter3:Constructor<Error>,
filter4:Constructor<Error>,
reason:Error,
):Bluebird<R>;
catchThrow(
filter1:Constructor<Error>|CatchFilter<Error>,
filter2:Constructor<Error>|CatchFilter<Error>,
filter3:Constructor<Error>|CatchFilter<Error>,
filter4:Constructor<Error>|CatchFilter<Error>,
reason:Error,
):Bluebird<R>;
catchThrow(
filter1:Constructor<Error>,
filter2:Constructor<Error>,
filter3:Constructor<Error>,
reason:Error,
):Bluebird<R>;
catchThrow(
filter1:Constructor<Error>|CatchFilter<Error>,
filter2:Constructor<Error>|CatchFilter<Error>,
filter3:Constructor<Error>|CatchFilter<Error>,
reason:Error,
):Bluebird<R>;
catchThrow(
filter1:Constructor<Error>,
filter2:Constructor<Error>,
reason:Error,
):Bluebird<R>;
catchThrow(
filter1:Constructor<Error>|CatchFilter<Error>,
filter2:Constructor<Error>|CatchFilter<Error>,
reason:Error,
):Bluebird<R>;
catchThrow(
filter1:Constructor<Error>,
reason:Error,
):Bluebird<R>;
catchThrow(
// tslint:disable-next-line:unified-signatures
filter1:Constructor<Error>|CatchFilter<Error>,
reason:Error,
):Bluebird<R>;
/**
* Convert to String.
*/
toString():string;
/**
* This is implicitly called by `JSON.stringify` when serializing the object. Returns a serialized representation of the `Promise`.
*/
toJSON():object;
/**
* Like calling `.then`, but the fulfillment value or rejection reason is assumed to be an array, which is flattened to the formal parameters of the handlers.
* Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
all<Q>(this:Bluebird<R&Iterable<Q>>):Bluebird<R>;
/**
* Same as calling `Promise.all(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
all():Bluebird<never>;
/**
* Same as calling `Promise.props(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
any<Q>(this:Bluebird<R&Iterable<Q>>):Bluebird<Q>;
/**
* Same as calling `Promise.any(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
any():Bluebird<never>;
/**
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling `Promise.some(thisPromise)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
some(count:number):Bluebird<never>;
/**
* Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling `Promise.race(thisPromise, count)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
*/
race():Bluebird<never>;
/**
* Same as calling `Bluebird.map(thisPromise, mapper)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling `Promise.reduce(thisPromise, Function reducer, initialValue)`. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling ``Promise.filter(thisPromise, filterer)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling ``Bluebird.each(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Same as calling ``Bluebird.mapSeries(thisPromise, iterator)``. With the exception that if this promise is bound to a value, the returned promise is bound to that value too.
* Cancel this `promise`. Will not do anything if this promise is already settled or if the cancellation feature has not been enabled
*/
cancel():void;
/**
* Basically sugar for doing: somePromise.catch(function(){});
*
* Which is needed in case error handlers are attached asynchronously to the promise later, which would otherwise result in premature unhandled rejection reporting.
*/
suppressUnhandledRejections():void;
/**
* Start the chain of promises with `Promise.try`. Any synchronous exceptions will be turned into rejections on the returned promise.
*
* Note about second argument: if it's specifically a true array, its values become respective arguments for the function call.
* Otherwise it is passed as is as the first argument for the function call.
*
* Alias for `attempt();` for compatibility with earlier ECMAScript version.
* Returns a new function that wraps the given function `fn`.
* The new function will always return a promise that is fulfilled with the original functions return values or rejected with thrown exceptions from the original function.
* This method is convenient when a function can sometimes return synchronously or throw synchronously.
* If `value` is already a trusted `Promise`, it is returned as is. If `value` is not a thenable, a fulfilled is: Promise returned with `value` as its fulfillment value.
* If `value` is a thenable (Promise-like object, like those returned by jQuery's `$.ajax`), returns a trusted that: Promise assimilates the state of the thenable.
*/
staticcast<R>(value:Resolvable<R>):Bluebird<R>;
/**
* Sugar for `Promise.resolve(undefined).bind(thisArg);`. See `.bind()`.
*/
staticbind(thisArg:any):Bluebird<void>;
/**
* See if `value` is a trusted Promise.
*/
staticis(value:any):boolean;
/**
* Call this right after the library is loaded to enabled long stack traces.
*
* Long stack traces cannot be disabled after being enabled, and cannot be enabled after promises have already been created.
* Long stack traces imply a substantial performance penalty, around 4-5x for throughput and 0.5x for latency.
*/
staticlongStackTraces():void;
/**
* Returns a promise that will be resolved with value (or undefined) after given ms milliseconds.
* If value is a promise, the delay will start counting down when it is fulfilled and the returned
* promise will be fulfilled with the fulfillment value of the value promise.
* Promisifies the entire object by going through the object's properties and creating an async equivalent of each function on the object and its prototype chain.
*
* The promisified method name will be the original method name postfixed with `Async`. Returns the input object.
*
* Note that the original methods on the object are not overwritten but new methods are created with the `Async`-postfix. For example,
* if you `promisifyAll()` the node.js `fs` object use `fs.statAsync()` to call the promisified `stat` method.
* Add `handler` as the handler to call when there is a possibly unhandled rejection. The default handler logs the error stack to stderr or `console.error` in browsers.
*
* Passing no value or a non-function will have the effect of removing any kind of handling for possibly unhandled rejections.
* Given an array, or a promise of an array, which contains promises (or a mix of promises and values) return a promise that is fulfilled when all the items in the array are fulfilled.
* The promise's fulfillment value is an array with fulfillment values at respective positions to the original array.
* If any promise in the array rejects, the returned promise is rejected with the rejection reason.
* Like ``Promise.all`` but for object properties instead of array items. Returns a promise that is fulfilled when all the properties of the object are fulfilled.
*
* The promise's fulfillment value is an object with fulfillment values at respective keys to the original object.
* If any promise in the object rejects, the returned promise is rejected with the rejection reason.
*
* If `object` is a trusted `Promise`, then it will be treated as a promise for object rather than for its properties.
* All other objects are treated for their properties as is returned by `Object.keys` - the object's own enumerable properties.
* For coordinating multiple concurrent discrete promises.
*
* Note: In 1.x and 0.x Promise.join used to be a Promise.all that took the values in as arguments instead in an array.
* This behavior has been deprecated but is still supported partially - when the last argument is an immediate function value the new semantics will apply
* which contains a promises (or a mix of promises and values) with the given `mapper` function with the signature `(item, index, arrayLength)`
* where `item` is the resolved value of a respective promise in the input array.
* If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the `mapper` function returns promises or thenables, the returned promise will wait for all the mapped results to be resolved as well.
*
* *The original array is not modified.*
*/
staticmap<R,U>(
values:Resolvable<Iterable<Resolvable<R>>>,
mapper:IterateFunction<R,U>,
options?:Bluebird.ConcurrencyOption
):Bluebird<U[]>;
/**
* Reduce an array, or a promise of an array,
* which contains a promises (or a mix of promises and values) with the given `reducer` function with the signature `(total, current, index, arrayLength)`
* where `item` is the resolved value of a respective promise in the input array.
* If any promise in the input array is rejected the returned promise is rejected as well.
*
* If the reducer function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration.
*
* *The original array is not modified. If no `initialValue` is given and the array doesn't contain at least 2 items,
* the callback will not be called and `undefined` is returned.
*
* If `initialValue` is given and the array doesn't have at least 1 item, `initialValue` is returned.*
* which contains a promises (or a mix of promises and values) with the given `filterer` function with the signature `(item, index, arrayLength)`
* where `item` is the resolved value of a respective promise in the input array.
* If any promise in the input array is rejected the returned promise is rejected as well.
*
* The return values from the filtered functions are coerced to booleans, with the exception of promises and thenables which are awaited for their eventual result.
*
* *The original array is not modified.
*/
staticfilter<R>(
values:Resolvable<Iterable<Resolvable<R>>>,
filterer:IterateFunction<R,boolean>,
option?:Bluebird.ConcurrencyOption
):Bluebird<R[]>;
/**
* Iterate over an array, or a promise of an array,
* which contains promises (or a mix of promises and values) with the given iterator function with the signature `(item, index, value)`
* where item is the resolved value of a respective promise in the input array.
* Iteration happens serially. If any promise in the input array is rejected the returned promise is rejected as well.
*
* Resolves to the original array unmodified, this method is meant to be used for side effects.
* If the iterator function returns a promise or a thenable, the result for the promise is awaited for before continuing with next iteration.
*/
staticeach<R>(
values:Resolvable<Iterable<Resolvable<R>>>,
iterator:IterateFunction<R,any>
):Bluebird<R[]>;
/**
* Given an Iterable(arrays are Iterable), or a promise of an Iterable, which produces promises (or a mix of promises and values),
* iterate over all the values in the Iterable into an array and iterate over the array serially, in-order.
*
* Returns a promise for an array that contains the values returned by the iterator function in their respective positions.
* The iterator won't be called for an item until its previous item, and the promise returned by the iterator for that item are fulfilled.
* This results in a mapSeries kind of utility but it can also be used simply as a side effect iterator similar to Array#forEach.
*
* If any promise in the input array is rejected or any promise returned by the iterator function is rejected, the result will be rejected as well.
*/
staticmapSeries<R,U>(
values:Resolvable<Iterable<Resolvable<R>>>,
iterator:IterateFunction<R,U>
):Bluebird<U[]>;
/**
* A meta method used to specify the disposer method that cleans up a resource when using `Promise.using`.
*
* Returns a Disposer object which encapsulates both the resource as well as the method to clean it up.
* The user can pass this object to `Promise.using` to get access to the resource when it becomes available,
* as well as to ensure its automatically cleaned up.
*
* The second argument passed to a disposer is the result promise of the using block, which you can
* Configure long stack traces, warnings, monitoring and cancellation.
* Note that even though false is the default here, a development environment might be detected which automatically
* enables long stack traces and warnings.
*/
staticconfig(options:{
/** Enable warnings */
warnings?:boolean|{
/** Enables all warnings except forgotten return statements. */
wForgottenReturn:boolean;
};
/** Enable long stack traces */
longStackTraces?:boolean;
/** Enable cancellation */
cancellation?:boolean;
/** Enable monitoring */
monitoring?:boolean;
}):void;
/**
* Create a new promise. The passed in function will receive functions `resolve` and `reject` as its arguments which can be called to seal the fate of the created promise.
* If promise cancellation is enabled, passed in function will receive one more function argument `onCancel` that allows to register an optional cancellation callback.
* Returns a reference to the controlled promise that can be passed to clients.
*/
promise:Bluebird<R>;
/**
* Resolve the underlying promise with `value` as the resolution value. If `value` is a thenable or a promise, the underlying promise will assume its state.
*/
resolve(value:R):void;
resolve():void;
/**
* Reject the underlying promise with `reason` as the rejection reason.
*/
reject(reason:any):void;
/**
* Gives you a callback representation of the `PromiseResolver`. Note that this is not a method but a property.
* The callback accepts error object in first argument and success values on the 2nd parameter and the rest, I.E. node js conventions.
*
* If the the callback is called with multiple success values, the resolver fulfills its promise with an array of the values.
*/
// TODO specify resolver callback
callback(err:any,value:R,...values:R[]):void;
}
interfaceInspection<R>{
/**
* See if the underlying promise was fulfilled at the creation time of this inspection object.
*/
isFulfilled():boolean;
/**
* See if the underlying promise was rejected at the creation time of this inspection object.
*/
isRejected():boolean;
/**
* See if the underlying promise was cancelled at the creation time of this inspection object.
*/
isCancelled():boolean;
/**
* See if the underlying promise was defer at the creation time of this inspection object.
*/
isPending():boolean;
/**
* Get the fulfillment value of the underlying promise. Throws if the promise wasn't fulfilled at the creation time of this inspection object.
*
* throws `TypeError`
*/
value():R;
/**
* Get the rejection reason for the underlying promise. Throws if the promise wasn't rejected at the creation time of this inspection object.
*
* throws `TypeError`
*/
reason():any;
}
/**
* Returns a new independent copy of the Bluebird library.
*
* This method should be used before you use any of the methods which would otherwise alter the global Bluebird object - to avoid polluting global state.
*/
functiongetNewLibraryCopy():typeofBluebird;
/**
* This is relevant to browser environments with no module loader.
*
* Release control of the Promise namespace to whatever it was before this library was loaded.
* Returns a reference to the library namespace so you can attach it to something else.
*/
functionnoConflict():typeofBluebird;
/**
* Changes how bluebird schedules calls a-synchronously.
*
* @param scheduler Should be a function that asynchronously schedules
These definitions were written by [ William Johnston](https://github.com/wjohnsto), [Kacper Polak](https://github.com/kacepe), [Krittanan Pingclasai](https://github.com/kpping), and [James Munro](https://github.com/jdmunro).