ra-core
Version:
Core components of react-admin, a frontend Framework for building admin applications on top of REST services, using ES6, React
106 lines • 3.76 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>
* );
*/
var memoryStore = function (initialStorage) {
if (initialStorage === void 0) { initialStorage = {}; }
// Use a flat Map to store key-value pairs directly without treating dots as nested paths
var storage = new Map(Object.entries(initialStorage !== null && initialStorage !== void 0 ? initialStorage : {}));
var subscriptions = {};
var initialized = false;
var itemsToSetAfterInitialization = {};
var publish = function (key, value) {
Object.keys(subscriptions).forEach(function (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: function () {
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) {
var items = Object.entries(itemsToSetAfterInitialization);
for (var _i = 0, items_1 = items; _i < items_1.length; _i++) {
var _a = items_1[_i], key = _a[0], value = _a[1];
storage.set(key, value);
publish(key, value);
}
itemsToSetAfterInitialization = {};
}
initialized = true;
},
teardown: function () {
storage.clear();
},
getItem: function (key, defaultValue) {
return storage.has(key)
? storage.get(key)
: defaultValue;
},
setItem: function (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: function (key) {
storage.delete(key);
publish(key, undefined);
},
removeItems: function (keyPrefix) {
var keysToDelete = [];
storage.forEach(function (_, key) {
if (key.startsWith(keyPrefix)) {
keysToDelete.push(key);
}
});
keysToDelete.forEach(function (key) {
storage.delete(key);
publish(key, undefined);
});
},
reset: function () {
var keysToDelete = [];
storage.forEach(function (_, key) {
keysToDelete.push(key);
});
storage.clear();
keysToDelete.forEach(function (key) {
publish(key, undefined);
});
},
subscribe: function (key, callback) {
var id = Math.random().toString();
subscriptions[id] = {
key: key,
callback: callback,
};
return function () {
delete subscriptions[id];
};
},
};
};
exports.memoryStore = memoryStore;
//# sourceMappingURL=memoryStore.js.map