From 027d610578ca42145d778db8523e78d43973082c Mon Sep 17 00:00:00 2001 From: yassinedorbozgithub Date: Mon, 16 Jun 2025 15:52:15 +0100 Subject: [PATCH] feat(api): enhance typing --- api/src/utils/test/utils.ts | 43 +++++++++++++++++++++++++++++-------- 1 file changed, 34 insertions(+), 9 deletions(-) diff --git a/api/src/utils/test/utils.ts b/api/src/utils/test/utils.ts index b68ee3e8..4dcc13a1 100644 --- a/api/src/utils/test/utils.ts +++ b/api/src/utils/test/utils.ts @@ -23,12 +23,36 @@ type TTypeOrToken = [ ...(new (...args: any[]) => any[]), ]; -type model = ModelDefinition | `${string}Model`; +type TModel = ModelDefinition | `${string}Model`; -interface buildTestingMocksProps extends ModuleMetadata { - models?: model[]; - autoInjectFrom?: ('all' | 'controllers' | 'providers')[]; -} +type ToUnionArray = (NonNullable extends (infer U)[] ? U : never)[]; + +type buildTestingMocksProps< + P extends ModuleMetadata['providers'] = ModuleMetadata['providers'], + C extends ModuleMetadata['controllers'] = ModuleMetadata['controllers'], +> = ModuleMetadata & { + models?: TModel[]; +} & ( + | { + providers: NonNullable

; + controllers: NonNullable; + autoInjectFrom?: 'all'[]; + } + | { + providers: NonNullable

; + controllers?: undefined; + autoInjectFrom?: 'providers'[]; + } + | { + controllers: NonNullable; + autoInjectFrom?: 'controllers'[]; + } + | { + providers?: never; + controllers?: never; + autoInjectFrom?: never; + } + ); const findInstances = async ( type: keyof TestingModule, @@ -133,7 +157,7 @@ const canInjectModels = (imports: buildTestingMocksProps['imports']): boolean => dynamicModule.module.name === 'MongooseModule', ) > -1; -const getModels = (models: model[]): ModelDefinition[] => +const getModels = (models: TModel[]): ModelDefinition[] => models.map((model) => typeof model === 'string' ? getModel(model, 'Model') : model, ); @@ -147,13 +171,14 @@ export const buildTestingMocks = async ({ ...rest }: buildTestingMocksProps) => { const nestedProviders: Provider[] = []; - const canAutoInjectFromAll = autoInjectFrom?.includes('all'); + const injectionFrom = autoInjectFrom as ToUnionArray; + const canAutoInjectFromAll = injectionFrom?.includes('all'); - if (canAutoInjectFromAll || autoInjectFrom?.includes('providers')) { + if (canAutoInjectFromAll || injectionFrom?.includes('providers')) { nestedProviders.push(...providers, ...getNestedDependencies(providers)); } - if (canAutoInjectFromAll || autoInjectFrom?.includes('controllers')) { + if (canAutoInjectFromAll || injectionFrom?.includes('controllers')) { nestedProviders.push(...controllers, ...getNestedDependencies(controllers)); }