UNPKG

2.81 kBTypeScriptView Raw
1import {
2 Context as LambdaContext,
3 Handler as LambdaHandler
4} from 'aws-lambda'
5
6declare type PluginHook = () => void
7declare type PluginHookWithMiddlewareName = (middlewareName: string) => void
8declare type PluginHookPromise = () => Promise<any>
9
10interface PluginObject {
11 beforePrefetch?: PluginHook
12 requestStart?: PluginHook
13 beforeMiddleware?: PluginHookWithMiddlewareName
14 afterMiddleware?: PluginHookWithMiddlewareName
15 beforeHandler?: PluginHook
16 afterHandler?: PluginHook
17 requestEnd?: PluginHookPromise
18}
19
20interface Request<TEvent = any, TResult = any, TErr = Error> {
21 event: TEvent
22 context: LambdaContext
23 response: TResult | null
24 error: TErr | null
25 internal: {
26 [key: string]: any
27 }
28}
29
30declare type MiddlewareFn<TEvent = any, TResult = any, TErr = Error> = (request: Request<TEvent, TResult, TErr>) => any
31
32export interface MiddlewareObj<TEvent = any, TResult = any, TErr = Error> {
33 before?: MiddlewareFn<TEvent, TResult, TErr>
34 after?: MiddlewareFn<TEvent, TResult, TErr>
35 onError?: MiddlewareFn<TEvent, TResult, TErr>
36}
37
38export interface MiddyfiedHandler<TEvent = any, TResult = any, TErr = Error> {
39 use: UseFn<TEvent, TResult, TErr>
40 applyMiddleware: AttachMiddlewareObj<TEvent, TResult, TErr>
41 before: AttachMiddlewareFn<TEvent, TResult, TErr>
42 after: AttachMiddlewareFn<TEvent, TResult, TErr>
43 onError: AttachMiddlewareFn<TEvent, TResult, TErr>
44 __middlewares: {
45 before: Array<MiddlewareFn<TEvent, TResult, TErr>>
46 after: Array<MiddlewareFn<TEvent, TResult, TErr>>
47 onError: Array<MiddlewareFn<TEvent, TResult, TErr>>
48 }
49 (event: TEvent, context: LambdaContext): Promise<TResult>
50}
51
52declare type AttachMiddlewareFn<TEvent = any, TResult = any, TErr = Error> = (middleware: MiddlewareFn) => MiddyfiedHandler<TEvent, TResult, TErr>
53
54declare type AttachMiddlewareObj<TEvent = any, TResult = any, TErr = Error> = (middleware: MiddlewareObj) => MiddyfiedHandler<TEvent, TResult, TErr>
55
56declare type UseFn<TEvent = any, TResult = any, TErr = Error> =
57 (middlewares: MiddlewareObj<TEvent, TResult, TErr> | Array<MiddlewareObj<TEvent, TResult, TErr>>) => MiddyfiedHandler<TEvent, TResult, TErr>
58
59/**
60 * Middy factory function. Use it to wrap your existing handler to enable middlewares on it.
61 * @param handler your original AWS Lambda function
62 * @param plugin wraps around each middleware and handler to add custom lifecycle behaviours (e.g. to profile performance)
63 */
64declare function middy<TEvent = any, TResult = any, TErr = Error> (handler?: LambdaHandler<TEvent, TResult>, plugin?: PluginObject): MiddyfiedHandler<TEvent, TResult, TErr>
65
66declare namespace middy {
67 export {
68 Request,
69 PluginHook,
70 PluginHookWithMiddlewareName,
71 PluginObject,
72 MiddlewareFn,
73 MiddlewareObj,
74 MiddyfiedHandler
75 }
76}
77
78export default middy