Skip to content

Commit

Permalink
build: simplify backend entrypoint
Browse files Browse the repository at this point in the history
  • Loading branch information
AdrianAndersen committed Jan 19, 2025
1 parent f235a66 commit 3a26f75
Show file tree
Hide file tree
Showing 5 changed files with 82 additions and 94 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import { SeCrypto } from "@backend/crypto/se.crypto";
import { SEResponseHandler } from "@backend/response/se.response.handler";
import { Router } from "express";

export function initAuthEndpoints(router: Router) {
export function createAuthEndpoints(router: Router) {
const userHandler = new UserHandler();

const localLoginPasswordValidator = new LocalLoginPasswordValidator(
Expand Down
57 changes: 25 additions & 32 deletions backend/src/collection-endpoint/collection-endpoint-creator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,40 +18,33 @@ import { StandMatchCollection } from "@backend/collections/stand-match/stand-mat
import { UniqueItemCollection } from "@backend/collections/unique-item/unique-item.collection";
import { UserDetailCollection } from "@backend/collections/user-detail/user-detail.collection";
import { UserMatchCollection } from "@backend/collections/user-match/user-match.collection";
import { SEResponseHandler } from "@backend/response/se.response.handler";
import { Router } from "express";

export class CollectionEndpointCreator {
constructor(private router: Router) {
new SEResponseHandler();
}

create() {
const collectionEndpoints = [
new CollectionEndpoint(this.router, BranchCollection),
new CollectionEndpoint(this.router, BranchItemCollection),
new CollectionEndpoint(this.router, CustomerItemCollection),
new CollectionEndpoint(this.router, DeliveryCollection),
new CollectionEndpoint(this.router, ItemCollection),
new CollectionEndpoint(this.router, OpeningHourCollection),
new CollectionEndpoint(this.router, OrderCollection),
new CollectionEndpoint(this.router, PaymentCollection),
new CollectionEndpoint(this.router, UserDetailCollection),
new CollectionEndpoint(this.router, PendingPasswordResetCollection),
new CollectionEndpoint(this.router, EmailValidationCollection),
new CollectionEndpoint(this.router, MessageCollection),
new CollectionEndpoint(this.router, StandMatchCollection),
new CollectionEndpoint(this.router, UserMatchCollection),
new CollectionEndpoint(this.router, InvoiceCollection),
new CollectionEndpoint(this.router, CompanyCollection),
new CollectionEndpoint(this.router, UniqueItemCollection),
new CollectionEndpoint(this.router, EditableTextCollection),
new CollectionEndpoint(this.router, SignatureCollection),
];
export function createCollectionEndpoints(router: Router) {
const collectionEndpoints = [
new CollectionEndpoint(router, BranchCollection),
new CollectionEndpoint(router, BranchItemCollection),
new CollectionEndpoint(router, CustomerItemCollection),
new CollectionEndpoint(router, DeliveryCollection),
new CollectionEndpoint(router, ItemCollection),
new CollectionEndpoint(router, OpeningHourCollection),
new CollectionEndpoint(router, OrderCollection),
new CollectionEndpoint(router, PaymentCollection),
new CollectionEndpoint(router, UserDetailCollection),
new CollectionEndpoint(router, PendingPasswordResetCollection),
new CollectionEndpoint(router, EmailValidationCollection),
new CollectionEndpoint(router, MessageCollection),
new CollectionEndpoint(router, StandMatchCollection),
new CollectionEndpoint(router, UserMatchCollection),
new CollectionEndpoint(router, InvoiceCollection),
new CollectionEndpoint(router, CompanyCollection),
new CollectionEndpoint(router, UniqueItemCollection),
new CollectionEndpoint(router, EditableTextCollection),
new CollectionEndpoint(router, SignatureCollection),
];

for (const collectionEndpoint of collectionEndpoints) {
collectionEndpoint.create();
collectionEndpoint.printEndpoints();
}
for (const collectionEndpoint of collectionEndpoints) {
collectionEndpoint.create();
collectionEndpoint.printEndpoints();
}
}
1 change: 1 addition & 0 deletions backend/src/collections/order/order.collection.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { BlCollection } from "@backend/collections/bl-collection";
import { OrderPatchHook } from "@backend/collections/order/hooks/order.patch.hook";
import { OrderPostHook } from "@backend/collections/order/hooks/order.post.hook";
import { BulkOrderOperation } from "@backend/collections/order/operations/bulk-order.operation";

Check failure on line 4 in backend/src/collections/order/order.collection.ts

View workflow job for this annotation

GitHub Actions / Lint

'BulkOrderOperation' is defined but never used
import { OrderConfirmOperation } from "@backend/collections/order/operations/confirm/order-confirm.operation";
import { OrderAgreementPdfOperation } from "@backend/collections/order/operations/order-agreement-pdf.operation";
import { OrderReceiptPdfOperation } from "@backend/collections/order/operations/order-receipt-pdf.operation";
Expand Down
67 changes: 15 additions & 52 deletions backend/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,17 @@
import "@backend/instrument";

import { initAuthEndpoints } from "@backend/auth/initAuthEndpoints";
import { CollectionEndpointCreator } from "@backend/collection-endpoint/collection-endpoint-creator";
import { assertEnv, BlEnvironment } from "@backend/config/environment";
import { createAuthEndpoints } from "@backend/auth/auth-endpoint-creator";
import { createCollectionEndpoints } from "@backend/collection-endpoint/collection-endpoint-creator";
import { logger } from "@backend/logger/logger";
import {
connectToDbAndStartServer,
getCorsHandler,
getDebugLoggerHandler,
getRedirectToHttpsHandler,
getSessionHandler,
} from "@backend/server/server";
import express, { json, Request, Response, Router } from "express";
import * as Sentry from "@sentry/node";
import express, { json, Router } from "express";
import passport from "passport";

logger.silly(" _ _ _");
Expand All @@ -21,67 +23,28 @@ logger.silly(" |_|");

const app = express();
const router = Router();

app.use(json({ limit: "1mb" }));

process.on("unhandledRejection", (reason, p) => {
logger.error(
`unhandled rejection at: ${p}, reason: ${reason}` +
(reason instanceof Error ? `, stack: ${reason.stack}` : ""),
);
});

app.use(getCorsHandler());
app.use(getSessionHandler());
app.use(getDebugLoggerHandler());
app.use(passport.initialize());
app.use(passport.session());

app.get("*", (request, res, next) => {
if (
request.headers["x-forwarded-proto"] !== "https" &&
assertEnv(BlEnvironment.API_ENV) === "production"
) {
res.redirect("https://" + request.hostname + request.url);
} else {
next();
}
});

app.use((request: Request, res: Response, next: () => void) => {
if (request.method !== "OPTIONS") {
// no point in showing all the preflight requests
logger.debug(`-> ${request.method} ${request.url}`);
if (
!(
request.url.includes("auth") &&
assertEnv(BlEnvironment.API_ENV) === "production"
)
) {
let body: string;
try {
body = JSON.stringify(request.body);
} catch {
body = request.body.toString("utf8");
}

logger.silly(`-> ${body}`);
}
}
next();
});

app.use(router);

passport.serializeUser((user, done) => {
done(null, user);
});

passport.deserializeUser((user, done) => {
// @ts-expect-error fixme: auto ignored
done(null, user);
});

initAuthEndpoints(router);
new CollectionEndpointCreator(router).create();
app.get("*", getRedirectToHttpsHandler());

createAuthEndpoints(router);
createCollectionEndpoints(router);
app.use(router);

Sentry.profiler.startProfiler();
Sentry.setupExpressErrorHandler(app);

connectToDbAndStartServer(app);
49 changes: 40 additions & 9 deletions backend/src/server/server.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,7 @@
import { assertEnv, BlEnvironment } from "@backend/config/environment";
import { logger } from "@backend/logger/logger";
import * as Sentry from "@sentry/node";
import cors from "cors";
import { Express, RequestHandler } from "express";
import { Express, Request, RequestHandler, Response } from "express";
import session from "express-session";
import mongoose from "mongoose";

Expand All @@ -27,6 +26,44 @@ export function getSessionHandler(): RequestHandler {
});
}

export function getRedirectToHttpsHandler(): RequestHandler {
return (request, res, next) => {
if (
request.headers["x-forwarded-proto"] !== "https" &&
assertEnv(BlEnvironment.API_ENV) === "production"
) {
res.redirect("https://" + request.hostname + request.url);
} else {
next();
}
};
}

export function getDebugLoggerHandler(): RequestHandler {
return (request: Request, res: Response, next: () => void) => {
if (request.method !== "OPTIONS") {
// no point in showing all the preflight requests
logger.debug(`-> ${request.method} ${request.url}`);
if (
!(
request.url.includes("auth") &&
assertEnv(BlEnvironment.API_ENV) === "production"
)
) {
let body: string;
try {
body = JSON.stringify(request.body);
} catch {
body = request.body.toString("utf8");
}

logger.silly(`-> ${body}`);
}
}
next();
};
}

export async function connectToDbAndStartServer(app: Express) {
mongoose.connection.on("disconnected", () => {
logger.error("mongoose connection was disconnected");
Expand All @@ -46,13 +83,7 @@ export async function connectToDbAndStartServer(app: Express) {
socketTimeoutMS: 45_000,
});

if (assertEnv(BlEnvironment.API_ENV) === "production") {
Sentry.profiler.startProfiler();
Sentry.setupExpressErrorHandler(app);
}

app.set("port", assertEnv(BlEnvironment.PORT));
app.listen(app.get("port"), () => {
app.listen(assertEnv(BlEnvironment.PORT), () => {
logger.info("ready to take requests!");
});
}

0 comments on commit 3a26f75

Please sign in to comment.