├── index.d.ts ├── .gitignore ├── tsconfig.json ├── .travis.yml ├── test ├── router-options.ts ├── tsconfig.json ├── router.ts ├── static.ts ├── middleware.ts ├── params.ts └── app.ts ├── .editorconfig ├── typings.json ├── lib ├── router │ ├── layer.d.ts │ ├── route.d.ts │ └── index.d.ts ├── express.d.ts ├── application.d.ts ├── request.d.ts └── response.d.ts ├── package.json ├── README.md └── tslint.json /index.d.ts: -------------------------------------------------------------------------------- 1 | 2 | import express = require('./lib/express'); 3 | export = express; 4 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | typings/ 2 | node_modules/ 3 | test/bundle.d.ts 4 | *.js 5 | package-lock.json 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "module": "commonjs", 4 | "noImplicitAny": true 5 | } 6 | } 7 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | 2 | language: node_js 3 | 4 | node_js: 5 | - 8 6 | 7 | install: 8 | - npm install --only=dev 9 | - typings install 10 | 11 | script: 12 | - npm run lint 13 | - npm run build 14 | - npm test 15 | -------------------------------------------------------------------------------- /test/router-options.ts: -------------------------------------------------------------------------------- 1 | 2 | import {Router, RouterOptions} from 'express'; 3 | 4 | const options: RouterOptions = { 5 | caseSensitive: true, 6 | mergeParams: true, 7 | strict: true 8 | }; 9 | 10 | const router = Router(options); 11 | 12 | export default router; 13 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | 2 | [*] 3 | insert_spaces = true 4 | indent_size = 4 5 | trim_trailing_whitespace = true 6 | insert_final_newline = true 7 | encoding = utf-8 8 | 9 | [*.{json,yml}] 10 | indent_size = 2 11 | 12 | [tslint.json] 13 | indent_size = 4 14 | 15 | [*.md] 16 | trim_trailing_whitespace = false 17 | -------------------------------------------------------------------------------- /test/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compilerOptions": { 3 | "target": "es5", 4 | "noImplicitAny": true, 5 | "module": "commonjs", 6 | "moduleResolution": "node" 7 | }, 8 | "files": [ 9 | "../typings/index.d.ts", 10 | "bundle.d.ts", 11 | "app.ts", 12 | "middleware.ts", 13 | "params.ts", 14 | "router.ts", 15 | "router-options.ts", 16 | "static.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /typings.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "express", 3 | "main": "index.d.ts", 4 | "version": "4.14.0", 5 | "homepage": "https://github.com/types/npm-express", 6 | "dependencies": { 7 | "path-to-regexp": "github:pillarjs/path-to-regexp/index.d.ts#ec285ed3500aed455df59e3b8b07f473412918a4", 8 | "serve-static": "registry:npm/serve-static#1.11.1+20161113104247" 9 | }, 10 | "globalDependencies": { 11 | "node": "registry:env/node#6.0.0+20170115054122" 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /test/router.ts: -------------------------------------------------------------------------------- 1 | 2 | import {Router, Request, Response, NextFunction} from 'express'; 3 | 4 | const router = Router(); 5 | 6 | router.move('/somepath', (req: Request, res: Response) => { 7 | res.set('Location', res.get('Destination')); 8 | }); 9 | 10 | router.route('/someroute') 11 | .get((req: Request, res: Response, next: NextFunction) => { 12 | req.accepts('application/json'); 13 | console.log('hello'); 14 | }); 15 | 16 | export default router; 17 | -------------------------------------------------------------------------------- /lib/router/layer.d.ts: -------------------------------------------------------------------------------- 1 | 2 | import {Options, Token} from 'path-to-regexp'; 3 | 4 | declare interface Layer { 5 | handle?: Function; 6 | name: string; 7 | params?: any; 8 | path?: string; 9 | keys: Token[]; 10 | regexp: RegExp; 11 | method: string; 12 | } 13 | 14 | declare const Layer: { 15 | (path: string, options?: Options, fn?: Function): Layer; 16 | new (path: string, options?: Options, fn?: Function): Layer; 17 | }; 18 | 19 | export = Layer; 20 | -------------------------------------------------------------------------------- /test/static.ts: -------------------------------------------------------------------------------- 1 | 2 | import express = require('express'); 3 | import {Stats} from 'fs'; 4 | 5 | const app = express(); 6 | 7 | // test that it's possible to use the static middleware 8 | app.use(express.static('/whatever', { 9 | etag: true, 10 | setHeaders(res: express.Response, path: string, stat: Stats) { 11 | // test that it's possible to type `res` as an express response instead of http.ServerResponse 12 | res.set('My-Header', 'my value'); 13 | } 14 | })); 15 | -------------------------------------------------------------------------------- /test/middleware.ts: -------------------------------------------------------------------------------- 1 | 2 | // writing middleware that modifyies req 3 | 4 | import createApplication = require('express'); 5 | import {Request, Response, NextFunction, RequestHandler} from 'express'; 6 | 7 | const app = createApplication(); 8 | 9 | class User { 10 | username: string; 11 | } 12 | 13 | interface Authenticated { 14 | user: User; 15 | } 16 | 17 | const userMiddleware: RequestHandler = (req: Request & Authenticated, res: Response, next: NextFunction) => { 18 | req.user = new User(); 19 | }; 20 | 21 | app.post('/echo', userMiddleware, (req: Request & Authenticated, res: Response, next: NextFunction) => { 22 | console.log(req.user.username); 23 | }); 24 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "@types/express", 3 | "version": "4.14.0", 4 | "private": true, 5 | "description": "TypeScript Typings for express", 6 | "typings": "index.d.ts", 7 | "scripts": { 8 | "build": "typings bundle -o test/bundle.d.ts", 9 | "test": "tsc -p test", 10 | "lint": "tslint -c tslint.json index.d.ts lib/**/*.d.ts test/**/*.ts" 11 | }, 12 | "author": "Felix Becker ", 13 | "license": "ISC", 14 | "devDependencies": { 15 | "tslint": "^5.4.3", 16 | "typescript": "^2.3.4", 17 | "typings": "^2.1.1" 18 | }, 19 | "peerDependencies": { 20 | "@types/node": "*" 21 | }, 22 | "dependencies": { 23 | "@types/serve-static": "github:types/npm-serve-static#c1f96843c8b96a37f6c534cb1dadb48f5329e4e0", 24 | "path-to-regexp": "github:pillarjs/path-to-regexp#ec285ed3500aed455df59e3b8b07f473412918a4" 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Typed express 2 | 3 | [![Greenkeeper badge](https://badges.greenkeeper.io/types/npm-express.svg)](https://greenkeeper.io/) 4 | [![Build Status](https://travis-ci.org/types/npm-express.svg?branch=master)](https://travis-ci.org/types/npm-express) 5 | 6 | Typescript Typings for [express](https://github.com/expressjs/express). 7 | 8 | ## Installation 9 | 10 | typings install --save express 11 | 12 | or 13 | 14 | npm install --save-dev types/npm-express# 15 | 16 | ## Usage 17 | 18 | ```ts 19 | import express = require('express'); 20 | 21 | const app = express(); 22 | 23 | app.get('/', (req: express.Request, res: express.Response) => { 24 | res.send('Hello World'); 25 | }); 26 | 27 | app.listen(3000); 28 | ``` 29 | 30 | [More examples](./test) 31 | 32 | ## Contributing 33 | You can run the tests by running `npm run build` and then `npm run test`. 34 | 35 | 36 | --------------------------------------- 37 | 38 | _Based on the typings by [Boris Yankov](https://github.com/borisyankov) on [DefinitelyTyped](https://github.com/DefinitelyTyped/DefinitelyTyped)_ 39 | 40 | -------------------------------------------------------------------------------- /test/params.ts: -------------------------------------------------------------------------------- 1 | 2 | // using req.params 3 | 4 | import express = require('express'); 5 | import {Request, Response, NextFunction} from 'express'; 6 | 7 | const app: express.Application = express(); 8 | 9 | // using params as hash 10 | app.post('/whatever/:aParam', (req: Request, res: Response, next: NextFunction) => { 11 | res.send(req.params['aParam']); 12 | }); 13 | 14 | // specifying the params as an interface 15 | interface WhateverParams { 16 | params: { 17 | aParam: string; 18 | }; 19 | } 20 | app.post('/whatever/:aParam', (req: Request & WhateverParams, res: Response, next: NextFunction) => { 21 | res.send(req.params.aParam); 22 | // accessing a non-existend param would now throw a compile-time error: 23 | // res.send(req.params.anotherParam); 24 | }); 25 | 26 | // specifying what's available inline 27 | app.post('/whatever/:aParam', (req: Request & {params: {aParam: string}}, res: Response, next: NextFunction) => { 28 | res.send(req.params.aParam); 29 | // accessing a non-existend param would now throw a compile-time error: 30 | // res.send(req.params.anotherParam); 31 | }); 32 | 33 | // regular expression matching group 34 | app.get(/hello(.*)world/, (req: Request, res: Response, next: NextFunction) => { 35 | res.send(req.params[1]); 36 | }); 37 | -------------------------------------------------------------------------------- /test/app.ts: -------------------------------------------------------------------------------- 1 | 2 | import express = require('express'); 3 | import {createServer} from 'http'; 4 | import router from './router'; 5 | 6 | const app = express(); 7 | 8 | createServer(app).listen(3000); 9 | 10 | // requesthandler 11 | const requestHandler: express.RequestHandler = (req, res, next) => { 12 | console.log(req.ip); 13 | res.json({hello: 'world'}); 14 | req.app.get('some_setting'); 15 | next(new Error()); 16 | }; 17 | 18 | app.get('/hello-world', (req: express.Request, res: express.Response, next: express.NextFunction) => { 19 | console.log(req.hostname); 20 | res.send('Hello World'); 21 | next(); 22 | }); 23 | 24 | app.put('/users/:userId', (req: express.Request, res: express.Response, next: express.NextFunction) => { 25 | res.status(400); 26 | }); 27 | 28 | // errorhandler 29 | const errorHandler: express.ErrorHandler = (err: any, req: express.Request, res: express.Response, next: express.NextFunction) => { 30 | console.error(err); 31 | }; 32 | 33 | app.use(errorHandler); 34 | 35 | app.use((err: any, req: express.Request, res: express.Response, next: express.NextFunction) => { 36 | console.error(err); 37 | }); 38 | 39 | // call with array 40 | app.use([requestHandler, requestHandler]); 41 | app.use(requestHandler, [requestHandler], errorHandler); 42 | 43 | // get / set 44 | app.set('some_setting', 'some_value'); 45 | console.log(app.get('some_setting')); 46 | 47 | // mount router 48 | app.use('/mountpath', router); 49 | app.use(/\/mountpath/, router); 50 | app.use(['/mountpath', /\/mountpath/], router); 51 | app.use(['/mountpath', '/mountpath(\.html)?', /\/[a-z](\.html)?/], router); 52 | app.use(router); 53 | 54 | app.listen(8080); 55 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rules": { 3 | "class-name": true, 4 | "comment-format": [true, "check-space"], 5 | "indent": [true, "spaces"], 6 | "no-duplicate-variable": true, 7 | "no-eval": true, 8 | "no-internal-module": true, 9 | "no-trailing-whitespace": true, 10 | "no-var-keyword": true, 11 | "one-line": [true, "check-catch", "check-finally", "check-else", "check-open-brace", "check-whitespace"], 12 | "quotemark": [true, "single"], 13 | "semicolon": [true, "always"], 14 | "triple-equals": [true, "allow-null-check"], 15 | "typedef-whitespace": [ 16 | true, 17 | { 18 | "call-signature": "nospace", 19 | "index-signature": "nospace", 20 | "parameter": "nospace", 21 | "property-declaration": "nospace", 22 | "variable-declaration": "nospace" 23 | }, 24 | { 25 | "call-signature": "onespace", 26 | "index-signature": "onespace", 27 | "parameter": "onespace", 28 | "property-declaration": "onespace", 29 | "variable-declaration": "onespace" 30 | } 31 | ], 32 | "variable-name": [true, "ban-keywords"], 33 | "whitespace": [true, "check-branch", "check-decl", "check-operator", "check-separator", "check-type"], 34 | "jsdoc-format": true, 35 | "no-consecutive-blank-lines": true, 36 | "one-variable-per-declaration": [true, "ignore-for-loop"], 37 | "curly": true, 38 | "no-empty": true, 39 | "no-duplicate-key": true, 40 | "no-unreachable": true, 41 | "no-unused-expression": true, 42 | "no-unused-variable": [true], 43 | "eofline": true, 44 | "trailing-comma": [true, {"singleline": "never", "multiline": "never"}], 45 | "align": [true, "parameters", "statements"] 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /lib/express.d.ts: -------------------------------------------------------------------------------- 1 | 2 | import {IncomingMessage, ServerResponse} from 'http'; 3 | import {EventEmitter} from 'events'; 4 | import {Application as _Application} from './application'; 5 | import {Request as _Request} from './request'; 6 | import {Response as _Response, CookieOptions as _CookieOptions} from './response'; 7 | import createRouter = require('./router/index'); 8 | import RouteClass = require('./router/route'); 9 | import serveStatic = require('serve-static'); 10 | 11 | declare namespace createApplication { 12 | 13 | // workaround to reexport the interfaces 14 | export type Request = _Request 15 | export type Response = _Response 16 | export type CookieOptions = _CookieOptions 17 | export type Application = _Application 18 | export type Router = createRouter.Router 19 | export type RouterOptions = createRouter.RouterOptions 20 | export type RequestHandler = createRouter.RequestHandler 21 | export type ErrorHandler = createRouter.ErrorHandler 22 | export type ParamHandler = createRouter.ParamHandler 23 | export type Handler = createRouter.Handler 24 | export type NextFunction = createRouter.NextFunction 25 | 26 | export interface Server extends Application, EventEmitter { 27 | (req: IncomingMessage, res: ServerResponse, next?: (err?: Error) => void): void; 28 | } 29 | 30 | // need to use an interface for this because `static` is a reserved word 31 | // and cannot be used as a variable identifier 32 | export interface Express { 33 | 34 | /** Create an express application. */ 35 | (): Server; 36 | 37 | /** The Application prototype */ 38 | application: Application; 39 | 40 | /** The Request prototype */ 41 | request: Request; 42 | 43 | /** The Response prototype */ 44 | response: Response; 45 | 46 | /** The Route constructor */ 47 | Route: typeof RouteClass; 48 | 49 | /** The Router constructor */ 50 | Router: typeof createRouter; 51 | 52 | /** The serve-static middleware */ 53 | static: typeof serveStatic; 54 | 55 | // TODO query 56 | } 57 | } 58 | 59 | declare const createApplication: createApplication.Express; 60 | export = createApplication; 61 | -------------------------------------------------------------------------------- /lib/application.d.ts: -------------------------------------------------------------------------------- 1 | 2 | import {Server} from 'http'; 3 | import {ListenOptions} from 'net'; 4 | import {Router, ParamHandler, HandlerArgument, PathArgument} from './router/index'; 5 | 6 | declare namespace app { 7 | export interface Application extends Router { 8 | /** 9 | * Contains one or more path patterns on which a sub-app was mounted. 10 | */ 11 | mountpath: string | string[]; 12 | 13 | /** 14 | * Has properties that are local variables within the application. 15 | * Once set, the value of app.locals properties persist throughout the life of the application, 16 | * in contrast with res.locals properties that are valid only for the lifetime of the request. 17 | * You can access local variables in templates rendered within the application. 18 | * This is useful for providing helper functions to templates, as well as application-level data. 19 | * Local variables are available in middleware via req.app.locals (see req.app) 20 | */ 21 | locals: any; 22 | 23 | /** 24 | * Initialize the server. 25 | * 26 | * - setup default configuration 27 | * - setup default middleware 28 | * - setup route reflection methods 29 | */ 30 | init(): void; 31 | 32 | /** 33 | * Initialize application configuration. 34 | */ 35 | defaultConfiguration(): void; 36 | 37 | /** 38 | * Register the given template engine callback `fn` 39 | * as `ext`. 40 | * 41 | * By default will `require()` the engine based on the 42 | * file extension. For example if you try to render 43 | * a "foo.jade" file Express will invoke the following internally: 44 | * 45 | * app.engine('jade', require('jade').__express); 46 | * 47 | * For engines that do not provide `.__express` out of the box, 48 | * or if you wish to "map" a different extension to the template engine 49 | * you may use this method. For example mapping the EJS template engine to 50 | * ".html" files: 51 | * 52 | * app.engine('html', require('ejs').renderFile); 53 | * 54 | * In this case EJS provides a `.renderFile()` method with 55 | * the same signature that Express expects: `(path, options, callback)`, 56 | * though note that it aliases this method as `ejs.__express` internally 57 | * so if you're using ".ejs" extensions you dont need to do anything. 58 | * 59 | * Some template engines do not follow this convention, the 60 | * [Consolidate.js](https://github.com/visionmedia/consolidate.js) 61 | * library was created to map all of node's popular template 62 | * engines to follow this convention, thus allowing them to 63 | * work seamlessly within Express. 64 | */ 65 | engine(ext: string, fn: Function): Application; 66 | 67 | /** 68 | * Assign `setting` to `val`, or return `setting`'s value. 69 | * 70 | * app.set('foo', 'bar'); 71 | * app.get('foo'); 72 | * // => "bar" 73 | * app.set('foo', ['bar', 'baz']); 74 | * app.get('foo'); 75 | * // => ["bar", "baz"] 76 | * 77 | * Mounted servers inherit their parent server's settings. 78 | */ 79 | set(setting: string, val: any): this; 80 | get(name: string): any; 81 | // need to duplicate this here from the Router because of the overload 82 | get(path: PathArgument, ...handlers: HandlerArgument[]): this; 83 | 84 | /** 85 | * Add callback triggers to route parameters, where name is the name of the parameter or an array of them, 86 | * and callback is the callback function. The parameters of the callback function are the request object, 87 | * the response object, the next middleware, the value of the parameter and the name of the parameter, 88 | * in that order. 89 | * If name is an array, the callback trigger is registered for each parameter declared in it, 90 | * in the order in which they are declared. Furthermore, for each declared parameter except the last one, 91 | * a call to next inside the callback will call the callback for the next declared parameter. 92 | * For the last parameter, a call to next will call the next middleware in place for the route currently 93 | * being processed, just like it would if name were just a string. 94 | * For example, when :user is present in a route path, you may map user loading logic to automatically 95 | * provide req.user to the route, or perform validations on the parameter input. 96 | */ 97 | param(name: string | string[], handler: ParamHandler): this; 98 | 99 | /** 100 | * @deprecated 101 | */ 102 | param(callback: (name: string, matcher: RegExp) => ParamHandler): this; 103 | 104 | /** 105 | * Return the app's absolute pathname 106 | * based on the parent(s) that have 107 | * mounted it. 108 | * 109 | * For example if the application was 110 | * mounted as "/admin", which itself 111 | * was mounted as "/blog" then the 112 | * return value would be "/blog/admin". 113 | */ 114 | path(): string; 115 | 116 | /** 117 | * Check if `setting` is enabled (truthy). 118 | * 119 | * app.enabled('foo') 120 | * // => false 121 | * 122 | * app.enable('foo') 123 | * app.enabled('foo') 124 | * // => true 125 | */ 126 | enabled(setting: string): boolean; 127 | 128 | /** 129 | * Check if `setting` is disabled. 130 | * 131 | * app.disabled('foo') 132 | * // => true 133 | * 134 | * app.enable('foo') 135 | * app.disabled('foo') 136 | * // => false 137 | */ 138 | disabled(setting: string): boolean; 139 | 140 | /** 141 | * Enable `setting`. 142 | */ 143 | enable(setting: string): this; 144 | 145 | /** 146 | * Disable `setting`. 147 | */ 148 | disable(setting: string): this; 149 | 150 | /** 151 | * Render the given view `name` name with `options` 152 | * and a callback accepting an error and the 153 | * rendered template string. 154 | * 155 | * Example: 156 | * 157 | * app.render('email', { name: 'Tobi' }, function(err, html){ 158 | * // ... 159 | * }) 160 | */ 161 | render(name: string, locals?: { [local: string]: any }, callback?: (err: Error, html: string) => void): void; 162 | render(name: string, callback: (err: Error, html: string) => void): void; 163 | 164 | /** 165 | * Listen for connections. 166 | * 167 | * A node `http.Server` is returned, with this 168 | * application (which is a `Function`) as its 169 | * callback. If you wish to create both an HTTP 170 | * and HTTPS server you may do so with the "http" 171 | * and "https" modules as shown here: 172 | * 173 | * var http = require('http') 174 | * , https = require('https') 175 | * , express = require('express') 176 | * , app = express(); 177 | * 178 | * http.createServer(app).listen(80); 179 | * https.createServer({ ... }, app).listen(443); 180 | */ 181 | listen(port: number, hostname?: string, backlog?: number, listeningListener?: Function): Server; 182 | listen(port: number, hostname?: string, listeningListener?: Function): Server; 183 | listen(port: number, backlog?: number, listeningListener?: Function): Server; 184 | listen(port: number, listeningListener?: Function): Server; 185 | listen(path: string, backlog?: number, listeningListener?: Function): Server; 186 | listen(path: string, listeningListener?: Function): Server; 187 | listen(handle: any, backlog?: number, listeningListener?: Function): Server; 188 | listen(handle: any, listeningListener?: Function): Server; 189 | listen(options: ListenOptions, listeningListener?: Function): Server; 190 | } 191 | } 192 | 193 | declare const app: app.Application; 194 | export = app; 195 | -------------------------------------------------------------------------------- /lib/router/route.d.ts: -------------------------------------------------------------------------------- 1 | 2 | import {HandlerArgument} from './index'; 3 | import Layer = require('./layer'); 4 | 5 | declare class Route { 6 | 7 | path: string; 8 | stack: Layer[]; 9 | 10 | /** 11 | * route handlers for various http methods 12 | */ 13 | methods: { 14 | [method: string]: boolean; 15 | }; 16 | 17 | constructor(path: string); 18 | 19 | all(...handlers: HandlerArgument[]): this; 20 | 21 | /** 22 | * The GET method means retrieve whatever information (in the form of an entity) 23 | * is identified by the Request-URI. If the Request-URI refers to a data-producing 24 | * process, it is the produced data which shall be returned as the entity in the 25 | * response and not the source text of the process, unless that text happens to be 26 | * the output of the process. 27 | */ 28 | get(...handlers: HandlerArgument[]): this; 29 | 30 | /** 31 | * The POST method is used to request that the origin server accept the entity 32 | * enclosed in the request as a new subordinate of the resource identified by the 33 | * Request-URI in the Request-Line. POST is designed to allow a uniform method to 34 | * cover the following functions: 35 | * - Annotation of existing resources; 36 | * - Posting a message to a bulletin board, newsgroup, mailing list, 37 | * or similar group of articles; 38 | * - Providing a block of data, such as the result of submitting a 39 | * form, to a data-handling process; 40 | * - Extending a database through an append operation. 41 | */ 42 | post(...handlers: HandlerArgument[]): this; 43 | 44 | /** 45 | * The PUT method requests that the enclosed entity be stored under the supplied 46 | * Request-URI. If the Request-URI refers to an already existing resource, the 47 | * enclosed entity SHOULD be considered as a modified version of the one residing 48 | * on the origin server. If the Request-URI does not point to an existing 49 | * resource, and that URI is capable of being defined as a new resource by the 50 | * requesting user agent, the origin server can create the resource with that URI 51 | */ 52 | put(...handlers: HandlerArgument[]): this; 53 | 54 | /** 55 | * The HEAD method is identical to GET except that the server MUST NOT send a 56 | * message body in the response (i.e., the response terminates at the end of the 57 | * header section). 58 | */ 59 | head(...handlers: HandlerArgument[]): this; 60 | 61 | /** 62 | * The DELETE method requests that the origin server remove the association 63 | * between the target resource and its current functionality. In effect, this 64 | * method is similar to the rm command in UNIX: it expresses a deletion operation 65 | * on the URI mapping of the origin server rather than an expectation that the 66 | * previously associated information be deleted. 67 | */ 68 | delete(...handlers: HandlerArgument[]): this; 69 | 70 | /** 71 | * The OPTIONS method requests information about the communication options 72 | * available for the target resource, at either the origin server or an 73 | * intervening intermediary. This method allows a client to determine the options 74 | * and/or requirements associated with a resource, or the capabilities of a 75 | * server, without implying a resource action. 76 | * 77 | */ 78 | options(...handlers: HandlerArgument[]): this; 79 | 80 | /** 81 | * The final recipient of the request SHOULD reflect the message received, 82 | * excluding some fields described below, back to the client as the message body 83 | * of a 200 (OK) response with a Content-Type of "message/http" (Section 8.3.1 of 84 | * RFC7230). 85 | */ 86 | trace(...handlers: HandlerArgument[]): this; 87 | 88 | /** 89 | * The WebDAV COPY Method creates a duplicate of the source resource identified by 90 | * the Request-Uniform Resource Identifier (URI), in the destination resource 91 | * identified by the Destination Header. The COPY Method can be used to duplicate 92 | * collection and property resources. 93 | */ 94 | copy(...handlers: HandlerArgument[]): this; 95 | 96 | /** 97 | * The WebDAV LOCK method is used to take out a lock of any access type on a 98 | * resource so that another principal will not modify the resource while it is 99 | * being edited. The LOCK method may also be used to initiate transactions, which 100 | * allow clients to define groups of operations that are performed atomically. 101 | */ 102 | lock(...handlers: HandlerArgument[]): this; 103 | 104 | /** 105 | * The WebDAV MKCOL method creates a new collection at the location specified by 106 | * the Request-Uniform Resource Identifier (URI). When invoked without a request 107 | * body, the collection will be created without member resources. When used with a 108 | * request body, you can create members and properties on the collections or 109 | * members. 110 | */ 111 | mkcol(...handlers: HandlerArgument[]): this; 112 | 113 | /** 114 | * The WebDAV MOVE Method is used to move a resource to the location specified by 115 | * a request Uniform Resource Identifier (URI). 116 | */ 117 | move(...handlers: HandlerArgument[]): this; 118 | 119 | /** 120 | * A purge is what happens when you pick out an object from the cache and discard 121 | * it along with its variants. Usually a purge is invoked through HTTP with the 122 | * method PURGE. An HTTP purge is similar to an HTTP GET request, except that the 123 | * method is PURGE. Actually you can call the method whatever you'd like, but most 124 | * people refer to this as purging. 125 | */ 126 | purge(...handlers: HandlerArgument[]): this; 127 | 128 | /** 129 | * The WebDAV PROPFIND Method retrieves properties for a resource identified by 130 | * the request Uniform Resource Identifier (URI). The PROPFIND Method can be used 131 | * on collection and property resources. 132 | */ 133 | propfind(...handlers: HandlerArgument[]): this; 134 | 135 | /** 136 | * The WebDAVPROPPATCH method sets properties for the resource at the specified 137 | * destination Uniform Resource Identifier (URI). All property names must be 138 | * scoped in the XML body using namespace URI references. 139 | */ 140 | proppatch(...handlers: HandlerArgument[]): this; 141 | 142 | /** 143 | * The WebDAVUNLOCK Method is used to remove the lock on the resource at the 144 | * request Uniform Resource Identifier (URI). The UNLOCK Method may also be used 145 | * to end a transaction that was initiated by the LOCK Method. 146 | */ 147 | unlock(...handlers: HandlerArgument[]): this; 148 | 149 | /** 150 | * A REPORT request is an extensible mechanism for obtaining information about a 151 | * resource. Unlike a resource property, which has a single value, the value of a 152 | * report can depend on additional information specified in the REPORT request 153 | * body and in the REPORT request headers. 154 | */ 155 | report(...handlers: HandlerArgument[]): this; 156 | 157 | /** 158 | * A MKACTIVITY request creates a new activity resource. A server MAY restrict 159 | * activity creation to particular collections, but a client can determine the 160 | * location of these collections from a DAV:activity-collection-set OPTIONS 161 | * request. 162 | */ 163 | mkactivity(...handlers: HandlerArgument[]): this; 164 | 165 | /** 166 | * A CHECKOUT request can be applied to a checked-in version-controlled resource 167 | * to allow modifications to the content and dead properties of that 168 | * version-controlled resource. 169 | */ 170 | checkout(...handlers: HandlerArgument[]): this; 171 | 172 | /** 173 | * The MERGE method performs the logical merge of a specified version (the "merge 174 | * source") into a specified version-controlled resource (the "merge target"). If 175 | * the merge source is neither an ancestor nor a descendant of the DAV:checked-in 176 | * or DAV:checked-out version of the merge target, the MERGE checks out the merge 177 | * target (if it is not already checked out) and adds the URL of the merge source 178 | * to the DAV:merge-set of the merge target. 179 | */ 180 | merge(...handlers: HandlerArgument[]): this; 181 | 182 | /** 183 | * a HTTP SEARCH method enhanced with the ssdp:discover functionality will be 184 | * referred to as a ssdp:discover request. 185 | */ 186 | 'm-search'(...handlers: HandlerArgument[]): this; 187 | 188 | /** 189 | * The WebDAV NOTIFY method is called by the server whenever an event that the 190 | * client has subscribed to fires. The NOTIFY method will send User Datagram 191 | * Protocol (UDP) packets to the client until the subscription has timed out. The 192 | * subscription to the resource will persist after the notification is sent by 193 | * the server. 194 | */ 195 | notify(...handlers: HandlerArgument[]): this; 196 | 197 | /** 198 | * The WebDAV SUBSCRIBE method is used to create a subscription to a resource. 199 | * This method is used to specify the details about the event to be monitored: 200 | * where to look for it; how long the event should be monitored; what the 201 | * notification mechanism is; and how long to delay before generating a 202 | * notification of the event. 203 | */ 204 | subscribe(...handlers: HandlerArgument[]): this; 205 | 206 | /** 207 | * The WebDAV UNSUBSCRIBE method is used to end a subscription to a resource. 208 | */ 209 | unsubscribe(...handlers: HandlerArgument[]): this; 210 | 211 | /** 212 | * The PATCH method requests that a set of changes described in the request entity 213 | * be applied to the resource identified by the Request- URI. The set of changes 214 | * is represented in a format called a "patch document" identified by a media 215 | * type. 216 | */ 217 | patch(...handlers: HandlerArgument[]): this; 218 | 219 | /** 220 | * The client invokes the SEARCH method to initiate a server-side search. The body 221 | * of the request defines the query. The server MUST emit an entity matching the 222 | * RFC2518 PROPFIND response. 223 | */ 224 | search(...handlers: HandlerArgument[]): this; 225 | 226 | /** 227 | * This specification reserves the method name CONNECT for use with a proxy that 228 | * can dynamically switch to being a tunnel (e.g. SSL tunneling). 229 | */ 230 | connect(...handlers: HandlerArgument[]): this; 231 | } 232 | 233 | export = Route; 234 | -------------------------------------------------------------------------------- /lib/request.d.ts: -------------------------------------------------------------------------------- 1 | 2 | import {IncomingMessage} from 'http'; 3 | import {Application} from './application'; 4 | import Route = require('./router/route'); 5 | 6 | declare namespace req { 7 | 8 | export interface RangeOptions { 9 | /** 10 | * Specifies if overlapping & adjacent ranges should be combined, defaults to `false`. 11 | * When `true`, ranges will be combined and returned as if they were specified that 12 | * way in the header. 13 | * 14 | * ```js 15 | * parseRange(100, 'bytes=50-55,0-10,5-10,56-60', { combine: true }) 16 | * // => [ 17 | * // { start: 0, end: 10 }, 18 | * // { start: 50, end: 60 } 19 | * // ] 20 | * ``` 21 | */ 22 | combined?: boolean; 23 | } 24 | 25 | export interface Range { 26 | start: number; 27 | end: number; 28 | } 29 | 30 | export interface Request extends IncomingMessage { 31 | 32 | /** 33 | * Return the protocol string "http" or "https" 34 | * when requested with TLS. When the "trust proxy" 35 | * setting is enabled the "X-Forwarded-Proto" header 36 | * field will be trusted. If you're running behind 37 | * a reverse proxy that supplies https for you this 38 | * may be enabled. 39 | */ 40 | protocol: string; 41 | 42 | /** 43 | * Short-hand for: 44 | * 45 | * req.protocol == 'https' 46 | */ 47 | secure: boolean; 48 | 49 | /** 50 | * Return the remote address, or when 51 | * "trust proxy" is `true` return 52 | * the upstream addr. 53 | */ 54 | ip: string; 55 | 56 | /** 57 | * When "trust proxy" is `true`, parse 58 | * the "X-Forwarded-For" ip address list. 59 | * 60 | * For example if the value were "client, proxy1, proxy2" 61 | * you would receive the array `["client", "proxy1", "proxy2"]` 62 | * where "proxy2" is the furthest down-stream. 63 | */ 64 | ips: string[]; 65 | 66 | /** 67 | * Return subdomains as an array. 68 | * 69 | * Subdomains are the dot-separated parts of the host before the main domain of 70 | * the app. By default, the domain of the app is assumed to be the last two 71 | * parts of the host. This can be changed by setting "subdomain offset". 72 | * 73 | * For example, if the domain is "tobi.ferrets.example.com": 74 | * If "subdomain offset" is not set, req.subdomains is `["ferrets", "tobi"]`. 75 | * If "subdomain offset" is 3, req.subdomains is `["tobi"]`. 76 | */ 77 | subdomains: string[]; 78 | 79 | /** 80 | * Short-hand for `url.parse(req.url).pathname`. 81 | */ 82 | path: string; 83 | 84 | /** 85 | * Parse the "Host" header field hostname. 86 | */ 87 | hostname: string; 88 | 89 | /** 90 | * @deprecated Use hostname instead. 91 | */ 92 | host: string; 93 | 94 | /** 95 | * Check if the request is fresh, aka 96 | * Last-Modified and/or the ETag 97 | * still match. 98 | */ 99 | fresh: boolean; 100 | 101 | /** 102 | * Check if the request is stale, aka 103 | * "Last-Modified" and / or the "ETag" for the 104 | * resource has changed. 105 | */ 106 | stale: boolean; 107 | 108 | /** 109 | * Check if the request was an _XMLHttpRequest_. 110 | */ 111 | xhr: boolean; 112 | 113 | /** 114 | * Contains a string corresponding to the HTTP method of the request: GET, POST, PUT, and so on. 115 | */ 116 | method: string; 117 | 118 | /** 119 | * req.url is not a native Express property, it is inherited from Node's http 120 | * module. In opposite to req.originalUrl, req.url is rewritten for internal 121 | * routing purposes. For example, the "mounting"" feature of app.use() will 122 | * rewrite req.url to strip the mount point. 123 | */ 124 | url: string; // needs to be redefined because IncomingMessage.url is optional 125 | 126 | /** 127 | * This property is an object containing a property for each query string parameter in the 128 | * route. If there is no query string, it is the empty object, {}. 129 | */ 130 | query: { 131 | [queryParam: string]: string; 132 | }; 133 | 134 | /** 135 | * Contains the currently-matched route 136 | */ 137 | route: Route; 138 | 139 | /** 140 | * This property is much like req.url; however, it retains the original request URL, allowing you to rewrite 141 | * req.url freely for internal routing purposes. For example, the “mounting” feature of app.use() will 142 | * rewrite req.url to strip the mount point. 143 | * 144 | * // GET /search?q=something 145 | * req.originalUrl 146 | * // => "/search?q=something" 147 | * 148 | * In a middleware function, req.originalUrl is a combination of req.baseUrl and req.path, as shown in the following example. 149 | * 150 | * app.use('/admin', function(req, res, next) { // GET 'http://www.example.com/admin/new' 151 | * console.log(req.originalUrl); // '/admin/new' 152 | * console.log(req.baseUrl); // '/admin' 153 | * console.log(req.path); // '/new' 154 | * next(); 155 | * }); 156 | * 157 | */ 158 | originalUrl: string; 159 | 160 | /** 161 | * The URL path on which a router instance was mounted. The req.baseUrl property is similar 162 | * to the mountpath property of the app object, except app.mountpath returns the matched 163 | * path pattern(s). 164 | */ 165 | baseUrl: string; 166 | 167 | /** 168 | * This property holds a reference to the instance of the Express application that is using 169 | * the middleware. If you follow the pattern in which you create a module that just exports 170 | * a middleware function and require() it in your main file, then the middleware can access 171 | * the Express instance via req.app 172 | */ 173 | app: Application; 174 | 175 | /** 176 | * This property is an object containing properties mapped to the named route "parameters". 177 | * For example, if you have the route `/user/:name`, then the "name" property is available as `req.params.name`. 178 | * This object defaults to `{}`. 179 | * When you use a regular expression for the route definition, capture groups are provided in the array using 180 | * `req.params[n]`, where n is the nth capture group. 181 | * This rule is applied to unnamed wild card matches with string routes such as `/file/*`. 182 | */ 183 | params: { 184 | [param: string]: string, 185 | [captureGroup: number]: string 186 | }; 187 | 188 | /** 189 | * Return request header. 190 | * 191 | * The `Referrer` header field is special-cased, 192 | * both `Referrer` and `Referer` are interchangeable. 193 | * 194 | * Examples: 195 | * 196 | * req.get('Content-Type'); 197 | * // => "text/plain" 198 | * 199 | * req.get('content-type'); 200 | * // => "text/plain" 201 | * 202 | * req.get('Something'); 203 | * // => undefined 204 | * 205 | * Aliased as `req.header()`. 206 | */ 207 | get(name: string): string; 208 | 209 | header(name: string): string; 210 | 211 | /** 212 | * Check if the given `type(s)` is acceptable, returning 213 | * the best match when true, otherwise `undefined`, in which 214 | * case you should respond with 406 "Not Acceptable". 215 | * 216 | * The `type` value may be a single mime type string 217 | * such as "application/json", the extension name 218 | * such as "json", a comma-delimted list such as "json, html, text/plain", 219 | * or an array `["json", "html", "text/plain"]`. When a list 220 | * or array is given the _best_ match, if any is returned. 221 | * 222 | * Examples: 223 | * 224 | * // Accept: text/html 225 | * req.accepts('html'); 226 | * // => "html" 227 | * 228 | * // Accept: text/*, application/json 229 | * req.accepts('html'); 230 | * // => "html" 231 | * req.accepts('text/html'); 232 | * // => "text/html" 233 | * req.accepts('json, text'); 234 | * // => "json" 235 | * req.accepts('application/json'); 236 | * // => "application/json" 237 | * 238 | * // Accept: text/*, application/json 239 | * req.accepts('image/png'); 240 | * req.accepts('png'); 241 | * // => undefined 242 | * 243 | * // Accept: text/*;q=.5, application/json 244 | * req.accepts(['html', 'json']); 245 | * req.accepts('html, json'); 246 | * // => "json" 247 | */ 248 | accepts(type: string | string[]): string | void; 249 | 250 | /** 251 | * Returns the first accepted charset of the specified character sets, 252 | * based on the request's Accept-Charset HTTP header field. 253 | * If none of the specified charsets is accepted, returns false. 254 | * 255 | * For more information, or if you have issues or concerns, see accepts. 256 | */ 257 | acceptsCharsets(charset?: string | string[]): string | boolean; 258 | 259 | /** 260 | * Returns the first accepted encoding of the specified encodings, 261 | * based on the request’s Accept-Encoding HTTP header field. 262 | * If none of the specified encodings is accepted, returns false. 263 | * 264 | * For more information, or if you have issues or concerns, see accepts. 265 | */ 266 | acceptsEncodings(encoding?: string | string[]): string | boolean; 267 | 268 | /** 269 | * Returns the first accepted language of the specified languages, 270 | * based on the request’s Accept-Language HTTP header field. 271 | * If none of the specified languages is accepted, returns false. 272 | * 273 | * For more information, or if you have issues or concerns, see accepts. 274 | */ 275 | acceptsLanguages(lang?: string | string[]): string | boolean; 276 | 277 | /** 278 | * Parse Range header field, 279 | * capping to the given `size`. 280 | * 281 | * Unspecified ranges such as "0-" require 282 | * knowledge of your resource length. In 283 | * the case of a byte range this is of course 284 | * the total number of bytes. If the Range 285 | * header field is not given `null` is returned, 286 | * `-1` when unsatisfiable, `-2` when syntactically invalid. 287 | * 288 | * NOTE: remember that ranges are inclusive, so 289 | * for example "Range: users=0-3" should respond 290 | * with 4 users when available, not 3. 291 | */ 292 | range(size: number, options?: RangeOptions): number | Range[]; 293 | 294 | /** 295 | * @deprecated Use either req.params, req.body or req.query, as applicable. 296 | * 297 | * Return the value of param `name` when present or `defaultValue`. 298 | * 299 | * - Checks route placeholders, ex: _/user/:id_ 300 | * - Checks body params, ex: id=12, {"id":12} 301 | * - Checks query string params, ex: ?id=12 302 | * 303 | * To utilize request bodies, `req.body` 304 | * should be an object. This can be done by using 305 | * the `connect.bodyParser()` middleware. 306 | */ 307 | param(name: string, defaultValue?: any): string; 308 | 309 | /** 310 | * Check if the incoming request contains the "Content-Type" 311 | * header field, and it contains the give mime `type`. 312 | * 313 | * Examples: 314 | * 315 | * // With Content-Type: text/html; charset=utf-8 316 | * req.is('html'); 317 | * req.is('text/html'); 318 | * req.is('text/*'); 319 | * // => true 320 | * 321 | * // When Content-Type is application/json 322 | * req.is('json'); 323 | * req.is('application/json'); 324 | * req.is('application/*'); 325 | * // => true 326 | * 327 | * req.is('html'); 328 | * // => false 329 | */ 330 | is(type: string | string[]): boolean; 331 | } 332 | } 333 | 334 | declare const req: req.Request; 335 | export = req; 336 | -------------------------------------------------------------------------------- /lib/response.d.ts: -------------------------------------------------------------------------------- 1 | 2 | import {ServerResponse} from 'http'; 3 | import {Application} from './application'; 4 | 5 | declare namespace res { 6 | 7 | export interface CookieOptions { 8 | maxAge?: number; 9 | signed?: boolean; 10 | expires?: Date; 11 | httpOnly?: boolean; 12 | path?: string; 13 | domain?: string; 14 | secure?: boolean; 15 | } 16 | 17 | export interface Response extends ServerResponse { 18 | 19 | app: Application; 20 | 21 | locals: any; 22 | 23 | charset: string; 24 | 25 | /** Property indicating if HTTP headers has been sent for the response. */ 26 | headersSent: boolean; 27 | 28 | /** 29 | * Set status `code`. 30 | */ 31 | status(code: number): this; 32 | 33 | /** 34 | * Set the response HTTP status code to `statusCode` and send its string representation as the response body. 35 | * 36 | * Examples: 37 | * 38 | * res.sendStatus(200); // equivalent to res.status(200).send('OK') 39 | * res.sendStatus(403); // equivalent to res.status(403).send('Forbidden') 40 | * res.sendStatus(404); // equivalent to res.status(404).send('Not Found') 41 | * res.sendStatus(500); // equivalent to res.status(500).send('Internal Server Error') 42 | */ 43 | sendStatus(code: number): this; 44 | 45 | /** 46 | * Set Link header field with the given `links`. 47 | * 48 | * Examples: 49 | * 50 | * res.links({ 51 | * next: 'http://api.example.com/users?page=2', 52 | * last: 'http://api.example.com/users?page=5' 53 | * }); 54 | */ 55 | links(links: any): this; 56 | 57 | /** 58 | * Send a response. 59 | * 60 | * Examples: 61 | * 62 | * res.send(new Buffer('wahoo')); 63 | * res.send({ some: 'json' }); 64 | * res.send('

some html

'); 65 | * res.send(404, 'Sorry, cant find that'); 66 | * res.send(404); 67 | */ 68 | send(body: string | Buffer | Object): this; 69 | 70 | /** 71 | * Send JSON response. 72 | * 73 | * Examples: 74 | * 75 | * res.json(null); 76 | * res.json({ user: 'tj' }); 77 | * res.json(500, 'oh noes!'); 78 | * res.json(404, 'I dont have that'); 79 | */ 80 | json(obj: any): this; 81 | 82 | /** 83 | * Send JSON response with JSONP callback support. 84 | * 85 | * Examples: 86 | * 87 | * res.jsonp(null); 88 | * res.jsonp({ user: 'tj' }); 89 | * res.jsonp(500, 'oh noes!'); 90 | * res.jsonp(404, 'I dont have that'); 91 | */ 92 | jsonp(obj: any): this; 93 | 94 | /** 95 | * Transfer the file at the given `path`. 96 | * 97 | * Automatically sets the _Content-Type_ response header field. 98 | * The callback `fn(err)` is invoked when the transfer is complete 99 | * or when an error occurs. Be sure to check `res.sentHeader` 100 | * if you wish to attempt responding, as the header and some data 101 | * may have already been transferred. 102 | * 103 | * Options: 104 | * 105 | * - `maxAge` defaulting to 0 (can be string converted by `ms`) 106 | * - `root` root directory for relative filenames 107 | * - `headers` object of headers to serve with file 108 | * - `dotfiles` serve dotfiles, defaulting to false; can be `"allow"` to send them 109 | * 110 | * Other options are passed along to `send`. 111 | * 112 | * Examples: 113 | * 114 | * The following example illustrates how `res.sendFile()` may 115 | * be used as an alternative for the `static()` middleware for 116 | * dynamic situations. The code backing `res.sendFile()` is actually 117 | * the same code, so HTTP cache support etc is identical. 118 | * 119 | * app.get('/user/:uid/photos/:file', function(req, res){ 120 | * var uid = req.params.uid 121 | * , file = req.params.file; 122 | * 123 | * req.user.mayViewFilesFrom(uid, function(yes){ 124 | * if (yes) { 125 | * res.sendFile('/uploads/' + uid + '/' + file); 126 | * } else { 127 | * res.send(403, 'Sorry! you cant see that.'); 128 | * } 129 | * }); 130 | * }); 131 | * 132 | * @api public 133 | */ 134 | sendFile(path: string): void; 135 | sendFile(path: string, options: any): void; 136 | sendFile(path: string, fn: (err?: Error) => any): void; 137 | sendFile(path: string, options: any, fn: (err?: Error) => any): void; 138 | 139 | /** 140 | * @deprecated Use sendFile instead. 141 | */ 142 | sendfile(path: string): void; 143 | sendfile(path: string, options: any): void; 144 | sendfile(path: string, fn: (err?: Error) => any): void; 145 | sendfile(path: string, options: any, fn: (err?: Error) => any): void; 146 | 147 | /** 148 | * Transfer the file at the given `path` as an attachment. 149 | * 150 | * Optionally providing an alternate attachment `filename`, 151 | * and optional callback `fn(err)`. The callback is invoked 152 | * when the data transfer is complete, or when an error has 153 | * ocurred. Be sure to check `res.headerSent` if you plan to respond. 154 | * 155 | * This method uses `res.sendFile()`. 156 | */ 157 | download(path: string): void; 158 | download(path: string, filename: string): void; 159 | download(path: string, fn: (err?: Error) => any): void; 160 | download(path: string, filename: string, fn: (err?: Error) => any): void; 161 | 162 | /** 163 | * Set _Content-Type_ response header with `type` through `mime.lookup()` 164 | * when it does not contain "/", or set the Content-Type to `type` otherwise. 165 | * 166 | * Examples: 167 | * 168 | * res.type('.html'); 169 | * res.type('html'); 170 | * res.type('json'); 171 | * res.type('application/json'); 172 | * res.type('png'); 173 | */ 174 | contentType(type: string): this; 175 | 176 | /** 177 | * Set _Content-Type_ response header with `type` through `mime.lookup()` 178 | * when it does not contain "/", or set the Content-Type to `type` otherwise. 179 | * 180 | * Examples: 181 | * 182 | * res.type('.html'); 183 | * res.type('html'); 184 | * res.type('json'); 185 | * res.type('application/json'); 186 | * res.type('png'); 187 | */ 188 | type(type: string): this; 189 | 190 | /** 191 | * Respond to the Acceptable formats using an `obj` 192 | * of mime-type callbacks. 193 | * 194 | * This method uses `req.accepted`, an array of 195 | * acceptable types ordered by their quality values. 196 | * When "Accept" is not present the _first_ callback 197 | * is invoked, otherwise the first match is used. When 198 | * no match is performed the server responds with 199 | * 406 "Not Acceptable". 200 | * 201 | * Content-Type is set for you, however if you choose 202 | * you may alter this within the callback using `res.type()` 203 | * or `res.set('Content-Type', ...)`. 204 | * 205 | * res.format({ 206 | * 'text/plain': function(){ 207 | * res.send('hey'); 208 | * }, 209 | * 210 | * 'text/html': function(){ 211 | * res.send('

hey

'); 212 | * }, 213 | * 214 | * 'appliation/json': function(){ 215 | * res.send({ message: 'hey' }); 216 | * } 217 | * }); 218 | * 219 | * In addition to canonicalized MIME types you may 220 | * also use extnames mapped to these types: 221 | * 222 | * res.format({ 223 | * text: function(){ 224 | * res.send('hey'); 225 | * }, 226 | * 227 | * html: function(){ 228 | * res.send('

hey

'); 229 | * }, 230 | * 231 | * json: function(){ 232 | * res.send({ message: 'hey' }); 233 | * } 234 | * }); 235 | * 236 | * By default Express passes an `Error` 237 | * with a `.status` of 406 to `next(err)` 238 | * if a match is not made. If you provide 239 | * a `.default` callback it will be invoked 240 | * instead. 241 | */ 242 | format(obj: any): this; 243 | 244 | /** 245 | * Set _Content-Disposition_ header to _attachment_ with optional `filename`. 246 | */ 247 | attachment(filename?: string): this; 248 | 249 | /** 250 | * Set header `field` to `val`, or pass 251 | * an object of header fields. 252 | * 253 | * Examples: 254 | * 255 | * res.set('Foo', ['bar', 'baz']); 256 | * res.set('Accept', 'application/json'); 257 | * res.set({ Accept: 'text/plain', 'X-API-Key': 'tobi' }); 258 | * 259 | * Aliased as `res.header()`. 260 | */ 261 | set(fields: { [field: string]: string }): this; 262 | set(field: string, value: string): this; 263 | header(fields: { [field: string]: string }): this; 264 | header(field: string, value: string): this; 265 | 266 | /** 267 | * Get value for header `field`. 268 | */ 269 | get(field: string): string; 270 | 271 | /** 272 | * Clear cookie `name`. 273 | */ 274 | clearCookie(name: string, options?: CookieOptions): this; 275 | 276 | /** 277 | * Set cookie `name` to `val`, with the given `options`. 278 | * 279 | * Options: 280 | * 281 | * - `maxAge` max-age in milliseconds, converted to `expires` 282 | * - `signed` sign the cookie 283 | * - `path` defaults to "/" 284 | * 285 | * Examples: 286 | * 287 | * // "Remember Me" for 15 minutes 288 | * res.cookie('rememberme', '1', { expires: new Date(Date.now() + 900000), httpOnly: true }); 289 | * 290 | * // save as above 291 | * res.cookie('rememberme', '1', { maxAge: 900000, httpOnly: true }) 292 | */ 293 | cookie(name: string, val: string | Object, options?: CookieOptions): this; 294 | 295 | /** 296 | * Set the location header to `url`. 297 | * 298 | * The given `url` can also be the name of a mapped url, for 299 | * example by default express supports "back" which redirects 300 | * to the _Referrer_ or _Referer_ headers or "/". 301 | * 302 | * Examples: 303 | * 304 | * res.location('/foo/bar').; 305 | * res.location('http://example.com'); 306 | * res.location('../login'); // /blog/post/1 -> /blog/login 307 | * 308 | * Mounting: 309 | * 310 | * When an application is mounted and `res.location()` 311 | * is given a path that does _not_ lead with "/" it becomes 312 | * relative to the mount-point. For example if the application 313 | * is mounted at "/blog", the following would become "/blog/login". 314 | * 315 | * res.location('login'); 316 | * 317 | * While the leading slash would result in a location of "/login": 318 | * 319 | * res.location('/login'); 320 | */ 321 | location(url: string): this; 322 | 323 | /** 324 | * Redirect to the given `url` with optional response `status` 325 | * defaulting to 302. 326 | * 327 | * The resulting `url` is determined by `res.location()`, so 328 | * it will play nicely with mounted apps, relative paths, 329 | * `"back"` etc. 330 | * 331 | * Examples: 332 | * 333 | * res.redirect('/foo/bar'); 334 | * res.redirect('http://example.com'); 335 | * res.redirect(301, 'http://example.com'); 336 | * res.redirect('http://example.com', 301); 337 | * res.redirect('../login'); // /blog/post/1 -> /blog/login 338 | */ 339 | redirect(url: string): void; 340 | redirect(status: number, url: string): void; 341 | redirect(url: string, status: number): void; 342 | 343 | /** 344 | * Render `view` with the given `options` and optional callback `fn`. 345 | * When a callback function is given a response will _not_ be made 346 | * automatically, otherwise a response of _200_ and _text/html_ is given. 347 | * 348 | * Options: 349 | * 350 | * - `cache` boolean hinting to the engine it should cache 351 | * - `filename` filename of the view being rendered 352 | */ 353 | render(view: string, locals?: { [local: string]: any }, callback?: (err: Error | void, html?: string) => void): void; 354 | render(view: string, callback?: (err: Error, html: string) => void): void; 355 | 356 | /** 357 | * Adds the field to the Vary response header, if it is not there already. 358 | * Examples: 359 | * 360 | * res.vary('User-Agent').render('docs'); 361 | * 362 | */ 363 | vary(field: string): this; 364 | } 365 | } 366 | 367 | declare const res: res.Response; 368 | export = res; 369 | -------------------------------------------------------------------------------- /lib/router/index.d.ts: -------------------------------------------------------------------------------- 1 | 2 | import {Request} from '../request'; 3 | import {Response} from '../response'; 4 | import Route = require('./route'); 5 | 6 | declare namespace createRouter { 7 | 8 | export type PathArgument = string | RegExp | (string | RegExp)[]; 9 | 10 | export interface NextFunction { 11 | (err?: any): void; 12 | } 13 | 14 | export interface RequestHandler { 15 | (req: Request, res: Response, next: NextFunction): any; 16 | } 17 | 18 | export interface ErrorHandler { 19 | (err: any, req: Request, res: Response, next: NextFunction): any; 20 | } 21 | 22 | export type Handler = RequestHandler | ErrorHandler; 23 | 24 | /** Can be passed to all methods like `use`, `get`, `all` etc */ 25 | export type HandlerArgument = Handler | Handler[]; 26 | 27 | export interface ParamHandler { 28 | (req: Request, res: Response, next: NextFunction, value: any, name: string): any; 29 | } 30 | 31 | export interface RouterOptions { 32 | caseSensitive?: boolean; 33 | mergeParams?: boolean; 34 | strict?: boolean; 35 | } 36 | 37 | export interface Router extends RequestHandler { 38 | 39 | /** 40 | * Map the given param placeholder `name`(s) to the given callback(s). 41 | * 42 | * Parameter mapping is used to provide pre-conditions to routes 43 | * which use normalized placeholders. For example a _:user_id_ parameter 44 | * could automatically load a user's information from the database without 45 | * any additional code, 46 | * 47 | * The callback uses the samesignature as middleware, the only differencing 48 | * being that the value of the placeholder is passed, in this case the _id_ 49 | * of the user. Once the `next()` function is invoked, just like middleware 50 | * it will continue on to execute the route, or subsequent parameter functions. 51 | * 52 | * app.param('user_id', function(req, res, next, id){ 53 | * User.find(id, function(err, user){ 54 | * if (err) { 55 | * next(err); 56 | * } else if (user) { 57 | * req.user = user; 58 | * next(); 59 | * } else { 60 | * next(new Error('failed to load user')); 61 | * } 62 | * }); 63 | * }); 64 | */ 65 | param(name: string, handler: ParamHandler): this; 66 | 67 | /** 68 | * @deprecated 69 | */ 70 | param(callback: (name: string, matcher: RegExp) => ParamHandler): this; 71 | 72 | all(path: PathArgument, ...handlers: HandlerArgument[]): this; 73 | 74 | /** 75 | * The GET method means retrieve whatever information (in the form of an entity) 76 | * is identified by the Request-URI. If the Request-URI refers to a data-producing 77 | * process, it is the produced data which shall be returned as the entity in the 78 | * response and not the source text of the process, unless that text happens to be 79 | * the output of the process. 80 | */ 81 | get(path: PathArgument, ...handlers: HandlerArgument[]): this; 82 | 83 | /** 84 | * The POST method is used to request that the origin server accept the entity 85 | * enclosed in the request as a new subordinate of the resource identified by the 86 | * Request-URI in the Request-Line. POST is designed to allow a uniform method to 87 | * cover the following functions: 88 | * - Annotation of existing resources; 89 | * - Posting a message to a bulletin board, newsgroup, mailing list, 90 | * or similar group of articles; 91 | * - Providing a block of data, such as the result of submitting a 92 | * form, to a data-handling process; 93 | * - Extending a database through an append operation. 94 | */ 95 | post(path: PathArgument, ...handlers: HandlerArgument[]): this; 96 | 97 | /** 98 | * The PUT method requests that the enclosed entity be stored under the supplied 99 | * Request-URI. If the Request-URI refers to an already existing resource, the 100 | * enclosed entity SHOULD be considered as a modified version of the one residing 101 | * on the origin server. If the Request-URI does not point to an existing 102 | * resource, and that URI is capable of being defined as a new resource by the 103 | * requesting user agent, the origin server can create the resource with that URI 104 | */ 105 | put(path: PathArgument, ...handlers: HandlerArgument[]): this; 106 | 107 | /** 108 | * The HEAD method is identical to GET except that the server MUST NOT send a 109 | * message body in the response (i.e., the response terminates at the end of the 110 | * header section). 111 | */ 112 | head(path: PathArgument, ...handlers: HandlerArgument[]): this; 113 | 114 | /** 115 | * The DELETE method requests that the origin server remove the association 116 | * between the target resource and its current functionality. In effect, this 117 | * method is similar to the rm command in UNIX: it expresses a deletion operation 118 | * on the URI mapping of the origin server rather than an expectation that the 119 | * previously associated information be deleted. 120 | */ 121 | delete(path: PathArgument, ...handlers: HandlerArgument[]): this; 122 | 123 | /** 124 | * The OPTIONS method requests information about the communication options 125 | * available for the target resource, at either the origin server or an 126 | * intervening intermediary. This method allows a client to determine the options 127 | * and/or requirements associated with a resource, or the capabilities of a 128 | * server, without implying a resource action. 129 | * 130 | */ 131 | options(path: PathArgument, ...handlers: HandlerArgument[]): this; 132 | 133 | /** 134 | * The final recipient of the request SHOULD reflect the message received, 135 | * excluding some fields described below, back to the client as the message body 136 | * of a 200 (OK) response with a Content-Type of "message/http" (Section 8.3.1 of 137 | * RFC7230). 138 | */ 139 | trace(path: PathArgument, ...handlers: HandlerArgument[]): this; 140 | 141 | /** 142 | * The WebDAV COPY Method creates a duplicate of the source resource identified by 143 | * the Request-Uniform Resource Identifier (URI), in the destination resource 144 | * identified by the Destination Header. The COPY Method can be used to duplicate 145 | * collection and property resources. 146 | */ 147 | copy(path: PathArgument, ...handlers: HandlerArgument[]): this; 148 | 149 | /** 150 | * The WebDAV LOCK method is used to take out a lock of any access type on a 151 | * resource so that another principal will not modify the resource while it is 152 | * being edited. The LOCK method may also be used to initiate transactions, which 153 | * allow clients to define groups of operations that are performed atomically. 154 | */ 155 | lock(path: PathArgument, ...handlers: HandlerArgument[]): this; 156 | 157 | /** 158 | * The WebDAV MKCOL method creates a new collection at the location specified by 159 | * the Request-Uniform Resource Identifier (URI). When invoked without a request 160 | * body, the collection will be created without member resources. When used with a 161 | * request body, you can create members and properties on the collections or 162 | * members. 163 | */ 164 | mkcol(path: PathArgument, ...handlers: HandlerArgument[]): this; 165 | 166 | /** 167 | * The WebDAV MOVE Method is used to move a resource to the location specified by 168 | * a request Uniform Resource Identifier (URI). 169 | */ 170 | move(path: PathArgument, ...handlers: HandlerArgument[]): this; 171 | 172 | /** 173 | * A purge is what happens when you pick out an object from the cache and discard 174 | * it along with its variants. Usually a purge is invoked through HTTP with the 175 | * method PURGE. An HTTP purge is similar to an HTTP GET request, except that the 176 | * method is PURGE. Actually you can call the method whatever you'd like, but most 177 | * people refer to this as purging. 178 | */ 179 | purge(path: PathArgument, ...handlers: HandlerArgument[]): this; 180 | 181 | /** 182 | * The WebDAV PROPFIND Method retrieves properties for a resource identified by 183 | * the request Uniform Resource Identifier (URI). The PROPFIND Method can be used 184 | * on collection and property resources. 185 | */ 186 | propfind(path: PathArgument, ...handlers: HandlerArgument[]): this; 187 | 188 | /** 189 | * The WebDAVPROPPATCH method sets properties for the resource at the specified 190 | * destination Uniform Resource Identifier (URI). All property names must be 191 | * scoped in the XML body using namespace URI references. 192 | */ 193 | proppatch(path: PathArgument, ...handlers: HandlerArgument[]): this; 194 | 195 | /** 196 | * The WebDAVUNLOCK Method is used to remove the lock on the resource at the 197 | * request Uniform Resource Identifier (URI). The UNLOCK Method may also be used 198 | * to end a transaction that was initiated by the LOCK Method. 199 | */ 200 | unlock(path: PathArgument, ...handlers: HandlerArgument[]): this; 201 | 202 | /** 203 | * A REPORT request is an extensible mechanism for obtaining information about a 204 | * resource. Unlike a resource property, which has a single value, the value of a 205 | * report can depend on additional information specified in the REPORT request 206 | * body and in the REPORT request headers. 207 | */ 208 | report(path: PathArgument, ...handlers: HandlerArgument[]): this; 209 | 210 | /** 211 | * A MKACTIVITY request creates a new activity resource. A server MAY restrict 212 | * activity creation to particular collections, but a client can determine the 213 | * location of these collections from a DAV:activity-collection-set OPTIONS 214 | * request. 215 | */ 216 | mkactivity(path: PathArgument, ...handlers: HandlerArgument[]): this; 217 | 218 | /** 219 | * A CHECKOUT request can be applied to a checked-in version-controlled resource 220 | * to allow modifications to the content and dead properties of that 221 | * version-controlled resource. 222 | */ 223 | checkout(path: PathArgument, ...handlers: HandlerArgument[]): this; 224 | 225 | /** 226 | * The MERGE method performs the logical merge of a specified version (the "merge 227 | * source") into a specified version-controlled resource (the "merge target"). If 228 | * the merge source is neither an ancestor nor a descendant of the DAV:checked-in 229 | * or DAV:checked-out version of the merge target, the MERGE checks out the merge 230 | * target (if it is not already checked out) and adds the URL of the merge source 231 | * to the DAV:merge-set of the merge target. 232 | */ 233 | merge(path: PathArgument, ...handlers: HandlerArgument[]): this; 234 | 235 | /** 236 | * a HTTP SEARCH method enhanced with the ssdp:discover functionality will be 237 | * referred to as a ssdp:discover request. 238 | */ 239 | 'm-search'(path: PathArgument, ...handlers: HandlerArgument[]): this; 240 | 241 | /** 242 | * The WebDAV NOTIFY method is called by the server whenever an event that the 243 | * client has subscribed to fires. The NOTIFY method will send User Datagram 244 | * Protocol (UDP) packets to the client until the subscription has timed out. The 245 | * subscription to the resource will persist after the notification is sent by 246 | * the server. 247 | */ 248 | notify(path: PathArgument, ...handlers: HandlerArgument[]): this; 249 | 250 | /** 251 | * The WebDAV SUBSCRIBE method is used to create a subscription to a resource. 252 | * This method is used to specify the details about the event to be monitored: 253 | * where to look for it; how long the event should be monitored; what the 254 | * notification mechanism is; and how long to delay before generating a 255 | * notification of the event. 256 | */ 257 | subscribe(path: PathArgument, ...handlers: HandlerArgument[]): this; 258 | 259 | /** 260 | * The WebDAV UNSUBSCRIBE method is used to end a subscription to a resource. 261 | */ 262 | unsubscribe(path: PathArgument, ...handlers: HandlerArgument[]): this; 263 | 264 | /** 265 | * The PATCH method requests that a set of changes described in the request entity 266 | * be applied to the resource identified by the Request- URI. The set of changes 267 | * is represented in a format called a "patch document" identified by a media 268 | * type. 269 | */ 270 | patch(path: PathArgument, ...handlers: HandlerArgument[]): this; 271 | 272 | /** 273 | * The client invokes the SEARCH method to initiate a server-side search. The body 274 | * of the request defines the query. The server MUST emit an entity matching the 275 | * RFC2518 PROPFIND response. 276 | */ 277 | search(path: PathArgument, ...handlers: HandlerArgument[]): this; 278 | 279 | /** 280 | * This specification reserves the method name CONNECT for use with a proxy that 281 | * can dynamically switch to being a tunnel (e.g. SSL tunneling). 282 | */ 283 | connect(path: PathArgument, ...handlers: HandlerArgument[]): this; 284 | 285 | use(...handlers: HandlerArgument[]): this; 286 | use(mountPoint: string | RegExp | (string | RegExp)[], ...handlers: HandlerArgument[]): this; 287 | 288 | route(prefix: PathArgument): Route; 289 | } 290 | } 291 | 292 | declare function createRouter(options?: createRouter.RouterOptions): createRouter.Router; 293 | export = createRouter; 294 | --------------------------------------------------------------------------------