UNPKG

@statezero/core

Version:

The type-safe frontend client for StateZero - connect directly to your backend models with zero boilerplate

63 lines (62 loc) 2.94 kB
import { configInstance } from '../../config.js'; // Cache for model classes to avoid repeated imports const modelClassCache = {}; /** * Get a model class by name, loading it from the correct folder structure * * @param {string} modelName - The model name (e.g. 'app.model') * @param {string} configKey - Optional config key override (defaults to Model.configKey) * @returns {Function|null} - The model class or null if not found */ export function getModelClass(modelName, configKey = this.configKey || 'default') { // Check cache first const cacheKey = `${configKey}:${modelName}`; if (modelClassCache[cacheKey]) { return modelClassCache[cacheKey]; } try { const config = configInstance.getConfig(); const backendConfig = config.backendConfigs[configKey]; if (!backendConfig) { throw new Error(`No backend configuration found for key: ${configKey}`); } const baseDir = backendConfig.GENERATED_TYPES_DIR.replace(/\/$/, ''); // Split the model name into parts (e.g., 'app.model' -> ['app', 'model']) const parts = modelName.split('.'); // The last part is the actual model name const modelClassName = parts[parts.length - 1]; // The path is all parts except the last one, joined by '/' const pathParts = parts.slice(0, parts.length - 1); const path = pathParts.length > 0 ? `/${pathParts.join('/')}` : ''; // Construct the full path to the module const modulePath = `${baseDir}${path}/${modelClassName}.js`; // Load the module using require (in Node.js) or dynamic import (in browser) // This implementation uses dynamic import as it's more common in modern JS environments let ModelClass; try { // For Node.js environments, you might use require // ModelClass = require(modulePath).default; // For browser/ES modules using dynamic import // Note: This is a synchronous approach to handle dynamic imports // In a real implementation, this would need to be async or preloaded // Since we can't do a true dynamic import synchronously, here we're assuming // there's a global registry that was populated during build/load time const allModels = window.__MODEL_REGISTRY__ || {}; ModelClass = allModels[modulePath]; if (!ModelClass) { throw new Error(`Model not found in registry: ${modulePath}`); } } catch (importError) { console.error(`Error loading model class from ${modulePath}:`, importError); return null; } // Cache the model class modelClassCache[cacheKey] = ModelClass; return ModelClass; } catch (error) { console.error(`Error getting model class for ${modelName}:`, error); return null; } }