nucleux
Version:
Simple, atomic hub for all your React application's state management needs. No providers, no boilerplate, just state that works.
46 lines (45 loc) • 1.6 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.isAtom = exports.getStoreProxy = exports.generateStoreDefinition = void 0;
const nanoid_1 = require("nanoid");
const Atom_1 = require("./Atom");
function isAtom(obj) {
return obj != null && typeof obj === 'object' && 'value' in obj;
}
exports.isAtom = isAtom;
function isFunction(obj) {
return typeof obj === 'function';
}
function generateStoreDefinition(storeClass) {
return {
storeId: (0, nanoid_1.nanoid)(),
storeClass,
};
}
exports.generateStoreDefinition = generateStoreDefinition;
function getStoreProxy(storeInstance, isServerSnapshot = false) {
return new Proxy(storeInstance, {
get(_, prop) {
const key = prop.toString();
if (Object.prototype.hasOwnProperty.call(storeInstance, key)) {
const storeMember = storeInstance[key];
// Check for method first
if (isFunction(storeMember)) {
return storeMember.bind(storeInstance);
}
// Then check for atom
if (isAtom(storeMember) && storeMember instanceof Atom_1.Atom) {
return isServerSnapshot
? storeMember.initialValue
: storeMember.value;
}
}
return undefined;
},
set() {
console.warn('Cannot modify store values directly. Use store methods instead.');
return false;
},
});
}
exports.getStoreProxy = getStoreProxy;