import { type EntityManager, type EntityRepository, MikroORM } from '@mikro-orm/postgresql'; import { Inject, Injectable, Logger } from '@nestjs/common'; import type { Constructor } from '@wener/utils'; import { Resolver } from 'type-graphql'; import type { StandardBaseEntity } from '../../entity'; import { EntityBaseService } from '../../entity/service'; import type { BaseObject } from '../BaseObject'; import { getObjectName } from '../getObjectName'; import type { EntityClass, ObjectClass } from '../types'; import { createListPayload } from './createListPayload'; import type { PageResponse } from './types'; export interface BaseEntityResolver> { readonly EntityType: EntityClass; readonly ObjectType: ObjectClass; readonly em: EntityManager; readonly repo: EntityRepository; readonly svc: SVC; } type BaseEntityResolverStatic> = { ObjectType: Constructor; ListPayloadType: Constructor>; EntityType: EntityClass; ServiceType?: Constructor; ObjectName: string; }; export type BaseEntityResolverConstructor< O = BaseObject, E extends StandardBaseEntity = StandardBaseEntity, SVC extends EntityBaseService = EntityBaseService, > = Constructor> & BaseEntityResolverStatic; export function createBaseEntityResolver< O extends object, E extends StandardBaseEntity, SVC extends EntityBaseService, >({ ObjectType, EntityType, ServiceType, ListPayloadType, }: { ObjectType: Constructor; EntityType: Constructor; // InputType?: Constructor; ListPayloadType?: Constructor>; ServiceType?: Constructor; }): BaseEntityResolverConstructor { @Injectable() @Resolver(ObjectType) class BaseEntityResolver { protected readonly log = new Logger(this.constructor.name); static ObjectName = getObjectName(ObjectType); static EntityType: Constructor = EntityType; static ObjectType: Constructor = ObjectType; static ServiceType?: Constructor = ServiceType; static ListPayloadType: Constructor> = ListPayloadType || createListPayload(ObjectType); readonly EntityType: EntityClass = EntityType; readonly ObjectType: ObjectClass = ObjectType; readonly em: EntityManager; readonly repo: EntityRepository; protected _svc?: SVC; constructor(@Inject(MikroORM) protected readonly orm: MikroORM) { this.EntityType = EntityType; this.ObjectType = ObjectType; this.em = orm.em; this.repo = this.em.getRepository(this.EntityType); } get svc(): SVC { return (this._svc ??= EntityBaseService.requireService(this.EntityType) as unknown as SVC); } } return BaseEntityResolver; }