Skip to content

Commit

Permalink
style(Bun): Introduce Bun to email-function
Browse files Browse the repository at this point in the history
  • Loading branch information
simonknittel committed Feb 18, 2024
1 parent 6feb3c5 commit fceaf4c
Show file tree
Hide file tree
Showing 22 changed files with 424 additions and 356 deletions.
6 changes: 3 additions & 3 deletions .github/workflows/validate-app.yml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ jobs:
path: app/node_modules
key: ${{ runner.os }}-${{ hashFiles('app/.nvmrc', 'app/package-lock.json', 'app/prisma/prisma.schema') }}

- name: Install app dependencies
- name: Install dependencies
run: npm ci
working-directory: app
if: steps.node-modules-cache.outputs.cache-hit != 'true'
Expand Down Expand Up @@ -70,7 +70,7 @@ jobs:
path: app/node_modules
key: ${{ runner.os }}-${{ hashFiles('app/.nvmrc', 'app/package-lock.json', 'app/prisma/prisma.schema') }}

- name: Install app dependencies
- name: Install dependencies
run: npm ci
working-directory: app
if: steps.node-modules-cache.outputs.cache-hit != 'true'
Expand All @@ -96,7 +96,7 @@ jobs:
path: app/node_modules
key: ${{ runner.os }}-${{ hashFiles('app/.nvmrc', 'app/package-lock.json', 'app/prisma/prisma.schema') }}

- name: Install app dependencies
- name: Install dependencies
run: npm ci
working-directory: app
if: steps.node-modules-cache.outputs.cache-hit != 'true'
Expand Down
27 changes: 27 additions & 0 deletions .github/workflows/validate-email-function.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
name: Validate email-function

on:
pull_request:
branches:
- main
- develop
paths:
- .github/workflows/validate-email-function.yml
- bun-packages/packages/email-function/**
- bun-packages/biome.json

jobs:
prettier:
runs-on: ubuntu-22.04

steps:
- uses: actions/[email protected]

- name: Set up Biome
uses: biomejs/setup-biome@v2
with:
version: 1.5.3

- name: Run Biome
run: biome ci .
working-directory: bun-packages/packages/email-function
5 changes: 5 additions & 0 deletions bun-packages/.vscode/extensions.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"recommendations": [
"biomejs.biome"
]
}
20 changes: 20 additions & 0 deletions bun-packages/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
{
"cSpell.words": [
"biomejs"
],
"[typescript]": {
"editor.defaultFormatter": "biomejs.biome",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"quickfix.biome": "explicit",
"source.organizeImports.biome": "explicit"
}
},
"[json]": {
"editor.defaultFormatter": "biomejs.biome",
"editor.formatOnSave": true,
"editor.codeActionsOnSave": {
"quickfix.biome": "explicit"
}
}
}
18 changes: 18 additions & 0 deletions bun-packages/biome.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
{
"$schema": "https://biomejs.dev/schemas/1.5.3/schema.json",
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
},
"vcs": {
"enabled": true,
"clientKind": "git",
"useIgnoreFile": true,
"defaultBranch": "default"
}
}
Binary file modified bun-packages/bun.lockb
Binary file not shown.
13 changes: 8 additions & 5 deletions bun-packages/package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
{
"name": "bun-packages",
"version": "0.1.0",
"workspaces": [
"packages/*"
]
"name": "bun-packages",
"version": "0.1.0",
"workspaces": [
"packages/*"
],
"devDependencies": {
"@biomejs/biome": "1.5.3"
}
}
54 changes: 27 additions & 27 deletions bun-packages/packages/email-function/package.json
Original file line number Diff line number Diff line change
@@ -1,29 +1,29 @@
{
"name": "email-function",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"build:lambda": "rm -rf dist && esbuild src/lambda.ts --bundle --outfile=dist/lambda.js --platform=node --target=node18 --minify --metafile=meta.json",
"build:node": "rm -rf dist && esbuild src/node.ts --bundle --outfile=dist/node.js --platform=node --target=node18 --format=esm --metafile=meta.json",
"start:node": "npm run build:node && node dist/node.js",
"lint": "tsc --project tsconfig.node.json"
},
"devDependencies": {
"esbuild": "0.20.0",
"typescript": "5.3.3"
},
"dependencies": {
"@aws-sdk/client-dynamodb": "3.511.0",
"@openpgp/web-stream-tools": "0.1.1",
"@react-email/render": "0.0.12",
"@types/aws-lambda": "8.10.133",
"@types/node": "20.10.2",
"dotenv": "16.4.2",
"form-data": "4.0.0",
"mailgun.js": "10.1.0",
"openpgp": "5.11.0",
"serialize-error": "11.0.3",
"zod": "3.22.4"
}
"name": "email-function",
"version": "0.1.0",
"private": true,
"type": "module",
"scripts": {
"build:lambda": "rm -rf dist && esbuild src/lambda.ts --bundle --outfile=dist/lambda.js --platform=node --target=node18 --minify --metafile=meta.json",
"build:node": "rm -rf dist && esbuild src/node.ts --bundle --outfile=dist/node.js --platform=node --target=node18 --format=esm --metafile=meta.json",
"start:node": "npm run build:node && node dist/node.js",
"lint": "tsc --project tsconfig.node.json"
},
"devDependencies": {
"esbuild": "0.20.0",
"typescript": "5.3.3"
},
"dependencies": {
"@aws-sdk/client-dynamodb": "3.511.0",
"@openpgp/web-stream-tools": "0.1.1",
"@react-email/render": "0.0.12",
"@types/aws-lambda": "8.10.133",
"@types/node": "20.10.2",
"dotenv": "16.4.2",
"form-data": "4.0.0",
"mailgun.js": "10.1.0",
"openpgp": "5.11.0",
"serialize-error": "11.0.3",
"zod": "3.22.4"
}
}
22 changes: 11 additions & 11 deletions bun-packages/packages/email-function/src/_lib/authorization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,20 +2,20 @@ import { z } from "zod";
import { fetchParameters } from "./fetchParameters";

export const authenticate = async (event) => {
const result = eventSchema.safeParse(event);
if (!result.success) throw new Error("Unauthorized");
const result = eventSchema.safeParse(event);
if (!result.success) throw new Error("Unauthorized");

const authParameters = await fetchParameters({
// deepcode ignore HardcodedNonCryptoSecret: This is not the actual secret but a reference to the secret in the parameters store
apiKey: "/email-function/api-key",
});
const authParameters = await fetchParameters({
// deepcode ignore HardcodedNonCryptoSecret: This is not the actual secret but a reference to the secret in the parameters store
apiKey: "/email-function/api-key",
});

if (result.data.headers.authorization !== `Bearer ${authParameters.apiKey}`)
throw new Error("Unauthorized");
if (result.data.headers.authorization !== `Bearer ${authParameters.apiKey}`)
throw new Error("Unauthorized");
};

const eventSchema = z.object({
headers: z.object({
authorization: z.string(),
}),
headers: z.object({
authorization: z.string(),
}),
});
7 changes: 5 additions & 2 deletions bun-packages/packages/email-function/src/_lib/encryptText.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
import { createMessage, encrypt, readKey } from 'openpgp';
import { createMessage, encrypt, readKey } from "openpgp";

export const encryptText = async (unencryptedText: string, publicKey: string) => {
export const encryptText = async (
unencryptedText: string,
publicKey: string,
) => {
const key = await readKey({ armoredKey: publicKey });

const message = await createMessage({ text: unencryptedText });
Expand Down
84 changes: 42 additions & 42 deletions bun-packages/packages/email-function/src/_lib/errorHandler.ts
Original file line number Diff line number Diff line change
@@ -1,50 +1,50 @@
import { serializeError } from "serialize-error";
import { ZodError } from "zod";
import { log } from "./logging";
import { CustomError } from "./logging/CustomError";
import { serializeError } from "serialize-error";

export const errorHandler = (error: unknown) => {
if (error instanceof ZodError) {
return {
statusCode: 400,
body: JSON.stringify({
message: "Bad request",
errors: error.errors,
}),
};
} else if (error instanceof Error && error.message === "Bad request") {
return {
statusCode: 400,
body: JSON.stringify({
message: "Bad request",
}),
};
} else if (error instanceof Error && error.message === "Unauthorized") {
return {
statusCode: 401,
body: JSON.stringify({
message: "Unauthorized",
}),
};
} else if (error instanceof CustomError) {
log.error(error.message, serializeError(error.context));
if (error instanceof ZodError) {
return {
statusCode: 400,
body: JSON.stringify({
message: "Bad request",
errors: error.errors,
}),
};
} else if (error instanceof Error && error.message === "Bad request") {
return {
statusCode: 400,
body: JSON.stringify({
message: "Bad request",
}),
};
} else if (error instanceof Error && error.message === "Unauthorized") {
return {
statusCode: 401,
body: JSON.stringify({
message: "Unauthorized",
}),
};
} else if (error instanceof CustomError) {
log.error(error.message, serializeError(error.context));

return {
statusCode: 500,
body: JSON.stringify({
message: "Internal server error",
}),
};
}
return {
statusCode: 500,
body: JSON.stringify({
message: "Internal server error",
}),
};
}

log.error("errorHandler", {
error: serializeError(error),
});
log.error("errorHandler", {
error: serializeError(error),
});

return {
statusCode: 500,
body: JSON.stringify({
message: "Internal server error",
}),
};
}
return {
statusCode: 500,
body: JSON.stringify({
message: "Internal server error",
}),
};
};
68 changes: 34 additions & 34 deletions bun-packages/packages/email-function/src/_lib/fetchParameters.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,42 +2,42 @@ import { z } from "zod";
import { CustomError } from "./logging/CustomError";

export const fetchParameters = async <T extends Record<string, string>>(
parameters: T
parameters: T,
): Promise<T> => {
if (!process.env.AWS_SESSION_TOKEN)
throw new Error("Missing AWS_SESSION_TOKEN for fetching parameters store");

const responses = await Promise.all(
Object.entries(parameters).map(async ([key, name]) => {
const uriEncodedParameterName = encodeURIComponent(name);

const response = await fetch(
`http://localhost:2773/systemsmanager/parameters/get?name=${uriEncodedParameterName}&withDecryption=true`,
{
headers: {
"X-Aws-Parameters-Secrets-Token": process.env.AWS_SESSION_TOKEN!,
},
}
);

if (!response.ok)
throw new CustomError("Failed to fetch parameters store", {
response: response.status,
body: await response.text(),
});

const body = await response.json();
const parameter = parameterSchema.parse(body);

return [key, parameter.Parameter.Value];
})
);

return Object.fromEntries(responses);
if (!process.env.AWS_SESSION_TOKEN)
throw new Error("Missing AWS_SESSION_TOKEN for fetching parameters store");

const responses = await Promise.all(
Object.entries(parameters).map(async ([key, name]) => {
const uriEncodedParameterName = encodeURIComponent(name);

const response = await fetch(
`http://localhost:2773/systemsmanager/parameters/get?name=${uriEncodedParameterName}&withDecryption=true`,
{
headers: {
"X-Aws-Parameters-Secrets-Token": process.env.AWS_SESSION_TOKEN!,
},
},
);

if (!response.ok)
throw new CustomError("Failed to fetch parameters store", {
response: response.status,
body: await response.text(),
});

const body = await response.json();
const parameter = parameterSchema.parse(body);

return [key, parameter.Parameter.Value];
}),
);

return Object.fromEntries(responses);
};

const parameterSchema = z.object({
Parameter: z.object({
Value: z.string(),
}),
Parameter: z.object({
Value: z.string(),
}),
});
Loading

0 comments on commit fceaf4c

Please sign in to comment.