Skip to content

Add TypeScript generic support for Request and Response types #292

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft
wants to merge 3 commits into
base: main
Choose a base branch
from
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 28 additions & 22 deletions index.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,21 +44,24 @@ export declare interface App {
[namespace: string]: Package;
}

export declare type Middleware = (
req: Request,
res: Response,
export declare type Middleware<TReq = Request, TRes = Response> = (
req: TReq,
res: TRes,
next: NextFunction
) => void;
export declare type ErrorHandlingMiddleware = (

export declare type ErrorHandlingMiddleware<TReq = Request, TRes = Response> = (
error: Error,
req: Request,
res: Response,
req: TReq,
res: TRes,
next: NextFunction
) => void;

export declare type ErrorCallback = (error?: Error) => void;
export declare type HandlerFunction = (
req: Request,
res: Response,

export declare type HandlerFunction<TReq = Request, TRes = Response> = (
req: TReq,
res: TRes,
next?: NextFunction
) => void | any | Promise<any>;

Expand All @@ -77,7 +80,10 @@ export declare type LoggerFunctionAdditionalInfo =
export declare type NextFunction = () => void;
export declare type TimestampFunction = () => string;
export declare type SerializerFunction = (body: object) => string;
export declare type FinallyFunction = (req: Request, res: Response) => void;
export declare type FinallyFunction<TReq = Request, TRes = Response> = (
req: TReq,
res: TRes
) => void;
export declare type METHODS =
| 'GET'
| 'POST'
Expand Down Expand Up @@ -136,18 +142,18 @@ export declare interface Options {
s3Config?: S3ClientConfig;
}

export declare class Request {
export declare class Request<
TParams = { [key: string]: string | undefined },
TQuery = { [key: string]: string | undefined },
TBody = any
> {
app: API;
version: string;
id: string;
params: {
[key: string]: string | undefined;
};
params: TParams;
method: string;
path: string;
query: {
[key: string]: string | undefined;
};
query: TQuery;
multiValueQuery: {
[key: string]: string[] | undefined;
};
Expand All @@ -160,7 +166,7 @@ export declare class Request {
rawHeaders?: {
[key: string]: string | undefined;
};
body: any;
body: TBody;
rawBody: string;
route: '';
requestContext: APIGatewayEventRequestContext;
Expand Down Expand Up @@ -196,7 +202,7 @@ export declare class Request {
[key: string]: any;
}

export declare class Response {
export declare class Response<TBody = any> {
status(code: number): this;

sendStatus(code: number): void;
Expand All @@ -219,11 +225,11 @@ export declare class Response {
callback?: ErrorCallback
): Promise<string>;

send(body: any): void;
send(body: TBody): void;

json(body: any): void;
json(body: TBody): void;

jsonp(body: any): void;
jsonp(body: TBody): void;

html(body: any): void;

Expand Down
148 changes: 148 additions & 0 deletions index.test-d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,6 +47,90 @@ expectType<{ [key: string]: string | undefined }>(req.headers);
expectType<any>(req.body);
expectType<{ [key: string]: string }>(req.cookies);

// Test generic Request types
interface CustomParams {
id: string;
userId: string;
}

interface CustomQuery {
filter?: string;
limit?: string;
}

interface CustomBody {
name: string;
email: string;
}

interface CustomResponseBody {
success: boolean;
message: string;
data?: any;
}

// Test that custom types can be used with Request and Response generics
const customReq = {} as Request<CustomParams, CustomQuery, CustomBody>;
expectType<CustomParams>(customReq.params);
expectType<CustomQuery>(customReq.query);
expectType<CustomBody>(customReq.body);
expectType<string>(customReq.params.id);
expectType<string>(customReq.params.userId);
expectType<string | undefined>(customReq.query.filter);
expectType<string | undefined>(customReq.query.limit);
expectType<string>(customReq.body.name);
expectType<string>(customReq.body.email);

const customRes = {} as Response<CustomResponseBody>;
expectType<void>(customRes.json({ success: true, message: 'test' }));
expectType<void>(customRes.send({ success: true, message: 'test', data: {} }));

// Test that sending wrong type should cause type error
expectError(customRes.json({ wrong: 'type' }));
expectError(customRes.send({ invalid: 'data' }));

// Test generic middleware types
type CustomRequest = Request<CustomParams>;
type CustomResponse = Response<CustomResponseBody>;

const typedMiddleware: Middleware<CustomRequest, CustomResponse> = (
req,
res,
next
) => {
expectType<string>(req.params.id);
expectType<string>(req.params.userId);
expectType<void>(res.json({ success: true, message: 'middleware test' }));
next();
};
expectType<Middleware<CustomRequest, CustomResponse>>(typedMiddleware);

// Test generic handler function types
type FullCustomRequest = Request<CustomParams, CustomQuery, CustomBody>;

const typedHandler: HandlerFunction<FullCustomRequest, CustomResponse> = (
req,
res
) => {
expectType<string>(req.params.id);
expectType<string | undefined>(req.query.filter);
expectType<string>(req.body.name);
res.json({ success: true, message: `Hello ${req.body.name}` });
};
expectType<HandlerFunction<FullCustomRequest, CustomResponse>>(typedHandler);

// Test generic error handling middleware
const typedErrorMiddleware: ErrorHandlingMiddleware<
CustomRequest,
CustomResponse
> = (error, req, res, next) => {
expectType<string>(req.params.id);
res.json({ success: false, message: error.message });
};
expectType<ErrorHandlingMiddleware<CustomRequest, CustomResponse>>(
typedErrorMiddleware
);

const apiGwV1Event: APIGatewayProxyEvent = {
body: '{"test":"body"}',
headers: { 'content-type': 'application/json' },
Expand Down Expand Up @@ -265,3 +349,67 @@ expectType<ApiError>(apiError);
expectType<string>(apiError.message);
expectType<number | undefined>(apiError.code);
expectType<any>(apiError.detail);

// Test specific example from the GitHub issue
interface MyDefinedRequest extends Request {
params: {
thingId: string;
anotherThingId: string;
};
context: Context & { metrics: any }; // MetricsLogger was not imported
}

interface MyDefinedResponseBody {
hello: string;
foo: string;
}

// Test the exact use case from the issue
const issueExampleHandler = (
request: MyDefinedRequest,
response: Response<MyDefinedResponseBody>
) => {
// request.params should be strongly typed
expectType<string>(request.params.thingId);
expectType<string>(request.params.anotherThingId);

// response.json should expect MyDefinedResponseBody
response.json({ hello: 'world', foo: 'bar' });

// This should cause a TypeScript error
expectError(response.json({ wrong: 'type' }));
};

expectType<
(request: MyDefinedRequest, response: Response<MyDefinedResponseBody>) => void
>(issueExampleHandler);

// Test backwards compatibility - default types should work the same as before
const defaultReq = {} as Request;
expectType<{ [key: string]: string | undefined }>(defaultReq.params);
expectType<{ [key: string]: string | undefined }>(defaultReq.query);
expectType<any>(defaultReq.body);

const defaultRes = {} as Response;
expectType<void>(defaultRes.json({ any: 'value' }));
expectType<void>(defaultRes.send('any string'));
expectType<void>(defaultRes.send({ any: 'object' }));

const defaultMiddleware: Middleware = (req, res, next) => {
expectType<{ [key: string]: string | undefined }>(req.params);
expectType<{ [key: string]: string | undefined }>(req.query);
expectType<any>(req.body);
expectType<void>(res.json({ any: 'value' }));
expectType<void>(res.send('any'));
next();
};
expectType<Middleware>(defaultMiddleware);

const defaultHandler: HandlerFunction = (req, res) => {
expectType<{ [key: string]: string | undefined }>(req.params);
expectType<{ [key: string]: string | undefined }>(req.query);
expectType<any>(req.body);
expectType<void>(res.json({ any: 'value' }));
expectType<void>(res.send('any'));
};
expectType<HandlerFunction>(defaultHandler);