1 | import {
|
2 | Callback,
|
3 | Context,
|
4 | Handler
|
5 | } from 'aws-lambda'
|
6 |
|
7 | declare type EventType<T, C> =
|
8 | T extends (event: infer EventArgType, context: C, callback: Callback<any>) => void ? EventArgType :
|
9 | T extends (event: infer EventArgType, context: C) => Promise<any> ? EventArgType :
|
10 | never;
|
11 |
|
12 | declare type HandlerReturnType<T, C> =
|
13 | T extends (event: any, context: C) => Promise<infer RetType> ? RetType :
|
14 | T extends (event: any, context: C, callback: Callback<infer RetType>) => void ? RetType :
|
15 | never;
|
16 |
|
17 | declare type AsyncHandler<C extends Context> =
|
18 | ((event: any, context: C, callback: Callback<any>) => void) |
|
19 | ((event: any, context: C) => Promise<any>);
|
20 |
|
21 | declare const middy: <H extends AsyncHandler<C>, C extends Context = Context>(handler: H) => middy.Middy<
|
22 | EventType<H, C>,
|
23 | HandlerReturnType<H, C>,
|
24 | C
|
25 | >
|
26 |
|
27 | declare namespace middy {
|
28 | interface Middy<T, R, C extends Context = Context> extends Handler<T, R> {
|
29 | use: <M extends MiddlewareObject<T, R, C>>(middlewares: M | M[]) => Middy<T, R, C>;
|
30 | before: (callbackFn: MiddlewareFunction<T, R, C>) => Middy<T, R, C>;
|
31 | after: (callbackFn: MiddlewareFunction<T, R, C>) => Middy<T, R, C>;
|
32 | onError: (callbackFn: MiddlewareFunction<T, R, C>) => Middy<T, R, C>;
|
33 | }
|
34 |
|
35 | type Middleware<C extends any, T = any, R = any> = (config?: C) => MiddlewareObject<T, R>;
|
36 |
|
37 | interface MiddlewareObject<T, R, C extends Context = Context> {
|
38 | before?: MiddlewareFunction<T, R, C>;
|
39 | after?: MiddlewareFunction<T, R, C>;
|
40 | onError?: MiddlewareFunction<T, R, C>;
|
41 | }
|
42 |
|
43 | type MiddlewareFunction<T, R, C extends Context = Context> = (handler: HandlerLambda<T, R, C>, next: NextFunction) => void | Promise<any>;
|
44 |
|
45 | type NextFunction = (error?: any) => void;
|
46 |
|
47 | interface HandlerLambda<T = any, V = any, C extends Context = Context> {
|
48 | event: T;
|
49 | context: C;
|
50 | response: V;
|
51 | error: Error;
|
52 | callback: Callback<V>;
|
53 | }
|
54 | }
|
55 |
|
56 | export default middy
|
57 | export as namespace middy;
|