From 9c488132040ac478163f372a9afef77240f9e4c0 Mon Sep 17 00:00:00 2001 From: Jonathan Sharpe Date: Wed, 5 Feb 2025 14:34:58 +0000 Subject: [PATCH] Defer app import to keep app.js simpler --- api/__tests__/testUtils.js | 4 +-- api/app.js | 61 ++++++++++++++++++-------------------- api/server.js | 3 +- 3 files changed, 31 insertions(+), 37 deletions(-) diff --git a/api/__tests__/testUtils.js b/api/__tests__/testUtils.js index 12ebf06b..65a29834 100644 --- a/api/__tests__/testUtils.js +++ b/api/__tests__/testUtils.js @@ -1,11 +1,9 @@ import request from "supertest"; -import createApp from "../app.js"; - /** * @returns {Promise} */ export async function createRequest() { - const app = await createApp(); + const { default: app } = await import("../app.js"); return request(app); } diff --git a/api/app.js b/api/app.js index ccd2f7fc..debfe134 100644 --- a/api/app.js +++ b/api/app.js @@ -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; diff --git a/api/server.js b/api/server.js index d54b9328..2e42c81c 100644 --- a/api/server.js +++ b/api/server.js @@ -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"; @@ -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}`));