All files / server/src/features/serial serialRepository.ts

80% Statements 36/45
80% Branches 8/10
100% Functions 5/5
79.06% Lines 34/43

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 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102                            40x 288x 288x 288x 288x                 40x     29x   29x 38x 38x   38x 38x       38x 2x 2x   36x   36x 36x         29x 29x 29x       29x 36x 36x               36x     29x                 40x       48x 48x               48x 40x 40x   32x 8x    
import generator from "generate-serial-number";
import { logger } from "server/utils/logger";
import {
  SerialModel,
  SerialSchemaDb,
} from "server/features/serial/serialSchema";
import { Serial } from "server/types/serialTypes";
import {
  Result,
  makeErrorResult,
  makeSuccessResult,
} from "shared/utils/result";
import { MongoDbError } from "shared/types/api/errors";
 
export const removeSerials = async (): Promise<Result<void, MongoDbError>> => {
  logger.info("MongoDB: remove ALL serials from db");
  try {
    await SerialModel.deleteMany({});
    return makeSuccessResult();
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error removing serials", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
export const saveSerials = async (
  count: number,
): Promise<Result<Serial[], MongoDbError>> => {
  const serials: Serial[] = [];
  // create serials
  for (let i = 1; i <= count; i += 1) {
    const serial = generator.generate(10);
    const rawSerials = serials.map((s) => s.serial);
 
    const findSerialResult = await findSerial(serial);
    Iif (!findSerialResult.ok) {
      return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
    }
 
    if (findSerialResult.value || rawSerials.includes(serial)) {
      i -= 1;
      continue;
    }
    serials.push(new SerialModel({ serial }));
 
    const addDashesRegex = /(.{3})(?=.)/g;
    logger.info(
      `MongoDB: Created new serial: ${serial.replaceAll(addDashesRegex, "$1-")}`,
    );
  }
 
  try {
    const response = await SerialModel.create(serials);
    logger.info(
      `MongoDB: Serials data saved. (${serials.length} serials saved)`,
    );
 
    const results = response.flatMap((serial) => {
      const result = SerialSchemaDb.safeParse(serial);
      Iif (!result.success) {
        logger.error(
          new Error(
            `Error validating saveSerials DB value: ${JSON.stringify(result.error)}`,
          ),
        );
        return [];
      }
      return result.data;
    });
 
    return makeSuccessResult(results);
  } catch (error) {
    logger.error(
      new Error("MongoDB: Error saving serials data", { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
};
 
export const findSerial = async (
  serial: string,
): Promise<Result<boolean, MongoDbError>> => {
  let response;
  try {
    response = await SerialModel.findOne({ serial }).lean();
  } catch (error) {
    logger.error(
      new Error(`MongoDB: Error finding serial ${serial}`, { cause: error }),
    );
    return makeErrorResult(MongoDbError.UNKNOWN_ERROR);
  }
 
  if (!response) {
    logger.debug(`MongoDB: Serial ${serial} not found`);
    return makeSuccessResult(false);
  }
  logger.debug(`MongoDB: Found serial ${serial}`);
  return makeSuccessResult(true);
};