UNPKG

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