connect: Add NextFunction for next, fix err parameter (#24883)

This commit is contained in:
Evan Hahn 2018-04-16 17:45:19 -07:00 committed by Ryan Cavanaugh
parent ed43fdd5b7
commit 23c8bbf227
2 changed files with 22 additions and 4 deletions

View File

@ -4,13 +4,23 @@ import connect = require("connect");
const app = connect();
// log all requests
app.use((req: http.IncomingMessage, res: http.ServerResponse, next: Function) => {
app.use((req: http.IncomingMessage, res: http.ServerResponse, next: connect.NextFunction) => {
console.log(req, res);
next();
});
// "Throw" an Error
app.use((req: http.IncomingMessage, res: http.ServerResponse, next: connect.NextFunction) => {
next(new Error("Something went wrong!"));
});
// "Throw" a number
app.use((req: http.IncomingMessage, res: http.ServerResponse, next: connect.NextFunction) => {
next(404);
});
// Stop on errors
app.use((err: Error, req: http.IncomingMessage, res: http.ServerResponse, next: Function) => {
app.use((err: any, req: http.IncomingMessage, res: http.ServerResponse, next: connect.NextFunction) => {
if (err) {
return res.end(`Error: ${err}`);
}
@ -18,6 +28,11 @@ app.use((err: Error, req: http.IncomingMessage, res: http.ServerResponse, next:
next();
});
// Use legacy `Function` for `next` parameter.
app.use((req: http.IncomingMessage, res: http.ServerResponse, next: Function) => {
next();
});
// respond to all requests
app.use((req: http.IncomingMessage, res: http.ServerResponse) => {
res.end("Hello from Connect!\n");

View File

@ -1,6 +1,7 @@
// Type definitions for connect v3.4.0
// Project: https://github.com/senchalabs/connect
// Definitions by: Maxime LUCE <https://github.com/SomaticIT>
// Evan Hahn <https://github.com/EvanHahn>
// Definitions: https://github.com/DefinitelyTyped/DefinitelyTyped
/// <reference types="node" />
@ -17,9 +18,11 @@ declare function createServer(): createServer.Server;
declare namespace createServer {
export type ServerHandle = HandleFunction | http.Server;
type NextFunction = (err?: any) => void;
export type SimpleHandleFunction = (req: http.IncomingMessage, res: http.ServerResponse) => void;
export type NextHandleFunction = (req: http.IncomingMessage, res: http.ServerResponse, next: Function) => void;
export type ErrorHandleFunction = (err: Error, req: http.IncomingMessage, res: http.ServerResponse, next: Function) => void;
export type NextHandleFunction = (req: http.IncomingMessage, res: http.ServerResponse, next: NextFunction) => void;
export type ErrorHandleFunction = (err: any, req: http.IncomingMessage, res: http.ServerResponse, next: NextFunction) => void;
export type HandleFunction = SimpleHandleFunction | NextHandleFunction | ErrorHandleFunction;
export interface ServerStackItem {