All files / server/src/db mongodb.ts

78.94% Statements 15/19
0% Branches 0/2
100% Functions 4/4
78.94% Lines 15/19

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68        60x       355x   355x       355x 355x           355x             355x 355x   2272x                           355x         60x 242x 242x               242x     60x        
import mongoose from "mongoose";
import { config } from "shared/config";
import { logger } from "server/utils/logger";
 
const connectToDb = async (
  dbConnString: string = config.server().dbConnString,
  dbName: string = config.server().dbName,
): Promise<void> => {
  logger.info(`MongoDB: Connecting to DB ${dbName}`);
 
  const options = {
    dbName,
  };
 
  try {
    await mongoose.connect(dbConnString, options);
  } catch (error) {
    // eslint-disable-next-line no-restricted-syntax -- Server startup
    throw new Error("MongoDB: Error connecting to DB", { cause: error });
  }
 
  logger.info("MongoDB: Connection successful");
 
  // Build schema indexes for the database just connected to. Mongoose's
  // automatic index build runs once per model per process, so a later
  // connection to a different database (every integration test gets its own)
  // would otherwise silently skip them - including the unique keys that keep
  // single-document collections single
  try {
    await Promise.all(
      Object.values(mongoose.models).map(async (model) => {
        await model.createIndexes();
      }),
    );
  } catch (error) {
    // A unique index fails to build when the data already violates it, e.g. a
    // database that collected duplicate settings documents before the unique
    // key existed. Name the cause: the fix is removing the duplicates
    // eslint-disable-next-line no-restricted-syntax -- Server startup
    throw new Error(
      "MongoDB: Error building indexes, database may hold data that violates them",
      { cause: error },
    );
  }
 
  mongoose.connection.on("error", (error) => {
    logger.error(new Error("MongoDB: Connection error", { cause: error }));
  });
};
 
const gracefulExit = async (): Promise<void> => {
  try {
    await mongoose.connection.close();
  } catch (error) {
    // eslint-disable-next-line no-restricted-syntax -- Server startup
    throw new Error("MongoDB: Error shutting down db connection", {
      cause: error,
    });
  }
 
  logger.info("MongoDB connection closed");
};
 
export const db = {
  connectToDb,
  gracefulExit,
};