ra-core
Version:
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
113 lines • 3.75 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.memoryStore = void 0;
/**
* Store using memory
*
* @example
*
* import { memoryStore } from 'react-admin';
*
* const App = () => (
* <Admin store={memoryStore()}>
* ...
* </Admin>
* );
*/
const memoryStore = (initialStorage = {}) => {
// Use a flat Map to store key-value pairs directly without treating dots as nested paths
let storage = new Map(Object.entries(initialStorage ?? {}));
const subscriptions = {};
let initialized = false;
let itemsToSetAfterInitialization = {};
const publish = (key, value) => {
Object.keys(subscriptions).forEach(id => {
if (!subscriptions[id])
return; // may happen if a component unmounts after a first subscriber was notified
if (subscriptions[id].key === key) {
subscriptions[id].callback(value);
}
});
};
return {
setup: () => {
storage = new Map(Object.entries(initialStorage));
// Because children might call setItem before the store is initialized,
// we store those calls parameters and apply them once the store is ready
if (Object.keys(itemsToSetAfterInitialization).length > 0) {
const items = Object.entries(itemsToSetAfterInitialization);
for (const [key, value] of items) {
storage.set(key, value);
publish(key, value);
}
itemsToSetAfterInitialization = {};
}
initialized = true;
},
teardown: () => {
storage.clear();
},
getItem(key, defaultValue) {
return storage.has(key)
? storage.get(key)
: defaultValue;
},
setItem(key, value) {
// Because children might call setItem before the store is initialized,
// we store those calls parameters and apply them once the store is ready
if (!initialized) {
itemsToSetAfterInitialization[key] = value;
return;
}
storage.set(key, value);
publish(key, value);
},
removeItem(key) {
storage.delete(key);
publish(key, undefined);
},
removeItems(keyPrefix) {
const keysToDelete = [];
storage.forEach((_, key) => {
if (key.startsWith(keyPrefix)) {
keysToDelete.push(key);
}
});
keysToDelete.forEach(key => {
storage.delete(key);
publish(key, undefined);
});
},
reset() {
const keysToDelete = [];
storage.forEach((_, key) => {
keysToDelete.push(key);
});
storage.clear();
keysToDelete.forEach(key => {
publish(key, undefined);
});
},
subscribe: (key, callback) => {
const id = Math.random().toString();
subscriptions[id] = {
key,
callback,
};
return () => {
delete subscriptions[id];
};
},
listItems: (keyPrefix) => {
return Array.from(storage.entries()).reduce((acc, [key, value]) => {
if (keyPrefix != null && !key.startsWith(keyPrefix)) {
return acc;
}
acc[key] = value;
return acc;
}, {});
},
};
};
exports.memoryStore = memoryStore;
//# sourceMappingURL=memoryStore.js.map