Skip to content

Commit

Permalink
Use a singleton for the DB connection
Browse files Browse the repository at this point in the history
  • Loading branch information
Vinnl committed Oct 31, 2024
1 parent 2a212cb commit e7a2b23
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 5 deletions.
7 changes: 5 additions & 2 deletions src/db/connect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
import knex from "knex";
import knexConfig from "./knexfile.js";

let connection: knex.Knex;
export default function createDbConnection(): knex.Knex {
/* c8 ignore start */
if (process.env.NODE_ENV === "development") {
Expand All @@ -15,9 +16,11 @@ export default function createDbConnection(): knex.Knex {
);
}

return (global as unknown as Record<string, knex.Knex>)[client];
connection ??= (global as unknown as Record<string, knex.Knex>)[client];
return connection;
}
/* c8 ignore stop */

return knex(knexConfig as knex.Knex.Config);
connection ??= knex(knexConfig as knex.Knex.Config);
return connection;
}
8 changes: 5 additions & 3 deletions src/scripts/cronjobs/monthlyActivityFree.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -4,21 +4,23 @@

import { SubscriberRow } from "knex/types/tables";
import { getFreeSubscribersWaitingForMonthlyEmail } from "../../db/tables/subscribers";
import { getLatestOnerepScanResults } from "../../db/tables/onerep_scans";
import { updateEmailPreferenceForSubscriber } from "../../db/tables/subscriber_email_preferences";
import { initEmail, sendEmail, closeEmailPool } from "../../utils/email";
import { renderEmail } from "../../emails/renderEmail";
import { MonthlyActivityFreeEmail } from "../../emails/templates/monthlyActivityFree/MonthlyActivityFreeEmail";
import { getCronjobL10n } from "../../app/functions/l10n/cronjobs";
import { sanitizeSubscriberRow } from "../../app/functions/server/sanitize";
import { getDashboardSummary } from "../../app/functions/server/dashboard";
import { getLatestOnerepScanResults } from "../../db/tables/onerep_scans";
import { getSubscriberBreaches } from "../../app/functions/server/getSubscriberBreaches";
import { refreshStoredScanResults } from "../../app/functions/server/refreshStoredScanResults";
import { getSignupLocaleCountry } from "../../emails/functions/getSignupLocaleCountry";
import { updateEmailPreferenceForSubscriber } from "../../db/tables/subscriber_email_preferences";
import createDbConnection from "../../db/connect";
import { logger } from "../../app/functions/server/logging";
import { getMonthlyActivityFreeUnsubscribeLink } from "../../app/functions/cronjobs/unsubscribeLinks";

void run();
await run();
await createDbConnection().destroy();

async function run() {
const batchSize = Number.parseInt(
Expand Down

0 comments on commit e7a2b23

Please sign in to comment.