@enter-at/lambda-handlers
Version:
An opinionated Typescript package that facilitates specifying AWS Lambda handlers including input validation, error handling and response formatting.
86 lines (85 loc) • 2.99 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.APIGatewayProxyHandler = void 0;
const error_1 = require("../error");
const header_1 = require("../header");
const response_1 = require("../response");
const BaseHandler_1 = require("./BaseHandler");
const index_1 = require("../index");
class APIGatewayProxyHandler extends BaseHandler_1.BaseHandler {
static handleError(err) {
if (err instanceof error_1.ForbiddenError) {
return (0, response_1.forbidden)(err.details);
}
if (err instanceof error_1.UnauthorizedError) {
return (0, response_1.unauthorized)(err.details);
}
if (err instanceof error_1.BadRequestError || err instanceof error_1.FormatError || err instanceof error_1.ValidationError) {
return (0, response_1.badRequest)(err.details);
}
if (err instanceof error_1.RequestTimeoutError) {
return (0, response_1.requestTimeout)(err.details);
}
if (err instanceof error_1.UnprocessableEntityError) {
return (0, response_1.unprocessableEntity)(err.details);
}
if (err instanceof error_1.NotFoundError) {
return (0, response_1.notFound)(err.details);
}
if (err instanceof error_1.ConflictError) {
return (0, response_1.conflict)(err.details);
}
index_1.config.logger.error({
name: err.name,
message: err.message,
stack: err.stack,
});
return (0, response_1.internalServerError)();
}
corsHeader;
constructor(args) {
super(args);
this.corsHeader = args?.cors ?? new header_1.CORSHeader("*", true);
}
after(result) {
result = result ?? (0, response_1.noContent)();
if (result.statusCode === undefined) {
result = (0, response_1.ok)(result);
}
return this.createResponse(result);
}
onException(exception) {
return this.createResponse(APIGatewayProxyHandler.handleError(exception));
}
formatInput(event) {
if (!event.body) {
return event;
}
try {
event.body = this.inputFormat.apply(event.body);
return event;
}
catch (err) {
throw err;
}
}
formatOutput(result) {
const { body, ...properties } = result;
return {
body: body ? this.outputFormat.apply(body) : "",
...properties,
};
}
createResponse(result) {
result.headers = this.createHeaders(result.headers);
return this.formatOutput(result);
}
createHeaders(headers) {
return {
...headers,
...(this.corsHeader && this.corsHeader.create()),
...(this.outputFormat && new header_1.ContentTypeHeader(this.outputFormat.contentType).create()),
};
}
}
exports.APIGatewayProxyHandler = APIGatewayProxyHandler;