Skip to content

Commit

Permalink
Defer app import to keep app.js simpler
Browse files Browse the repository at this point in the history
  • Loading branch information
textbook committed Feb 5, 2025
1 parent 2d7728c commit 9c48813
Show file tree
Hide file tree
Showing 3 changed files with 31 additions and 37 deletions.
4 changes: 1 addition & 3 deletions api/__tests__/testUtils.js
Original file line number Diff line number Diff line change
@@ -1,11 +1,9 @@
import request from "supertest";

import createApp from "../app.js";

/**
* @returns {Promise<import("supertest").Agent>}
*/
export async function createRequest() {
const app = await createApp();
const { default: app } = await import("../app.js");
return request(app);
}
61 changes: 29 additions & 32 deletions api/app.js
Original file line number Diff line number Diff line change
@@ -1,45 +1,42 @@
import express from "express";

import apiRouter from "./api.js";
import { testConnection } from "./db.js";
import config from "./utils/config.cjs";
import {
asyncHandler,
clientRouter,
configuredHelmet,
configuredMorgan,
httpsOnly,
logErrors,
} from "./utils/middleware.js";

const API_ROOT = "/api";

/** @type {import("express").Application} */
let app;
const app = express();

export default async function createApp() {
if (app) {
return app;
}
app.use(express.json());
app.use(configuredHelmet());
app.use(configuredMorgan());

const middleware = await import("./utils/middleware.js");

app = express();

app.use(express.json());
app.use(middleware.configuredHelmet());
app.use(middleware.configuredMorgan());

if (config.production) {
app.enable("trust proxy");
app.use(middleware.httpsOnly());
}
if (config.production) {
app.enable("trust proxy");
app.use(httpsOnly());
}

const { testConnection } = await import("./db.js");
app.get(
"/healthz",
middleware.asyncHandler(async (_, res) => {
await testConnection();
res.sendStatus(200);
}),
);
app.get(
"/healthz",
asyncHandler(async (_, res) => {
await testConnection();
res.sendStatus(200);
}),
);

const { default: apiRouter } = await import("./api.js");
app.use(API_ROOT, apiRouter);
app.use(API_ROOT, apiRouter);

app.use(middleware.clientRouter(API_ROOT));
app.use(clientRouter(API_ROOT));

app.use(middleware.logErrors());
app.use(logErrors());

return app;
}
export default app;
3 changes: 1 addition & 2 deletions api/server.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import createApp from "./app.js";
import { connectDb } from "./db.js";
import config from "./utils/config.cjs";
import logger from "./utils/logger.js";
Expand All @@ -7,6 +6,6 @@ const { port } = config.init();

await connectDb();

const app = await createApp();
const { default: app } = await import("./app.js");

app.listen(port, () => logger.info(`listening on ${port}`));

0 comments on commit 9c48813

Please sign in to comment.