Skip to content

Commit

Permalink
fix
Browse files Browse the repository at this point in the history
  • Loading branch information
phjardas committed Dec 13, 2023
1 parent 6abcbb7 commit e5275f9
Show file tree
Hide file tree
Showing 4 changed files with 34 additions and 31 deletions.
13 changes: 4 additions & 9 deletions src/local/api.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import * as bodyParser from "body-parser";
import { RequestHandler, Router } from "express";
import { Router, type RequestHandler } from "express";
import type { HTTPLambdaHandler } from "../types";
import { createAuthorizers } from "./authorizer";
import { expressLambda } from "./express-lambda";
Expand Down Expand Up @@ -59,7 +59,7 @@ class LocalExpressAPI {
bodyParser.raw({
type: requestBody.mimeTypes ?? "*/*",
limit: requestBody.limit,
})
}),
);
break;
}
Expand Down Expand Up @@ -104,13 +104,8 @@ export async function createLocalExpressAPI({
.map((route) => route.path)
.filter((val, index, arr) => arr.indexOf(val) === index)
.map((path) =>
api.route({
method: "options",
path,
handlerId: "cors",
handler: optionsHandler,
})
)
api.route({ method: "options", path, handlerId: "cors" }),
),
);
}

Expand Down
40 changes: 21 additions & 19 deletions src/local/express-lambda.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,26 +3,25 @@ import type {
APIGatewayProxyEventBase,
APIGatewayProxyResult,
Context,
Handler,
} from "aws-lambda";
import * as express from "express";
import type { AuthorizedLambdaEvent, AuthorizerContext } from "../types";
import { LoggerImpl } from "../logging";
import type {
AuthorizedLambdaEvent,
AuthorizerContext,
HTTPLambdaHandler,
} from "../types";

export function expressLambda(
name: string,
handler: Handler<
APIGatewayProxyEventBase<AuthorizerContext>,
APIGatewayProxyResult | undefined
>
handler: HTTPLambdaHandler,
): express.RequestHandler {
return async (req, res, next) => {
try {
const event = createEvent<AuthorizerContext>(req);
const context = createContext({ name });

const response = await handler(event, context, () => {
throw new Error("Lambda handler with callback is not supported");
});
const logger = new LoggerImpl();
const response = await handler(event, context, logger);

sendResponse(response, res);
} catch (error) {
Expand All @@ -32,11 +31,11 @@ export function expressLambda(
}

export function createEvent<TAuthorizerContext>(
req: express.Request
req: express.Request,
): APIGatewayProxyEventBase<TAuthorizerContext> {
const headers = Object.entries(req.headers).reduce(
(acc, [key, value]) => ({ ...acc, [key]: value }),
{}
{},
);

return {
Expand Down Expand Up @@ -70,7 +69,7 @@ export function createEvent<TAuthorizerContext>(
}

function parseBody(
body: null | string | Buffer
body: null | string | Buffer,
): Pick<APIGatewayProxyEventBase<unknown>, "body" | "isBase64Encoded"> {
if (body instanceof Buffer) {
return {
Expand Down Expand Up @@ -118,21 +117,21 @@ export function createContext({

function sendResponse(
response: APIGatewayProxyResult | undefined | void,
res: express.Response<unknown, Record<string, unknown>>
res: express.Response<unknown, Record<string, unknown>>,
) {
if (response) {
res.status(response.statusCode || 200);
if (response.headers) {
Object.entries(response.headers).forEach(([key, value]) =>
res.set(key, value.toString())
res.set(key, value.toString()),
);
}

if (response.body) {
res.send(
response.isBase64Encoded
? Buffer.from(response.body, "base64")
: response.body
: response.body,
);
} else {
res.end();
Expand All @@ -143,20 +142,23 @@ function sendResponse(
}

function createQueryStringParameters(
req: express.Request
req: express.Request,
): Pick<
AuthorizedLambdaEvent,
"queryStringParameters" | "multiValueQueryStringParameters"
> {
const entries = Object.entries(req.query).map(([key, value]) =>
typeof value === "string"
? [key, [value]]
: [key, Array.isArray(value) ? value.map((v) => v.toString()) : undefined]
: [
key,
Array.isArray(value) ? value.map((v) => v.toString()) : undefined,
],
);

return {
queryStringParameters: Object.fromEntries(
entries.map(([key, value]) => [key, value?.slice(-1)?.[0]])
entries.map(([key, value]) => [key, value?.slice(-1)?.[0]]),
),
multiValueQueryStringParameters: Object.fromEntries(entries),
};
Expand Down
5 changes: 3 additions & 2 deletions src/local/types.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import type {
APIGatewayProxyHandler,
APIGatewayRequestAuthorizerHandler,
APIGatewayTokenAuthorizerHandler,
} from "aws-lambda";
Expand All @@ -22,7 +23,7 @@ export type AuthorizerRegistration = { id: string } & (
);

export type HandlerResolver = (
handlerId: string
handlerId: string,
) => HTTPLambdaHandler | Promise<HTTPLambdaHandler>;

export type Method =
Expand Down Expand Up @@ -57,6 +58,6 @@ export type Route = {
export type APIOptions = {
handlerResolver: HandlerResolver;
routes: Array<Route>;
optionsHandler?: HTTPLambdaHandler;
optionsHandler?: APIGatewayProxyHandler;
authorizers?: Array<AuthorizerRegistration>;
};
7 changes: 6 additions & 1 deletion src/logging.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,12 @@ import log, { type JsonLog } from "json-log";
export * from "json-log";
export { default } from "json-log";

export interface Logger {}
export interface Logger {
addContext(context: Record<string, unknown>): void;
info(message: string, data?: Record<string, unknown>): void;
warn(message: string, data?: Record<string, unknown>): void;
error(message: string, data?: Record<string, unknown>): void;
}

export class LoggerImpl implements Logger {
constructor(
Expand Down

0 comments on commit e5275f9

Please sign in to comment.