/
index.ts
70 lines (63 loc) · 1.64 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
import { ServerLogic } from "@phenyl/http-rules";
import {
HttpMethod,
QueryStringParams,
ServerParams
} from "@phenyl/interfaces";
export type LambdaCallback = (err?: Error | null, result?: any) => void;
export type LambdaHandler = (
event: LambdaEvent,
context: LambdaContext,
cb: LambdaCallback
) => any;
export type LambdaEvent = {
resource: string;
path: string;
httpMethod: HttpMethod;
headers: { [key: string]: string };
queryStringParameters: QueryStringParams;
pathParameters: { [key: string]: string };
requestContext: {
accountId: string;
resourceId: string;
stage: string;
requestId: string;
identity: Object;
resourcePath: string;
httpMethod: HttpMethod;
apiId: string;
};
body: string;
isBase64Encoded: boolean;
};
export type LambdaContext = Object;
/**
* This adapter runs the following three steps.
* 1. Prepare EncodedHttpRequest.
* 2. Invoke ServerLogic.
* 3. Return EncodedHttpResponse using callback.
*/
export const createLambdaHandler = (
params: ServerParams<any>
): LambdaHandler => {
return async (
event: LambdaEvent,
context: LambdaContext,
cb: LambdaCallback
): Promise<void> => {
/**
* Universal server logic.
* Offers the flow: EncodedHttpRequest => EncodedHttpResponse
*/
const logic = new ServerLogic(params);
const encodedHttpRequest = {
method: event.httpMethod,
path: event.path,
body: event.body,
headers: event.headers,
qsParams: event.queryStringParameters
};
const encodedHttpResponse = await logic.handleRequest(encodedHttpRequest);
cb(null, encodedHttpResponse);
};
};