UNPKG

17.7 kBTypeScriptView Raw
1// Type definitions for @koa/router 12.x
2// Project: https://github.com/koajs/koa-router#readme
3// Definitions by: Jerry Chin <https://github.com/hellopao>
4// Pavel Ivanov <https://github.com/schfkt>
5// JounQin <https://github.com/JounQin>
6// Romain Faust <https://github.com/romain-faust>
7// Guillaume Mayer <https://github.com/Guillaume-Mayer>
8// Andrea Gueugnaut <https://github.com/falinor>
9// Jeremy Forsythe <https://github.com/jdforsythe>
10// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
11// TypeScript Version: 4.1
12
13/* =================== USAGE ===================
14
15 import * as Router from "@koa/router";
16 var router = new Router();
17
18 =============================================== */
19
20 import * as Koa from "koa";
21
22 declare namespace Router {
23 interface RouterOptions {
24 /**
25 * Prefix for all routes.
26 */
27 prefix?: string | undefined;
28 /**
29 * Methods which should be supported by the router.
30 */
31 methods?: string[] | undefined;
32 routerPath?: string | undefined;
33 /**
34 * Whether or not routing should be case-sensitive.
35 */
36 sensitive?: boolean | undefined;
37 /**
38 * Whether or not routes should matched strictly.
39 *
40 * If strict matching is enabled, the trailing slash is taken into
41 * account when matching routes.
42 */
43 strict?: boolean | undefined;
44 /**
45 * Only run last matched route's controller when there are multiple matches
46 */
47 exclusive?: boolean | undefined;
48 /**
49 * Host for router match
50 */
51 host?: string | RegExp | undefined;
52 }
53
54 interface RouterParamContext<StateT = Koa.DefaultState, ContextT = Koa.DefaultContext> {
55 /**
56 * url params
57 */
58 params: Record<string, string>;
59 /**
60 * the router instance
61 */
62 router: Router<StateT, ContextT>;
63 /**
64 * Matched route
65 */
66 _matchedRoute: string | RegExp | undefined;
67 _matchedRouteName: string | undefined;
68 }
69
70 type RouterContext<StateT = Koa.DefaultState, ContextT = Koa.DefaultContext, BodyT = unknown> = Koa.ParameterizedContext<StateT, ContextT & RouterParamContext<StateT, ContextT>, BodyT>;
71
72 type Middleware<StateT = Koa.DefaultState, ContextT = Koa.DefaultContext, BodyT = unknown> = Koa.Middleware<StateT, ContextT & RouterParamContext<StateT, ContextT>, BodyT>;
73
74 interface ParamMiddleware<StateT = Koa.DefaultState, ContextT = Koa.DefaultContext, BodyT = unknown> {
75 (param: string, ctx: RouterContext<StateT, ContextT, BodyT>, next: Koa.Next): any;
76 }
77
78 interface RouterAllowedMethodsOptions {
79 /**
80 * throw error instead of setting status and header
81 */
82 throw?: boolean | undefined;
83 /**
84 * throw the returned value in place of the default NotImplemented error
85 */
86 notImplemented?: (() => any) | undefined;
87 /**
88 * throw the returned value in place of the default MethodNotAllowed error
89 */
90 methodNotAllowed?: (() => any) | undefined;
91 }
92
93 interface LayerOptions {
94 /**
95 * Route name
96 */
97 name: string | null;
98 /**
99 * Case sensitive (default: false)
100 */
101 sensitive?: boolean | undefined;
102 /**
103 * Require the trailing slash (default: false)
104 */
105 strict?: boolean | undefined;
106 /**
107 * (default: false)
108 */
109 end?: boolean | undefined;
110 /**
111 * (default: '')
112 */
113 prefix?: string | undefined;
114 ignoreCaptures?: boolean | undefined;
115 }
116
117 interface UrlOptionsQuery {
118 query: object | string;
119 }
120
121 interface RoutesMatch {
122 path: Layer[];
123 pathAndMethod: Layer[];
124 route: boolean;
125 }
126
127 class ParamName {
128 asterisk: boolean;
129 delimiter: string;
130 name: string;
131 optional: boolean;
132 partial: boolean;
133 pattern: string;
134 prefix: string;
135 repeat: string;
136 }
137
138 class Layer {
139 opts: LayerOptions;
140 name: string | null;
141 methods: string[];
142 paramNames: ParamName[];
143 stack: Middleware[];
144 regexp: RegExp;
145 path: string;
146
147 constructor(path: string | RegExp, methods: string[], middleware: Middleware | Middleware[], opts?: LayerOptions);
148
149 /**
150 * Returns whether request `path` matches route.
151 */
152 match(path: string): boolean;
153
154 /**
155 * Returns map of URL parameters for given `path` and `paramNames`.
156 */
157 params<ParamT extends string = string>(path: string | RegExp, captures: ParamT[], params?: Record<string, any>): { [key in ParamT]?: string };
158
159 /**
160 * Returns array of regexp url path captures.
161 */
162 captures(path: string): string[];
163
164 /**
165 * Generate URL for route using given `params`.
166 *
167 * @example
168 *
169 * ```javascript
170 * const route = new Layer('/users/:id', ['GET'], fn);
171 *
172 * route.url({ id: 123 }); // => "/users/123"
173 * ```
174 */
175 url(params: object): string;
176
177 /**
178 * Run validations on route named parameters.
179 *
180 * @example
181 *
182 * ```javascript
183 * router
184 * .param('user', function (id, ctx, next) {
185 * ctx.user = users[id];
186 * if (!ctx.user) return ctx.status = 404;
187 * next();
188 * })
189 * .get('/users/:user', function (ctx, next) {
190 * ctx.body = ctx.user;
191 * });
192 * ```
193 */
194 param(param: string, middleware: ParamMiddleware): Layer;
195
196 /**
197 * Prefix route path.
198 */
199 setPrefix(prefix: string): Layer;
200 }
201}
202
203declare class Router<StateT = Koa.DefaultState, ContextT = Koa.DefaultContext> {
204 opts: Router.RouterOptions;
205 methods: string[];
206 params: object;
207 stack: Router.Layer[];
208
209 /**
210 * Create a new router.
211 */
212 constructor(opt?: Router.RouterOptions);
213
214 /**
215 * Use given middleware.
216 *
217 * Middleware run in the order they are defined by `.use()`. They are invoked
218 * sequentially, requests start at the first middleware and work their way
219 * "down" the middleware stack.
220 */
221 use(...middleware: Array<Router.Middleware<StateT, ContextT>>): Router<StateT, ContextT>;
222 /**
223 * Use given middleware.
224 *
225 * Middleware run in the order they are defined by `.use()`. They are invoked
226 * sequentially, requests start at the first middleware and work their way
227 * "down" the middleware stack.
228 */
229 use(
230 path: string | string[] | RegExp,
231 ...middleware: Array<Router.Middleware<StateT, ContextT>>
232 ): Router<StateT, ContextT>;
233
234 /**
235 * HTTP get method
236 */
237 get<T = {}, U = {}, B = unknown>(
238 name: string,
239 path: string | RegExp,
240 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
241 ): Router<StateT, ContextT>;
242 /**
243 * HTTP get method
244 */
245 get<T = {}, U = {}, B = unknown>(
246 path: string | RegExp | Array<string | RegExp>,
247 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
248 ): Router<StateT, ContextT>;
249
250 /**
251 * HTTP post method
252 */
253 post<T = {}, U = {}, B = unknown>(
254 name: string,
255 path: string | RegExp,
256 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
257 ): Router<StateT, ContextT>;
258 /**
259 * HTTP post method
260 */
261 post<T = {}, U = {}, B = unknown>(
262 path: string | RegExp | Array<string | RegExp>,
263 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
264 ): Router<StateT, ContextT>;
265
266 /**
267 * HTTP put method
268 */
269 put<T = {}, U = {}, B = unknown>(
270 name: string,
271 path: string | RegExp,
272 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
273 ): Router<StateT, ContextT>;
274 /**
275 * HTTP put method
276 */
277 put<T = {}, U = {}, B = unknown>(
278 path: string | RegExp | Array<string | RegExp>,
279 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
280 ): Router<StateT, ContextT>;
281
282 /**
283 * HTTP link method
284 */
285 link<T = {}, U = {}, B = unknown>(
286 name: string,
287 path: string | RegExp,
288 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
289 ): Router<StateT, ContextT>;
290 /**
291 * HTTP link method
292 */
293 link<T = {}, U = {}, B = unknown>(
294 path: string | RegExp | Array<string | RegExp>,
295 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
296 ): Router<StateT, ContextT>;
297
298 /**
299 * HTTP unlink method
300 */
301 unlink<T = {}, U = {}, B = unknown>(
302 name: string,
303 path: string | RegExp,
304 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
305 ): Router<StateT, ContextT>;
306 /**
307 * HTTP unlink method
308 */
309 unlink<T = {}, U = {}, B = unknown>(
310 path: string | RegExp | Array<string | RegExp>,
311 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
312 ): Router<StateT, ContextT>;
313
314 /**
315 * HTTP delete method
316 */
317 delete<T = {}, U = {}, B = unknown>(
318 name: string,
319 path: string | RegExp,
320 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
321 ): Router<StateT, ContextT>;
322 /**
323 * HTTP delete method
324 */
325 delete<T = {}, U = {}, B = unknown>(
326 path: string | RegExp | Array<string | RegExp>,
327 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
328 ): Router<StateT, ContextT>;
329
330 /**
331 * Alias for `router.delete()` because delete is a reserved word
332 */
333 del<T = {}, U = {}, B = unknown>(
334 name: string,
335 path: string | RegExp,
336 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
337 ): Router<StateT, ContextT>;
338 /**
339 * Alias for `router.delete()` because delete is a reserved word
340 */
341 del<T = {}, U = {}, B = unknown>(
342 path: string | RegExp | Array<string | RegExp>,
343 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
344 ): Router<StateT, ContextT>;
345
346 /**
347 * HTTP head method
348 */
349 head<T = {}, U = {}, B = unknown>(
350 name: string,
351 path: string | RegExp,
352 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
353 ): Router<StateT, ContextT>;
354 /**
355 * HTTP head method
356 */
357 head<T = {}, U = {}, B = unknown>(
358 path: string | RegExp | Array<string | RegExp>,
359 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
360 ): Router<StateT, ContextT>;
361
362 /**
363 * HTTP options method
364 */
365 options<T = {}, U = {}, B = unknown>(
366 name: string,
367 path: string | RegExp,
368 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
369 ): Router<StateT, ContextT>;
370 /**
371 * HTTP options method
372 */
373 options<T = {}, U = {}, B = unknown>(
374 path: string | RegExp | Array<string | RegExp>,
375 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
376 ): Router<StateT, ContextT>;
377
378 /**
379 * HTTP patch method
380 */
381 patch<T = {}, U = {}, B = unknown>(
382 name: string,
383 path: string | RegExp,
384 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
385 ): Router<StateT, ContextT>;
386 /**
387 * HTTP patch method
388 */
389 patch<T = {}, U = {}, B = unknown>(
390 path: string | RegExp | Array<string | RegExp>,
391 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
392 ): Router<StateT, ContextT>;
393
394 /**
395 * Register route with all methods.
396 */
397 all<T = {}, U = {}, B = unknown>(
398 name: string,
399 path: string | RegExp,
400 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
401 ): Router<StateT, ContextT>;
402 /**
403 * Register route with all methods.
404 */
405 all<T = {}, U = {}, B = unknown>(
406 path: string | RegExp | Array<string | RegExp>,
407 ...middleware: Array<Router.Middleware<StateT & T, ContextT & U, B>>
408 ): Router<StateT, ContextT>;
409
410 /**
411 * Set the path prefix for a Router instance that was already initialized.
412 *
413 * @example
414 *
415 * ```javascript
416 * router.prefix('/things/:thing_id')
417 * ```
418 */
419 prefix(prefix: string): Router<StateT, ContextT>;
420
421 /**
422 * Returns router middleware which dispatches a route matching the request.
423 */
424 routes(): Router.Middleware<StateT, ContextT>;
425
426 /**
427 * Returns router middleware which dispatches a route matching the request.
428 */
429 middleware(): Router.Middleware<StateT, ContextT>;
430
431 /**
432 * Returns separate middleware for responding to `OPTIONS` requests with
433 * an `Allow` header containing the allowed methods, as well as responding
434 * with `405 Method Not Allowed` and `501 Not Implemented` as appropriate.
435 *
436 * @example
437 *
438 * ```javascript
439 * var Koa = require('koa');
440 * var Router = require('koa-router');
441 *
442 * var app = new Koa();
443 * var router = new Router();
444 *
445 * app.use(router.routes());
446 * app.use(router.allowedMethods());
447 * ```
448 *
449 * **Example with [Boom](https://github.com/hapijs/boom)**
450 *
451 * ```javascript
452 * var Koa = require('koa');
453 * var Router = require('koa-router');
454 * var Boom = require('boom');
455 *
456 * var app = new Koa();
457 * var router = new Router();
458 *
459 * app.use(router.routes());
460 * app.use(router.allowedMethods({
461 * throw: true,
462 * notImplemented: () => new Boom.notImplemented(),
463 * methodNotAllowed: () => new Boom.methodNotAllowed()
464 * }));
465 * ```
466 */
467 allowedMethods(
468 options?: Router.RouterAllowedMethodsOptions
469 ): Router.Middleware<StateT, ContextT>;
470
471 /**
472 * Redirect `source` to `destination` URL with optional 30x status `code`.
473 *
474 * Both `source` and `destination` can be route names.
475 *
476 * ```javascript
477 * router.redirect('/login', 'sign-in');
478 * ```
479 *
480 * This is equivalent to:
481 *
482 * ```javascript
483 * router.all('/login', ctx => {
484 * ctx.redirect('/sign-in');
485 * ctx.status = 301;
486 * });
487 * ```
488 */
489 redirect(source: string, destination: string, code?: number): Router<StateT, ContextT>;
490
491 /**
492 * Create and register a route.
493 */
494 register(
495 path: string | RegExp,
496 methods: string[],
497 middleware: Router.Middleware<StateT, ContextT> | Array<Router.Middleware<StateT, ContextT>>,
498 opts?: Router.LayerOptions,
499 ): Router.Layer;
500
501 /**
502 * Lookup route with given `name`.
503 */
504 route(name: string): Router.Layer | boolean;
505
506 /**
507 * Generate URL for route. Takes either map of named `params` or series of
508 * arguments (for regular expression routes)
509 *
510 * router = new Router();
511 * router.get('user', "/users/:id", ...
512 *
513 * router.url('user', { id: 3 });
514 * // => "/users/3"
515 *
516 * Query can be generated from third argument:
517 *
518 * router.url('user', { id: 3 }, { query: { limit: 1 } });
519 * // => "/users/3?limit=1"
520 *
521 * router.url('user', { id: 3 }, { query: "limit=1" });
522 * // => "/users/3?limit=1"
523 *
524 */
525 url(name: string, params?: any, options?: Router.UrlOptionsQuery): Error | string;
526
527 /**
528 * Match given `path` and return corresponding routes.
529 */
530 match(path: string, method: string): Router.RoutesMatch;
531
532 /**
533 * Run middleware for named route parameters. Useful for auto-loading or
534 * validation.
535 *
536 * @example
537 *
538 * ```javascript
539 * router
540 * .param('user', (id, ctx, next) => {
541 * ctx.user = users[id];
542 * if (!ctx.user) return ctx.status = 404;
543 * return next();
544 * })
545 * .get('/users/:user', ctx => {
546 * ctx.body = ctx.user;
547 * })
548 * .get('/users/:user/friends', ctx => {
549 * return ctx.user.getFriends().then(function(friends) {
550 * ctx.body = friends;
551 * });
552 * })
553 * // /users/3 => {"id": 3, "name": "Alex"}
554 * // /users/3/friends => [{"id": 4, "name": "TJ"}]
555 * ```
556 */
557
558 param<BodyT = unknown>(param: string, middleware: Router.ParamMiddleware<StateT, ContextT, BodyT>): Router<StateT, ContextT>;
559
560 /**
561 * Generate URL for route. Takes a route name and map of named `params`.
562 *
563 * @example
564 *
565 * ```javascript
566 * router.get('user', '/users/:id', (ctx, next) => {
567 * // ...
568 * });
569 *
570 * router.url('user', 3);
571 * // => "/users/3"
572 *
573 * router.url('user', { id: 3 });
574 * // => "/users/3"
575 *
576 * router.use((ctx, next) => {
577 * // redirect to named route
578 * ctx.redirect(ctx.router.url('sign-in'));
579 * })
580 *
581 * router.url('user', { id: 3 }, { query: { limit: 1 } });
582 * // => "/users/3?limit=1"
583 *
584 * router.url('user', { id: 3 }, { query: "limit=1" });
585 * // => "/users/3?limit=1"
586 * ```
587 */
588 static url(path: string | RegExp, params: object): string;
589 }
590
591 export = Router;
592
\No newline at end of file