|
| 1 | +import Joi from '@hapi/joi'; |
| 2 | +import { metricScope, MetricsLogger } from 'aws-embedded-metrics'; |
| 3 | +import { |
| 4 | + APIGatewayProxyEvent, |
| 5 | + APIGatewayProxyHandler, |
| 6 | + APIGatewayProxyResult, |
| 7 | + Context, |
| 8 | +} from 'aws-lambda'; |
| 9 | +import { default as bunyan, default as Logger } from 'bunyan'; |
| 10 | + |
| 11 | +export type BaseRInj = { |
| 12 | + log: Logger; |
| 13 | +}; |
| 14 | + |
| 15 | +export type HandleRequestParams<CInj, RInj, Req> = { |
| 16 | + context: Context; |
| 17 | + event: APIGatewayProxyEvent; |
| 18 | + request: Req; |
| 19 | + containerInjected: CInj; |
| 20 | + requestInjected: RInj; |
| 21 | +}; |
| 22 | + |
| 23 | +export type Response<Res> = { |
| 24 | + statusCode: number; |
| 25 | + body: Res; |
| 26 | +}; |
| 27 | + |
| 28 | +export abstract class Injector<CInj, RInj extends BaseRInj, Req> { |
| 29 | + private containerInjected: CInj; |
| 30 | + public constructor() {} |
| 31 | + |
| 32 | + public async build() { |
| 33 | + this.containerInjected = await this.buildContainerInjected(); |
| 34 | + return this; |
| 35 | + } |
| 36 | + |
| 37 | + public abstract getRequestInjected( |
| 38 | + containerInjected: CInj, |
| 39 | + request: Req, |
| 40 | + event: APIGatewayProxyEvent, |
| 41 | + context: Context, |
| 42 | + log: Logger, |
| 43 | + metrics: MetricsLogger |
| 44 | + ): Promise<RInj>; |
| 45 | + |
| 46 | + public abstract buildContainerInjected(): Promise<CInj>; |
| 47 | + |
| 48 | + public async getContainerInjected(): Promise<CInj> { |
| 49 | + if (this.containerInjected === undefined) { |
| 50 | + throw new Error( |
| 51 | + 'Container injected undefined. Must call build() before using.' |
| 52 | + ); |
| 53 | + } |
| 54 | + return this.containerInjected; |
| 55 | + } |
| 56 | +} |
| 57 | + |
| 58 | +export abstract class APIGLambdaHandler<CInj, RInj extends BaseRInj, Req, Res> { |
| 59 | + constructor( |
| 60 | + private handlerName: string, |
| 61 | + private injector: Injector<CInj, RInj, Req> |
| 62 | + ) {} |
| 63 | + |
| 64 | + get handler(): APIGatewayProxyHandler { |
| 65 | + return metricScope( |
| 66 | + (metric: MetricsLogger) => |
| 67 | + async ( |
| 68 | + event: APIGatewayProxyEvent, |
| 69 | + context: Context |
| 70 | + ): Promise<APIGatewayProxyResult> => { |
| 71 | + let log: Logger = bunyan.createLogger({ |
| 72 | + name: this.handlerName, |
| 73 | + serializers: bunyan.stdSerializers, |
| 74 | + level: bunyan.INFO, |
| 75 | + requestId: context.awsRequestId, |
| 76 | + }); |
| 77 | + |
| 78 | + log.info({ event, context }, 'Request started.'); |
| 79 | + |
| 80 | + let request: Req; |
| 81 | + try { |
| 82 | + const requestValidation = await this.parseAndValidateRequest(event); |
| 83 | + |
| 84 | + if (requestValidation.state == 'invalid') { |
| 85 | + return requestValidation.errorResponse; |
| 86 | + } |
| 87 | + |
| 88 | + request = requestValidation.request; |
| 89 | + } catch (err) { |
| 90 | + log.error({ err }, 'Unexpected error validating request'); |
| 91 | + return { statusCode: 500, body: 'Internal error' }; |
| 92 | + } |
| 93 | + |
| 94 | + const containerInjected = await this.injector.getContainerInjected(); |
| 95 | + |
| 96 | + let requestInjected: RInj; |
| 97 | + try { |
| 98 | + requestInjected = await this.injector.getRequestInjected( |
| 99 | + containerInjected, |
| 100 | + request, |
| 101 | + event, |
| 102 | + context, |
| 103 | + log, |
| 104 | + metric |
| 105 | + ); |
| 106 | + } catch (err) { |
| 107 | + log.error({ err, event }, 'Error building request injected.'); |
| 108 | + return { statusCode: 500, body: 'Internal error' }; |
| 109 | + } |
| 110 | + |
| 111 | + ({ log } = requestInjected); |
| 112 | + |
| 113 | + let statusCode: number; |
| 114 | + let body: Res; |
| 115 | + |
| 116 | + log.info({ request }, 'Invoking handle request'); |
| 117 | + try { |
| 118 | + ({ statusCode, body } = await this.handleRequest({ |
| 119 | + context, |
| 120 | + event, |
| 121 | + request, |
| 122 | + containerInjected, |
| 123 | + requestInjected, |
| 124 | + })); |
| 125 | + } catch (err) { |
| 126 | + log.error({ err }, 'Unexpected error in handler'); |
| 127 | + return { statusCode: 500, body: 'Internal error' }; |
| 128 | + } |
| 129 | + |
| 130 | + // let response: Res; |
| 131 | + try { |
| 132 | + const responseValidation = await this.parseAndValidateResponse( |
| 133 | + body |
| 134 | + ); |
| 135 | + |
| 136 | + if (responseValidation.state == 'invalid') { |
| 137 | + return responseValidation.errorResponse; |
| 138 | + } |
| 139 | + |
| 140 | + // response = responseValidation.response; |
| 141 | + } catch (err) { |
| 142 | + log.error({ err }, 'Unexpected error in handler'); |
| 143 | + return { statusCode: 500, body: 'Internal error' }; |
| 144 | + } |
| 145 | + |
| 146 | + return { statusCode, body: JSON.stringify(body) }; |
| 147 | + } |
| 148 | + ); |
| 149 | + } |
| 150 | + |
| 151 | + public abstract handleRequest( |
| 152 | + params: HandleRequestParams<CInj, RInj, Req> |
| 153 | + ): Promise<Response<Res>>; |
| 154 | + |
| 155 | + protected abstract requestBodySchema(): Joi.ObjectSchema | null; |
| 156 | + protected abstract responseBodySchema(): Joi.ObjectSchema | null; |
| 157 | + |
| 158 | + private async parseAndValidateRequest( |
| 159 | + event: APIGatewayProxyEvent |
| 160 | + ): Promise< |
| 161 | + | { state: 'valid'; request: Req } |
| 162 | + | { state: 'invalid'; errorResponse: APIGatewayProxyResult } |
| 163 | + > { |
| 164 | + let body: any; |
| 165 | + try { |
| 166 | + body = JSON.parse(event.body ?? ''); |
| 167 | + } catch (err) { |
| 168 | + return { state: 'invalid', errorResponse: { statusCode: 422, body: '' } }; |
| 169 | + } |
| 170 | + |
| 171 | + const bodySchema = this.requestBodySchema(); |
| 172 | + |
| 173 | + if (!bodySchema) { |
| 174 | + return { state: 'valid', request: body as Req }; |
| 175 | + } |
| 176 | + |
| 177 | + const res = bodySchema.validate(body, { |
| 178 | + allowUnknown: true, // Makes API schema changes and rollbacks easier. |
| 179 | + stripUnknown: true, |
| 180 | + }); |
| 181 | + |
| 182 | + if (res.error) { |
| 183 | + return { |
| 184 | + state: 'invalid', |
| 185 | + errorResponse: { statusCode: 400, body: res.error.message }, |
| 186 | + }; |
| 187 | + } |
| 188 | + |
| 189 | + return { state: 'valid', request: res.value as Req }; |
| 190 | + } |
| 191 | + |
| 192 | + private async parseAndValidateResponse( |
| 193 | + body: Res |
| 194 | + ): Promise< |
| 195 | + | { state: 'valid'; response: Res } |
| 196 | + | { state: 'invalid'; errorResponse: APIGatewayProxyResult } |
| 197 | + > { |
| 198 | + const responseSchema = this.responseBodySchema(); |
| 199 | + |
| 200 | + if (!responseSchema) { |
| 201 | + return { state: 'valid', response: body as Res }; |
| 202 | + } |
| 203 | + |
| 204 | + const res = responseSchema.validate(body, { |
| 205 | + allowUnknown: true, |
| 206 | + stripUnknown: true, // Ensure no unexpected fields returned to users. |
| 207 | + }); |
| 208 | + |
| 209 | + if (res.error) { |
| 210 | + return { |
| 211 | + state: 'invalid', |
| 212 | + errorResponse: { statusCode: 500, body: 'Internal error' }, |
| 213 | + }; |
| 214 | + } |
| 215 | + |
| 216 | + return { state: 'valid', response: res.value as Res }; |
| 217 | + } |
| 218 | +} |
0 commit comments