UNPKG

41.7 kBTypeScriptView Raw
1// Type definitions for Express 4.17
2// Project: http://expressjs.com
3// Definitions by: Boris Yankov <https://github.com/borisyankov>
4// Satana Charuwichitratana <https://github.com/micksatana>
5// Sami Jaber <https://github.com/samijaber>
6// Jose Luis Leon <https://github.com/JoseLion>
7// David Stephens <https://github.com/dwrss>
8// Shin Ando <https://github.com/andoshin11>
9// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
10// TypeScript Version: 2.3
11
12// This extracts the core definitions from express to prevent a circular dependency between express and serve-static
13/// <reference types="node" />
14
15import { SendOptions } from 'send';
16
17declare global {
18 namespace Express {
19 // These open interfaces may be extended in an application-specific manner via declaration merging.
20 // See for example method-override.d.ts (https://github.com/DefinitelyTyped/DefinitelyTyped/blob/master/types/method-override/index.d.ts)
21 interface Request {}
22 interface Response {}
23 interface Locals {}
24 interface Application {}
25 }
26}
27
28import * as http from 'http';
29import { EventEmitter } from 'events';
30import { Options as RangeParserOptions, Result as RangeParserResult, Ranges as RangeParserRanges } from 'range-parser';
31import { ParsedQs } from 'qs';
32
33export {};
34
35export type Query = ParsedQs;
36
37export interface NextFunction {
38 (err?: any): void;
39 /**
40 * "Break-out" of a router by calling {next('router')};
41 * @see {https://expressjs.com/en/guide/using-middleware.html#middleware.router}
42 */
43 (deferToNext: 'router'): void;
44 /**
45 * "Break-out" of a route by calling {next('route')};
46 * @see {https://expressjs.com/en/guide/using-middleware.html#middleware.application}
47 */
48 (deferToNext: 'route'): void;
49}
50
51export interface Dictionary<T> {
52 [key: string]: T;
53}
54
55export interface ParamsDictionary {
56 [key: string]: string;
57}
58export type ParamsArray = string[];
59export type Params = ParamsDictionary | ParamsArray;
60
61export interface Locals extends Express.Locals {}
62
63export interface RequestHandler<
64 P = ParamsDictionary,
65 ResBody = any,
66 ReqBody = any,
67 ReqQuery = ParsedQs,
68 LocalsObj extends Record<string, any> = Record<string, any>
69> {
70 // tslint:disable-next-line callable-types (This is extended from and can't extend from a type alias in ts<2.2)
71 (
72 req: Request<P, ResBody, ReqBody, ReqQuery, LocalsObj>,
73 res: Response<ResBody, LocalsObj>,
74 next: NextFunction,
75 ): void;
76}
77
78export type ErrorRequestHandler<
79 P = ParamsDictionary,
80 ResBody = any,
81 ReqBody = any,
82 ReqQuery = ParsedQs,
83 LocalsObj extends Record<string, any> = Record<string, any>
84> = (
85 err: any,
86 req: Request<P, ResBody, ReqBody, ReqQuery, LocalsObj>,
87 res: Response<ResBody, LocalsObj>,
88 next: NextFunction,
89) => void;
90
91export type PathParams = string | RegExp | Array<string | RegExp>;
92
93export type RequestHandlerParams<
94 P = ParamsDictionary,
95 ResBody = any,
96 ReqBody = any,
97 ReqQuery = ParsedQs,
98 LocalsObj extends Record<string, any> = Record<string, any>
99> =
100 | RequestHandler<P, ResBody, ReqBody, ReqQuery, LocalsObj>
101 | ErrorRequestHandler<P, ResBody, ReqBody, ReqQuery, LocalsObj>
102 | Array<RequestHandler<P> | ErrorRequestHandler<P>>;
103
104type RemoveTail<S extends string, Tail extends string> = S extends `${infer P}${Tail}` ? P : S;
105type GetRouteParameter<S extends string> = RemoveTail<
106 RemoveTail<RemoveTail<S, `/${string}`>, `-${string}`>,
107 `.${string}`
108>;
109
110// prettier-ignore
111export type RouteParameters<Route extends string> = string extends Route
112 ? ParamsDictionary
113 : Route extends `${string}(${string}`
114 ? ParamsDictionary //TODO: handling for regex parameters
115 : Route extends `${string}:${infer Rest}`
116 ? (
117 GetRouteParameter<Rest> extends never
118 ? ParamsDictionary
119 : GetRouteParameter<Rest> extends `${infer ParamName}?`
120 ? { [P in ParamName]?: string }
121 : { [P in GetRouteParameter<Rest>]: string }
122 ) &
123 (Rest extends `${GetRouteParameter<Rest>}${infer Next}`
124 ? RouteParameters<Next> : unknown)
125 : {};
126
127export interface IRouterMatcher<
128 T,
129 Method extends 'all' | 'get' | 'post' | 'put' | 'delete' | 'patch' | 'options' | 'head' = any
130> {
131 <
132 Route extends string,
133 P = RouteParameters<Route>,
134 ResBody = any,
135 ReqBody = any,
136 ReqQuery = ParsedQs,
137 LocalsObj extends Record<string, any> = Record<string, any>
138 >(
139 // (it's used as the default type parameter for P)
140 // eslint-disable-next-line no-unnecessary-generics
141 path: Route,
142 // (This generic is meant to be passed explicitly.)
143 // eslint-disable-next-line no-unnecessary-generics
144 ...handlers: Array<RequestHandler<P, ResBody, ReqBody, ReqQuery, LocalsObj>>
145 ): T;
146 <
147 Path extends string,
148 P = RouteParameters<Path>,
149 ResBody = any,
150 ReqBody = any,
151 ReqQuery = ParsedQs,
152 LocalsObj extends Record<string, any> = Record<string, any>
153 >(
154 // (it's used as the default type parameter for P)
155 // eslint-disable-next-line no-unnecessary-generics
156 path: Path,
157 // (This generic is meant to be passed explicitly.)
158 // eslint-disable-next-line no-unnecessary-generics
159 ...handlers: Array<RequestHandlerParams<P, ResBody, ReqBody, ReqQuery, LocalsObj>>
160 ): T;
161 <
162 P = ParamsDictionary,
163 ResBody = any,
164 ReqBody = any,
165 ReqQuery = ParsedQs,
166 LocalsObj extends Record<string, any> = Record<string, any>
167 >(
168 path: PathParams,
169 // (This generic is meant to be passed explicitly.)
170 // eslint-disable-next-line no-unnecessary-generics
171 ...handlers: Array<RequestHandler<P, ResBody, ReqBody, ReqQuery, LocalsObj>>
172 ): T;
173 <
174 P = ParamsDictionary,
175 ResBody = any,
176 ReqBody = any,
177 ReqQuery = ParsedQs,
178 LocalsObj extends Record<string, any> = Record<string, any>
179 >(
180 path: PathParams,
181 // (This generic is meant to be passed explicitly.)
182 // eslint-disable-next-line no-unnecessary-generics
183 ...handlers: Array<RequestHandlerParams<P, ResBody, ReqBody, ReqQuery, LocalsObj>>
184 ): T;
185 (path: PathParams, subApplication: Application): T;
186}
187
188export interface IRouterHandler<T, Route extends string = string> {
189 (...handlers: Array<RequestHandler<RouteParameters<Route>>>): T;
190 (...handlers: Array<RequestHandlerParams<RouteParameters<Route>>>): T;
191 <
192 P = RouteParameters<Route>,
193 ResBody = any,
194 ReqBody = any,
195 ReqQuery = ParsedQs,
196 LocalsObj extends Record<string, any> = Record<string, any>
197 >(
198 // (This generic is meant to be passed explicitly.)
199 // eslint-disable-next-line no-unnecessary-generics
200 ...handlers: Array<RequestHandler<P, ResBody, ReqBody, ReqQuery, LocalsObj>>
201 ): T;
202 <
203 P = RouteParameters<Route>,
204 ResBody = any,
205 ReqBody = any,
206 ReqQuery = ParsedQs,
207 LocalsObj extends Record<string, any> = Record<string, any>
208 >(
209 // (This generic is meant to be passed explicitly.)
210 // eslint-disable-next-line no-unnecessary-generics
211 ...handlers: Array<RequestHandlerParams<P, ResBody, ReqBody, ReqQuery, LocalsObj>>
212 ): T;
213 <
214 P = ParamsDictionary,
215 ResBody = any,
216 ReqBody = any,
217 ReqQuery = ParsedQs,
218 LocalsObj extends Record<string, any> = Record<string, any>
219 >(
220 // (This generic is meant to be passed explicitly.)
221 // eslint-disable-next-line no-unnecessary-generics
222 ...handlers: Array<RequestHandler<P, ResBody, ReqBody, ReqQuery, LocalsObj>>
223 ): T;
224 <
225 P = ParamsDictionary,
226 ResBody = any,
227 ReqBody = any,
228 ReqQuery = ParsedQs,
229 LocalsObj extends Record<string, any> = Record<string, any>
230 >(
231 // (This generic is meant to be passed explicitly.)
232 // eslint-disable-next-line no-unnecessary-generics
233 ...handlers: Array<RequestHandlerParams<P, ResBody, ReqBody, ReqQuery, LocalsObj>>
234 ): T;
235}
236
237export interface IRouter extends RequestHandler {
238 /**
239 * Map the given param placeholder `name`(s) to the given callback(s).
240 *
241 * Parameter mapping is used to provide pre-conditions to routes
242 * which use normalized placeholders. For example a _:user_id_ parameter
243 * could automatically load a user's information from the database without
244 * any additional code,
245 *
246 * The callback uses the samesignature as middleware, the only differencing
247 * being that the value of the placeholder is passed, in this case the _id_
248 * of the user. Once the `next()` function is invoked, just like middleware
249 * it will continue on to execute the route, or subsequent parameter functions.
250 *
251 * app.param('user_id', function(req, res, next, id){
252 * User.find(id, function(err, user){
253 * if (err) {
254 * next(err);
255 * } else if (user) {
256 * req.user = user;
257 * next();
258 * } else {
259 * next(new Error('failed to load user'));
260 * }
261 * });
262 * });
263 */
264 param(name: string, handler: RequestParamHandler): this;
265
266 /**
267 * Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param()
268 *
269 * @deprecated since version 4.11
270 */
271 param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this;
272
273 /**
274 * Special-cased "all" method, applying the given route `path`,
275 * middleware, and callback to _every_ HTTP method.
276 */
277 all: IRouterMatcher<this, 'all'>;
278 get: IRouterMatcher<this, 'get'>;
279 post: IRouterMatcher<this, 'post'>;
280 put: IRouterMatcher<this, 'put'>;
281 delete: IRouterMatcher<this, 'delete'>;
282 patch: IRouterMatcher<this, 'patch'>;
283 options: IRouterMatcher<this, 'options'>;
284 head: IRouterMatcher<this, 'head'>;
285
286 checkout: IRouterMatcher<this>;
287 connect: IRouterMatcher<this>;
288 copy: IRouterMatcher<this>;
289 lock: IRouterMatcher<this>;
290 merge: IRouterMatcher<this>;
291 mkactivity: IRouterMatcher<this>;
292 mkcol: IRouterMatcher<this>;
293 move: IRouterMatcher<this>;
294 'm-search': IRouterMatcher<this>;
295 notify: IRouterMatcher<this>;
296 propfind: IRouterMatcher<this>;
297 proppatch: IRouterMatcher<this>;
298 purge: IRouterMatcher<this>;
299 report: IRouterMatcher<this>;
300 search: IRouterMatcher<this>;
301 subscribe: IRouterMatcher<this>;
302 trace: IRouterMatcher<this>;
303 unlock: IRouterMatcher<this>;
304 unsubscribe: IRouterMatcher<this>;
305 link: IRouterMatcher<this>;
306 unlink: IRouterMatcher<this>;
307
308 use: IRouterHandler<this> & IRouterMatcher<this>;
309
310 route<T extends string>(prefix: T): IRoute<T>;
311 route(prefix: PathParams): IRoute;
312 /**
313 * Stack of configured routes
314 */
315 stack: any[];
316}
317
318export interface IRoute<Route extends string = string> {
319 path: string;
320 stack: any;
321 all: IRouterHandler<this, Route>;
322 get: IRouterHandler<this, Route>;
323 post: IRouterHandler<this, Route>;
324 put: IRouterHandler<this, Route>;
325 delete: IRouterHandler<this, Route>;
326 patch: IRouterHandler<this, Route>;
327 options: IRouterHandler<this, Route>;
328 head: IRouterHandler<this, Route>;
329
330 checkout: IRouterHandler<this, Route>;
331 copy: IRouterHandler<this, Route>;
332 lock: IRouterHandler<this, Route>;
333 merge: IRouterHandler<this, Route>;
334 mkactivity: IRouterHandler<this, Route>;
335 mkcol: IRouterHandler<this, Route>;
336 move: IRouterHandler<this, Route>;
337 'm-search': IRouterHandler<this, Route>;
338 notify: IRouterHandler<this, Route>;
339 purge: IRouterHandler<this, Route>;
340 report: IRouterHandler<this, Route>;
341 search: IRouterHandler<this, Route>;
342 subscribe: IRouterHandler<this, Route>;
343 trace: IRouterHandler<this, Route>;
344 unlock: IRouterHandler<this, Route>;
345 unsubscribe: IRouterHandler<this, Route>;
346}
347
348export interface Router extends IRouter {}
349
350export interface CookieOptions {
351 maxAge?: number | undefined;
352 signed?: boolean | undefined;
353 expires?: Date | undefined;
354 httpOnly?: boolean | undefined;
355 path?: string | undefined;
356 domain?: string | undefined;
357 secure?: boolean | undefined;
358 encode?: ((val: string) => string) | undefined;
359 sameSite?: boolean | 'lax' | 'strict' | 'none' | undefined;
360}
361
362export interface ByteRange {
363 start: number;
364 end: number;
365}
366
367export interface RequestRanges extends RangeParserRanges {}
368
369export type Errback = (err: Error) => void;
370
371/**
372 * @param P For most requests, this should be `ParamsDictionary`, but if you're
373 * using this in a route handler for a route that uses a `RegExp` or a wildcard
374 * `string` path (e.g. `'/user/*'`), then `req.params` will be an array, in
375 * which case you should use `ParamsArray` instead.
376 *
377 * @see https://expressjs.com/en/api.html#req.params
378 *
379 * @example
380 * app.get('/user/:id', (req, res) => res.send(req.params.id)); // implicitly `ParamsDictionary`
381 * app.get<ParamsArray>(/user\/(.*)/, (req, res) => res.send(req.params[0]));
382 * app.get<ParamsArray>('/user/*', (req, res) => res.send(req.params[0]));
383 */
384export interface Request<
385 P = ParamsDictionary,
386 ResBody = any,
387 ReqBody = any,
388 ReqQuery = ParsedQs,
389 LocalsObj extends Record<string, any> = Record<string, any>
390> extends http.IncomingMessage,
391 Express.Request {
392 /**
393 * Return request header.
394 *
395 * The `Referrer` header field is special-cased,
396 * both `Referrer` and `Referer` are interchangeable.
397 *
398 * Examples:
399 *
400 * req.get('Content-Type');
401 * // => "text/plain"
402 *
403 * req.get('content-type');
404 * // => "text/plain"
405 *
406 * req.get('Something');
407 * // => undefined
408 *
409 * Aliased as `req.header()`.
410 */
411 get(name: 'set-cookie'): string[] | undefined;
412 get(name: string): string | undefined;
413
414 header(name: 'set-cookie'): string[] | undefined;
415 header(name: string): string | undefined;
416
417 /**
418 * Check if the given `type(s)` is acceptable, returning
419 * the best match when true, otherwise `undefined`, in which
420 * case you should respond with 406 "Not Acceptable".
421 *
422 * The `type` value may be a single mime type string
423 * such as "application/json", the extension name
424 * such as "json", a comma-delimted list such as "json, html, text/plain",
425 * or an array `["json", "html", "text/plain"]`. When a list
426 * or array is given the _best_ match, if any is returned.
427 *
428 * Examples:
429 *
430 * // Accept: text/html
431 * req.accepts('html');
432 * // => "html"
433 *
434 * // Accept: text/*, application/json
435 * req.accepts('html');
436 * // => "html"
437 * req.accepts('text/html');
438 * // => "text/html"
439 * req.accepts('json, text');
440 * // => "json"
441 * req.accepts('application/json');
442 * // => "application/json"
443 *
444 * // Accept: text/*, application/json
445 * req.accepts('image/png');
446 * req.accepts('png');
447 * // => undefined
448 *
449 * // Accept: text/*;q=.5, application/json
450 * req.accepts(['html', 'json']);
451 * req.accepts('html, json');
452 * // => "json"
453 */
454 accepts(): string[];
455 accepts(type: string): string | false;
456 accepts(type: string[]): string | false;
457 accepts(...type: string[]): string | false;
458
459 /**
460 * Returns the first accepted charset of the specified character sets,
461 * based on the request's Accept-Charset HTTP header field.
462 * If none of the specified charsets is accepted, returns false.
463 *
464 * For more information, or if you have issues or concerns, see accepts.
465 */
466 acceptsCharsets(): string[];
467 acceptsCharsets(charset: string): string | false;
468 acceptsCharsets(charset: string[]): string | false;
469 acceptsCharsets(...charset: string[]): string | false;
470
471 /**
472 * Returns the first accepted encoding of the specified encodings,
473 * based on the request's Accept-Encoding HTTP header field.
474 * If none of the specified encodings is accepted, returns false.
475 *
476 * For more information, or if you have issues or concerns, see accepts.
477 */
478 acceptsEncodings(): string[];
479 acceptsEncodings(encoding: string): string | false;
480 acceptsEncodings(encoding: string[]): string | false;
481 acceptsEncodings(...encoding: string[]): string | false;
482
483 /**
484 * Returns the first accepted language of the specified languages,
485 * based on the request's Accept-Language HTTP header field.
486 * If none of the specified languages is accepted, returns false.
487 *
488 * For more information, or if you have issues or concerns, see accepts.
489 */
490 acceptsLanguages(): string[];
491 acceptsLanguages(lang: string): string | false;
492 acceptsLanguages(lang: string[]): string | false;
493 acceptsLanguages(...lang: string[]): string | false;
494
495 /**
496 * Parse Range header field, capping to the given `size`.
497 *
498 * Unspecified ranges such as "0-" require knowledge of your resource length. In
499 * the case of a byte range this is of course the total number of bytes.
500 * If the Range header field is not given `undefined` is returned.
501 * If the Range header field is given, return value is a result of range-parser.
502 * See more ./types/range-parser/index.d.ts
503 *
504 * NOTE: remember that ranges are inclusive, so for example "Range: users=0-3"
505 * should respond with 4 users when available, not 3.
506 *
507 */
508 range(size: number, options?: RangeParserOptions): RangeParserRanges | RangeParserResult | undefined;
509
510 /**
511 * Return an array of Accepted media types
512 * ordered from highest quality to lowest.
513 */
514 accepted: MediaType[];
515
516 /**
517 * @deprecated since 4.11 Use either req.params, req.body or req.query, as applicable.
518 *
519 * Return the value of param `name` when present or `defaultValue`.
520 *
521 * - Checks route placeholders, ex: _/user/:id_
522 * - Checks body params, ex: id=12, {"id":12}
523 * - Checks query string params, ex: ?id=12
524 *
525 * To utilize request bodies, `req.body`
526 * should be an object. This can be done by using
527 * the `connect.bodyParser()` middleware.
528 */
529 param(name: string, defaultValue?: any): string;
530
531 /**
532 * Check if the incoming request contains the "Content-Type"
533 * header field, and it contains the give mime `type`.
534 *
535 * Examples:
536 *
537 * // With Content-Type: text/html; charset=utf-8
538 * req.is('html');
539 * req.is('text/html');
540 * req.is('text/*');
541 * // => true
542 *
543 * // When Content-Type is application/json
544 * req.is('json');
545 * req.is('application/json');
546 * req.is('application/*');
547 * // => true
548 *
549 * req.is('html');
550 * // => false
551 */
552 is(type: string | string[]): string | false | null;
553
554 /**
555 * Return the protocol string "http" or "https"
556 * when requested with TLS. When the "trust proxy"
557 * setting is enabled the "X-Forwarded-Proto" header
558 * field will be trusted. If you're running behind
559 * a reverse proxy that supplies https for you this
560 * may be enabled.
561 */
562 protocol: string;
563
564 /**
565 * Short-hand for:
566 *
567 * req.protocol == 'https'
568 */
569 secure: boolean;
570
571 /**
572 * Return the remote address, or when
573 * "trust proxy" is `true` return
574 * the upstream addr.
575 */
576 ip: string;
577
578 /**
579 * When "trust proxy" is `true`, parse
580 * the "X-Forwarded-For" ip address list.
581 *
582 * For example if the value were "client, proxy1, proxy2"
583 * you would receive the array `["client", "proxy1", "proxy2"]`
584 * where "proxy2" is the furthest down-stream.
585 */
586 ips: string[];
587
588 /**
589 * Return subdomains as an array.
590 *
591 * Subdomains are the dot-separated parts of the host before the main domain of
592 * the app. By default, the domain of the app is assumed to be the last two
593 * parts of the host. This can be changed by setting "subdomain offset".
594 *
595 * For example, if the domain is "tobi.ferrets.example.com":
596 * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`.
597 * If "subdomain offset" is 3, req.subdomains is `["tobi"]`.
598 */
599 subdomains: string[];
600
601 /**
602 * Short-hand for `url.parse(req.url).pathname`.
603 */
604 path: string;
605
606 /**
607 * Parse the "Host" header field hostname.
608 */
609 hostname: string;
610
611 /**
612 * @deprecated Use hostname instead.
613 */
614 host: string;
615
616 /**
617 * Check if the request is fresh, aka
618 * Last-Modified and/or the ETag
619 * still match.
620 */
621 fresh: boolean;
622
623 /**
624 * Check if the request is stale, aka
625 * "Last-Modified" and / or the "ETag" for the
626 * resource has changed.
627 */
628 stale: boolean;
629
630 /**
631 * Check if the request was an _XMLHttpRequest_.
632 */
633 xhr: boolean;
634
635 //body: { username: string; password: string; remember: boolean; title: string; };
636 body: ReqBody;
637
638 //cookies: { string; remember: boolean; };
639 cookies: any;
640
641 method: string;
642
643 params: P;
644
645 query: ReqQuery;
646
647 route: any;
648
649 signedCookies: any;
650
651 originalUrl: string;
652
653 url: string;
654
655 baseUrl: string;
656
657 app: Application;
658
659 /**
660 * After middleware.init executed, Request will contain res and next properties
661 * See: express/lib/middleware/init.js
662 */
663 res?: Response<ResBody, LocalsObj> | undefined;
664 next?: NextFunction | undefined;
665}
666
667export interface MediaType {
668 value: string;
669 quality: number;
670 type: string;
671 subtype: string;
672}
673
674export type Send<ResBody = any, T = Response<ResBody>> = (body?: ResBody) => T;
675
676export interface SendFileOptions extends SendOptions {
677 /** Object containing HTTP headers to serve with the file. */
678 headers?: Record<string, unknown>;
679}
680
681export interface DownloadOptions extends SendOptions {
682 /** Object containing HTTP headers to serve with the file. The header `Content-Disposition` will be overridden by the filename argument. */
683 headers?: Record<string, unknown>;
684}
685
686export interface Response<
687 ResBody = any,
688 LocalsObj extends Record<string, any> = Record<string, any>,
689 StatusCode extends number = number
690> extends http.ServerResponse,
691 Express.Response {
692 /**
693 * Set status `code`.
694 */
695 status(code: StatusCode): this;
696
697 /**
698 * Set the response HTTP status code to `statusCode` and send its string representation as the response body.
699 * @link http://expressjs.com/4x/api.html#res.sendStatus
700 *
701 * Examples:
702 *
703 * res.sendStatus(200); // equivalent to res.status(200).send('OK')
704 * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden')
705 * res.sendStatus(404); // equivalent to res.status(404).send('Not Found')
706 * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error')
707 */
708 sendStatus(code: StatusCode): this;
709
710 /**
711 * Set Link header field with the given `links`.
712 *
713 * Examples:
714 *
715 * res.links({
716 * next: 'http://api.example.com/users?page=2',
717 * last: 'http://api.example.com/users?page=5'
718 * });
719 */
720 links(links: any): this;
721
722 /**
723 * Send a response.
724 *
725 * Examples:
726 *
727 * res.send(new Buffer('wahoo'));
728 * res.send({ some: 'json' });
729 * res.send('<p>some html</p>');
730 * res.status(404).send('Sorry, cant find that');
731 */
732 send: Send<ResBody, this>;
733
734 /**
735 * Send JSON response.
736 *
737 * Examples:
738 *
739 * res.json(null);
740 * res.json({ user: 'tj' });
741 * res.status(500).json('oh noes!');
742 * res.status(404).json('I dont have that');
743 */
744 json: Send<ResBody, this>;
745
746 /**
747 * Send JSON response with JSONP callback support.
748 *
749 * Examples:
750 *
751 * res.jsonp(null);
752 * res.jsonp({ user: 'tj' });
753 * res.status(500).jsonp('oh noes!');
754 * res.status(404).jsonp('I dont have that');
755 */
756 jsonp: Send<ResBody, this>;
757
758 /**
759 * Transfer the file at the given `path`.
760 *
761 * Automatically sets the _Content-Type_ response header field.
762 * The callback `fn(err)` is invoked when the transfer is complete
763 * or when an error occurs. Be sure to check `res.headersSent`
764 * if you wish to attempt responding, as the header and some data
765 * may have already been transferred.
766 *
767 * Options:
768 *
769 * - `maxAge` defaulting to 0 (can be string converted by `ms`)
770 * - `root` root directory for relative filenames
771 * - `headers` object of headers to serve with file
772 * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them
773 *
774 * Other options are passed along to `send`.
775 *
776 * Examples:
777 *
778 * The following example illustrates how `res.sendFile()` may
779 * be used as an alternative for the `static()` middleware for
780 * dynamic situations. The code backing `res.sendFile()` is actually
781 * the same code, so HTTP cache support etc is identical.
782 *
783 * app.get('/user/:uid/photos/:file', function(req, res){
784 * var uid = req.params.uid
785 * , file = req.params.file;
786 *
787 * req.user.mayViewFilesFrom(uid, function(yes){
788 * if (yes) {
789 * res.sendFile('/uploads/' + uid + '/' + file);
790 * } else {
791 * res.send(403, 'Sorry! you cant see that.');
792 * }
793 * });
794 * });
795 *
796 * @api public
797 */
798 sendFile(path: string, fn?: Errback): void;
799 sendFile(path: string, options: SendFileOptions, fn?: Errback): void;
800
801 /**
802 * @deprecated Use sendFile instead.
803 */
804 sendfile(path: string): void;
805 /**
806 * @deprecated Use sendFile instead.
807 */
808 sendfile(path: string, options: SendFileOptions): void;
809 /**
810 * @deprecated Use sendFile instead.
811 */
812 sendfile(path: string, fn: Errback): void;
813 /**
814 * @deprecated Use sendFile instead.
815 */
816 sendfile(path: string, options: SendFileOptions, fn: Errback): void;
817
818 /**
819 * Transfer the file at the given `path` as an attachment.
820 *
821 * Optionally providing an alternate attachment `filename`,
822 * and optional callback `fn(err)`. The callback is invoked
823 * when the data transfer is complete, or when an error has
824 * ocurred. Be sure to check `res.headersSent` if you plan to respond.
825 *
826 * The optional options argument passes through to the underlying
827 * res.sendFile() call, and takes the exact same parameters.
828 *
829 * This method uses `res.sendfile()`.
830 */
831 download(path: string, fn?: Errback): void;
832 download(path: string, filename: string, fn?: Errback): void;
833 download(path: string, filename: string, options: DownloadOptions, fn?: Errback): void;
834
835 /**
836 * Set _Content-Type_ response header with `type` through `mime.lookup()`
837 * when it does not contain "/", or set the Content-Type to `type` otherwise.
838 *
839 * Examples:
840 *
841 * res.type('.html');
842 * res.type('html');
843 * res.type('json');
844 * res.type('application/json');
845 * res.type('png');
846 */
847 contentType(type: string): this;
848
849 /**
850 * Set _Content-Type_ response header with `type` through `mime.lookup()`
851 * when it does not contain "/", or set the Content-Type to `type` otherwise.
852 *
853 * Examples:
854 *
855 * res.type('.html');
856 * res.type('html');
857 * res.type('json');
858 * res.type('application/json');
859 * res.type('png');
860 */
861 type(type: string): this;
862
863 /**
864 * Respond to the Acceptable formats using an `obj`
865 * of mime-type callbacks.
866 *
867 * This method uses `req.accepted`, an array of
868 * acceptable types ordered by their quality values.
869 * When "Accept" is not present the _first_ callback
870 * is invoked, otherwise the first match is used. When
871 * no match is performed the server responds with
872 * 406 "Not Acceptable".
873 *
874 * Content-Type is set for you, however if you choose
875 * you may alter this within the callback using `res.type()`
876 * or `res.set('Content-Type', ...)`.
877 *
878 * res.format({
879 * 'text/plain': function(){
880 * res.send('hey');
881 * },
882 *
883 * 'text/html': function(){
884 * res.send('<p>hey</p>');
885 * },
886 *
887 * 'appliation/json': function(){
888 * res.send({ message: 'hey' });
889 * }
890 * });
891 *
892 * In addition to canonicalized MIME types you may
893 * also use extnames mapped to these types:
894 *
895 * res.format({
896 * text: function(){
897 * res.send('hey');
898 * },
899 *
900 * html: function(){
901 * res.send('<p>hey</p>');
902 * },
903 *
904 * json: function(){
905 * res.send({ message: 'hey' });
906 * }
907 * });
908 *
909 * By default Express passes an `Error`
910 * with a `.status` of 406 to `next(err)`
911 * if a match is not made. If you provide
912 * a `.default` callback it will be invoked
913 * instead.
914 */
915 format(obj: any): this;
916
917 /**
918 * Set _Content-Disposition_ header to _attachment_ with optional `filename`.
919 */
920 attachment(filename?: string): this;
921
922 /**
923 * Set header `field` to `val`, or pass
924 * an object of header fields.
925 *
926 * Examples:
927 *
928 * res.set('Foo', ['bar', 'baz']);
929 * res.set('Accept', 'application/json');
930 * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' });
931 *
932 * Aliased as `res.header()`.
933 */
934 set(field: any): this;
935 set(field: string, value?: string | string[]): this;
936
937 header(field: any): this;
938 header(field: string, value?: string | string[]): this;
939
940 // Property indicating if HTTP headers has been sent for the response.
941 headersSent: boolean;
942
943 /** Get value for header `field`. */
944 get(field: string): string|undefined;
945
946 /** Clear cookie `name`. */
947 clearCookie(name: string, options?: CookieOptions): this;
948
949 /**
950 * Set cookie `name` to `val`, with the given `options`.
951 *
952 * Options:
953 *
954 * - `maxAge` max-age in milliseconds, converted to `expires`
955 * - `signed` sign the cookie
956 * - `path` defaults to "/"
957 *
958 * Examples:
959 *
960 * // "Remember Me" for 15 minutes
961 * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true });
962 *
963 * // save as above
964 * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true })
965 */
966 cookie(name: string, val: string, options: CookieOptions): this;
967 cookie(name: string, val: any, options: CookieOptions): this;
968 cookie(name: string, val: any): this;
969
970 /**
971 * Set the location header to `url`.
972 *
973 * The given `url` can also be the name of a mapped url, for
974 * example by default express supports "back" which redirects
975 * to the _Referrer_ or _Referer_ headers or "/".
976 *
977 * Examples:
978 *
979 * res.location('/foo/bar').;
980 * res.location('http://example.com');
981 * res.location('../login'); // /blog/post/1 -> /blog/login
982 *
983 * Mounting:
984 *
985 * When an application is mounted and `res.location()`
986 * is given a path that does _not_ lead with "/" it becomes
987 * relative to the mount-point. For example if the application
988 * is mounted at "/blog", the following would become "/blog/login".
989 *
990 * res.location('login');
991 *
992 * While the leading slash would result in a location of "/login":
993 *
994 * res.location('/login');
995 */
996 location(url: string): this;
997
998 /**
999 * Redirect to the given `url` with optional response `status`
1000 * defaulting to 302.
1001 *
1002 * The resulting `url` is determined by `res.location()`, so
1003 * it will play nicely with mounted apps, relative paths,
1004 * `"back"` etc.
1005 *
1006 * Examples:
1007 *
1008 * res.redirect('back');
1009 * res.redirect('/foo/bar');
1010 * res.redirect('http://example.com');
1011 * res.redirect(301, 'http://example.com');
1012 * res.redirect('http://example.com', 301);
1013 * res.redirect('../login'); // /blog/post/1 -> /blog/login
1014 */
1015 redirect(url: string): void;
1016 redirect(status: number, url: string): void;
1017 /** @deprecated use res.redirect(status, url) instead */
1018 redirect(url: string, status: number): void;
1019
1020 /**
1021 * Render `view` with the given `options` and optional callback `fn`.
1022 * When a callback function is given a response will _not_ be made
1023 * automatically, otherwise a response of _200_ and _text/html_ is given.
1024 *
1025 * Options:
1026 *
1027 * - `cache` boolean hinting to the engine it should cache
1028 * - `filename` filename of the view being rendered
1029 */
1030 render(view: string, options?: object, callback?: (err: Error, html: string) => void): void;
1031 render(view: string, callback?: (err: Error, html: string) => void): void;
1032
1033 locals: LocalsObj & Locals;
1034
1035 charset: string;
1036
1037 /**
1038 * Adds the field to the Vary response header, if it is not there already.
1039 * Examples:
1040 *
1041 * res.vary('User-Agent').render('docs');
1042 *
1043 */
1044 vary(field: string): this;
1045
1046 app: Application;
1047
1048 /**
1049 * Appends the specified value to the HTTP response header field.
1050 * If the header is not already set, it creates the header with the specified value.
1051 * The value parameter can be a string or an array.
1052 *
1053 * Note: calling res.set() after res.append() will reset the previously-set header value.
1054 *
1055 * @since 4.11.0
1056 */
1057 append(field: string, value?: string[] | string): this;
1058
1059 /**
1060 * After middleware.init executed, Response will contain req property
1061 * See: express/lib/middleware/init.js
1062 */
1063 req: Request;
1064}
1065
1066export interface Handler extends RequestHandler {}
1067
1068export type RequestParamHandler = (req: Request, res: Response, next: NextFunction, value: any, name: string) => any;
1069
1070export type ApplicationRequestHandler<T> = IRouterHandler<T> &
1071 IRouterMatcher<T> &
1072 ((...handlers: RequestHandlerParams[]) => T);
1073
1074export interface Application<
1075 LocalsObj extends Record<string, any> = Record<string, any>
1076> extends EventEmitter, IRouter, Express.Application {
1077 /**
1078 * Express instance itself is a request handler, which could be invoked without
1079 * third argument.
1080 */
1081 (req: Request | http.IncomingMessage, res: Response | http.ServerResponse): any;
1082
1083 /**
1084 * Initialize the server.
1085 *
1086 * - setup default configuration
1087 * - setup default middleware
1088 * - setup route reflection methods
1089 */
1090 init(): void;
1091
1092 /**
1093 * Initialize application configuration.
1094 */
1095 defaultConfiguration(): void;
1096
1097 /**
1098 * Register the given template engine callback `fn`
1099 * as `ext`.
1100 *
1101 * By default will `require()` the engine based on the
1102 * file extension. For example if you try to render
1103 * a "foo.jade" file Express will invoke the following internally:
1104 *
1105 * app.engine('jade', require('jade').__express);
1106 *
1107 * For engines that do not provide `.__express` out of the box,
1108 * or if you wish to "map" a different extension to the template engine
1109 * you may use this method. For example mapping the EJS template engine to
1110 * ".html" files:
1111 *
1112 * app.engine('html', require('ejs').renderFile);
1113 *
1114 * In this case EJS provides a `.renderFile()` method with
1115 * the same signature that Express expects: `(path, options, callback)`,
1116 * though note that it aliases this method as `ejs.__express` internally
1117 * so if you're using ".ejs" extensions you dont need to do anything.
1118 *
1119 * Some template engines do not follow this convention, the
1120 * [Consolidate.js](https://github.com/visionmedia/consolidate.js)
1121 * library was created to map all of node's popular template
1122 * engines to follow this convention, thus allowing them to
1123 * work seamlessly within Express.
1124 */
1125 engine(
1126 ext: string,
1127 fn: (path: string, options: object, callback: (e: any, rendered?: string) => void) => void,
1128 ): this;
1129
1130 /**
1131 * Assign `setting` to `val`, or return `setting`'s value.
1132 *
1133 * app.set('foo', 'bar');
1134 * app.get('foo');
1135 * // => "bar"
1136 * app.set('foo', ['bar', 'baz']);
1137 * app.get('foo');
1138 * // => ["bar", "baz"]
1139 *
1140 * Mounted servers inherit their parent server's settings.
1141 */
1142 set(setting: string, val: any): this;
1143 get: ((name: string) => any) & IRouterMatcher<this>;
1144
1145 param(name: string | string[], handler: RequestParamHandler): this;
1146
1147 /**
1148 * Alternatively, you can pass only a callback, in which case you have the opportunity to alter the app.param()
1149 *
1150 * @deprecated since version 4.11
1151 */
1152 param(callback: (name: string, matcher: RegExp) => RequestParamHandler): this;
1153
1154 /**
1155 * Return the app's absolute pathname
1156 * based on the parent(s) that have
1157 * mounted it.
1158 *
1159 * For example if the application was
1160 * mounted as "/admin", which itself
1161 * was mounted as "/blog" then the
1162 * return value would be "/blog/admin".
1163 */
1164 path(): string;
1165
1166 /**
1167 * Check if `setting` is enabled (truthy).
1168 *
1169 * app.enabled('foo')
1170 * // => false
1171 *
1172 * app.enable('foo')
1173 * app.enabled('foo')
1174 * // => true
1175 */
1176 enabled(setting: string): boolean;
1177
1178 /**
1179 * Check if `setting` is disabled.
1180 *
1181 * app.disabled('foo')
1182 * // => true
1183 *
1184 * app.enable('foo')
1185 * app.disabled('foo')
1186 * // => false
1187 */
1188 disabled(setting: string): boolean;
1189
1190 /** Enable `setting`. */
1191 enable(setting: string): this;
1192
1193 /** Disable `setting`. */
1194 disable(setting: string): this;
1195
1196 /**
1197 * Render the given view `name` name with `options`
1198 * and a callback accepting an error and the
1199 * rendered template string.
1200 *
1201 * Example:
1202 *
1203 * app.render('email', { name: 'Tobi' }, function(err, html){
1204 * // ...
1205 * })
1206 */
1207 render(name: string, options?: object, callback?: (err: Error, html: string) => void): void;
1208 render(name: string, callback: (err: Error, html: string) => void): void;
1209
1210 /**
1211 * Listen for connections.
1212 *
1213 * A node `http.Server` is returned, with this
1214 * application (which is a `Function`) as its
1215 * callback. If you wish to create both an HTTP
1216 * and HTTPS server you may do so with the "http"
1217 * and "https" modules as shown here:
1218 *
1219 * var http = require('http')
1220 * , https = require('https')
1221 * , express = require('express')
1222 * , app = express();
1223 *
1224 * http.createServer(app).listen(80);
1225 * https.createServer({ ... }, app).listen(443);
1226 */
1227 listen(port: number, hostname: string, backlog: number, callback?: () => void): http.Server;
1228 listen(port: number, hostname: string, callback?: () => void): http.Server;
1229 listen(port: number, callback?: () => void): http.Server;
1230 listen(callback?: () => void): http.Server;
1231 listen(path: string, callback?: () => void): http.Server;
1232 listen(handle: any, listeningListener?: () => void): http.Server;
1233
1234 router: string;
1235
1236 settings: any;
1237
1238 resource: any;
1239
1240 map: any;
1241
1242 locals: LocalsObj & Locals;
1243
1244 /**
1245 * The app.routes object houses all of the routes defined mapped by the
1246 * associated HTTP verb. This object may be used for introspection
1247 * capabilities, for example Express uses this internally not only for
1248 * routing but to provide default OPTIONS behaviour unless app.options()
1249 * is used. Your application or framework may also remove routes by
1250 * simply by removing them from this object.
1251 */
1252 routes: any;
1253
1254 /**
1255 * Used to get all registered routes in Express Application
1256 */
1257 _router: any;
1258
1259 use: ApplicationRequestHandler<this>;
1260
1261 /**
1262 * The mount event is fired on a sub-app, when it is mounted on a parent app.
1263 * The parent app is passed to the callback function.
1264 *
1265 * NOTE:
1266 * Sub-apps will:
1267 * - Not inherit the value of settings that have a default value. You must set the value in the sub-app.
1268 * - Inherit the value of settings with no default value.
1269 */
1270 on: (event: string, callback: (parent: Application) => void) => this;
1271
1272 /**
1273 * The app.mountpath property contains one or more path patterns on which a sub-app was mounted.
1274 */
1275 mountpath: string | string[];
1276}
1277
1278export interface Express extends Application {
1279 request: Request;
1280 response: Response;
1281}