74 lines
2.0 KiB
TypeScript
74 lines
2.0 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);
|
|
const lowerKey = apiName.toLowerCase();
|
|
if (lowerKey !== apiName && !this.registry.has(lowerKey)) {
|
|
this.registry.set(lowerKey, modelClass);
|
|
}
|
|
}
|
|
|
|
/**
|
|
* Get a model from the registry
|
|
*/
|
|
getModel(apiName: string): ModelClass<BaseModel> {
|
|
const model = this.registry.get(apiName) || this.registry.get(apiName.toLowerCase());
|
|
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) || this.registry.has(apiName.toLowerCase());
|
|
}
|
|
|
|
/**
|
|
* 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.registry.get(apiName.toLowerCase()),
|
|
);
|
|
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();
|
|
}
|
|
}
|