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.19 kB
JavaScript
/**
* Store using memory
*
* @example
*
* import { memoryStore } from 'react-admin';
*
* const App = () => (
* <Admin store={memoryStore()}>
* ...
* </Admin>
* );
*/
export 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(flatten(initialStorage)));
var subscriptions = {};
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 () { },
teardown: function () {
storage.clear();
},
getItem: function (key, defaultValue) {
return storage.has(key)
? storage.get(key)
: defaultValue;
},
setItem: function (key, value) {
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];
};
},
};
};
// taken from https://stackoverflow.com/a/19101235/1333479
var flatten = function (data) {
var result = {};
function doFlatten(current, prop) {
if (Object(current) !== current) {
// scalar value
result[prop] = current;
}
else if (Array.isArray(current)) {
// array
result[prop] = current;
}
else {
// object
var isEmpty = true;
for (var p in current) {
isEmpty = false;
doFlatten(current[p], prop ? prop + '.' + p : p);
}
if (isEmpty && prop)
result[prop] = {};
}
}
doFlatten(data, '');
return result;
};
//# sourceMappingURL=memoryStore.js.map