@statezero/core
Version:
The type-safe frontend client for StateZero - connect directly to your backend models with zero boilerplate
64 lines (63 loc) • 2.45 kB
JavaScript
import { ModelStore } from '../stores/modelStore.js';
import { isNil } from 'lodash-es';
export class ModelStoreRegistry {
constructor() {
this._stores = new Map();
this.syncManager = () => { console.warn("SyncManager not set for ModelStoreRegistry"); };
}
clear() {
for (const modelClass of this._stores.keys()) {
this.syncManager.unfollowModel(this, modelClass);
}
this._stores = new Map();
}
setSyncManager(syncManager) {
this.syncManager = syncManager;
}
getStore(modelClass) {
if (!this._stores.has(modelClass)) {
// Create a new ModelStore on demand
const fetchModels = async ({ pks, modelClass }) => {
return await modelClass.objects.filter({
[`${modelClass.primaryKeyField}__in`]: pks
}).fetch().serialize();
};
this._stores.set(modelClass, new ModelStore(modelClass, fetchModels, null, null));
this.syncManager.followModel(this, modelClass);
}
return this._stores.get(modelClass);
}
// Get a single entity from the store
getEntity(modelClass, pk) {
// defensive checks for this nested func
if (isNil(modelClass) || isNil(pk))
return;
if (pk[modelClass.primaryKeyField])
throw new Error("getEntity should be called with a pk not an object");
// logic
const store = this.getStore(modelClass);
const renderedData = store.render([pk]);
return renderedData[0] || null;
}
// Add or update an entity ground truth in the store, not for operations!
setEntity(modelClass, pk, data) {
// defensive checks for this nested func
if (isNil(modelClass) || isNil(pk))
return;
if (pk[modelClass.primaryKeyField])
throw new Error("getEntity should be called with a pk not an object");
// logic
const store = this.getStore(modelClass);
store.addToGroundTruth([data]);
return data;
}
// Batch add or update entities in the store ground truth
setEntities(modelClass, entities) {
if (isNil(modelClass) || !entities?.length)
return;
const store = this.getStore(modelClass);
store.addToGroundTruth(entities);
}
}
// Export singleton instance
export const modelStoreRegistry = new ModelStoreRegistry();