69 lines
1.7 KiB
TypeScript
69 lines
1.7 KiB
TypeScript
import { Injectable } from '@nestjs/common';
|
|
import { ModelClass } from 'objection';
|
|
import { BaseModel } from './base.model';
|
|
import { DynamicModelFactory, ObjectMetadata } from './dynamic-model.factory';
|
|
|
|
/**
|
|
* Registry to store and retrieve dynamic models
|
|
* One registry per tenant
|
|
*/
|
|
@Injectable()
|
|
export class ModelRegistry {
|
|
private registry = new Map<string, ModelClass<BaseModel>>();
|
|
|
|
/**
|
|
* Register a model in the registry
|
|
*/
|
|
registerModel(apiName: string, modelClass: ModelClass<BaseModel>): void {
|
|
this.registry.set(apiName, modelClass);
|
|
}
|
|
|
|
/**
|
|
* Get a model from the registry
|
|
*/
|
|
getModel(apiName: string): ModelClass<BaseModel> {
|
|
const model = this.registry.get(apiName);
|
|
if (!model) {
|
|
throw new Error(`Model for ${apiName} not found in registry`);
|
|
}
|
|
return model;
|
|
}
|
|
|
|
/**
|
|
* Check if a model exists in the registry
|
|
*/
|
|
hasModel(apiName: string): boolean {
|
|
return this.registry.has(apiName);
|
|
}
|
|
|
|
/**
|
|
* Create and register a model from metadata
|
|
*/
|
|
createAndRegisterModel(
|
|
metadata: ObjectMetadata,
|
|
): ModelClass<BaseModel> {
|
|
// Create model with a getModel function that resolves from this registry
|
|
// Returns undefined if model not found (for models not yet registered)
|
|
const model = DynamicModelFactory.createModel(
|
|
metadata,
|
|
(apiName: string) => this.registry.get(apiName),
|
|
);
|
|
this.registerModel(metadata.apiName, model);
|
|
return model;
|
|
}
|
|
|
|
/**
|
|
* Get all registered model names
|
|
*/
|
|
getAllModelNames(): string[] {
|
|
return Array.from(this.registry.keys());
|
|
}
|
|
|
|
/**
|
|
* Clear the registry (useful for testing)
|
|
*/
|
|
clear(): void {
|
|
this.registry.clear();
|
|
}
|
|
}
|