feat(backend): Mechanisme geïmplementeerd om makkelijk repositories te verkrijgen.

This commit is contained in:
Gerald Schmittinger 2025-02-25 00:39:24 +01:00
parent 374de3b21a
commit b730be375c
4 changed files with 26 additions and 11 deletions

View file

@ -0,0 +1,16 @@
import {AnyEntity, EntityName, EntityRepository} from "@mikro-orm/core";
import {forkEntityManager} from "../orm";
import {StudentRepository} from "./users/student-repository";
import {Student} from "../entities/users/student.entity";
function repositoryGetter<T extends AnyEntity, R extends EntityRepository<T>>(entity: EntityName<T>): () => R {
let cachedRepo: R | undefined;
return (): R => {
if (!cachedRepo) {
cachedRepo = forkEntityManager().getRepository(entity) as R;
}
return cachedRepo;
}
}
export const getStudentRepository = repositoryGetter<Student, StudentRepository>(Student);

View file

@ -1,4 +1,4 @@
import {AnyEntity, EntityName, EntityRepository, MikroORM} from '@mikro-orm/core';
import { EntityManager, MikroORM} from '@mikro-orm/core';
import config from './mikro-orm.config.js';
import {EnvVars, getEnvVar} from "./util/envvars";
@ -17,10 +17,9 @@ export async function initORM(testingMode: boolean = false) {
}
}
}
export function getRepository<T extends AnyEntity>(entityName: EntityName<T>): EntityRepository<T> {
if (orm === undefined) {
throw new Error("ORM is not initialized yet");
export function forkEntityManager(): EntityManager {
if (!orm) {
throw Error("Accessing the Entity Manager before the ORM is fully initialized.")
}
return orm.em.fork().getRepository(entityName);
return orm.em.fork();
}

View file

@ -1,8 +1,8 @@
import {initializeTests} from "../testutils"
import {setupTestApp} from "../setup-tests"
import {Student} from "../../src/entities/users/student.entity";
import {describe, it, expect, beforeAll} from "vitest";
import {getRepository} from "../../src/orm";
import {StudentRepository} from "../../src/data/users/student-repository";
import {getStudentRepository} from "../../src/data/repositories";
const username = "teststudent";
const firstName = "John";
@ -11,8 +11,8 @@ describe("StudentRepository", () => {
let studentRepository: StudentRepository;
beforeAll(async () => {
await initializeTests()
studentRepository = getRepository(Student) as StudentRepository;
setupTestApp();
studentRepository = getStudentRepository();
});
it("should return the queried student after he was added", async () => {

View file

@ -1,7 +1,7 @@
import {initORM} from "../src/orm";
import dotenv from "dotenv";
export async function initializeTests() {
export async function setupTestApp() {
dotenv.config({path: ".env.test"});
await initORM(true);
}