UNPKG

@vitorluizc/persistence

Version:

Persistence provides a pretty easy API to handle Storage's implementations.

44 lines (39 loc) 1.46 kB
/** * Creates a Persistence, an object to easily get and set values to a persistent * storage like `SessionStorage` or `LocalStorage`. * @example ```js * const state = createPersistence('state@name', { * placeholder: 'Unknown' * }); * * // This creates a persistent field's value. * const el = document.querySelector('input[name="name"]'); * el.value = state.get(); * el.addEventListener('input', () => state.set(el.value));``` * @param name - Persistence uses the name as storage's key. * @param options - Options to set timeout, storage and placeholder value. */ var createPersistence = function (name, options) { if ( options === void 0 ) options = {}; var storage = options.storage; if ( storage === void 0 ) storage = window.localStorage; var timeout = options.timeout; var placeholder = options.placeholder; var isExpired = function (updatedAt) { return timeout !== undefined && Date.now() > updatedAt + timeout; }; return { set: function (value) { var state = JSON.stringify({ value: value, updatedAt: Date.now() }); storage.setItem(name, state); }, get: function () { var state = storage.getItem(name); if (state === null) { return placeholder; } var record = JSON.parse(state); return isExpired(record.updatedAt) ? placeholder : record.value; }, delete: function () { return storage.removeItem(name); } }; }; export default createPersistence;