All files / src/web stored-json.js

100% Statements 11/11
100% Branches 6/6
100% Functions 2/2
100% Lines 9/9

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34                4129x 3873x 3873x   8x 8x                         3046x 2986x 2986x   4x      
/**
 * The value kept as JSON under `key`, or null when there is none, there is no storage, or it cannot be read; a failure
 * is logged as reading `what`.
 * @param {(() => Storage) | null} storage
 * @param {string} key
 * @param {string} what
 */
export function readStored(storage, key, what) {
    if (!storage) return null;
    try {
        return JSON.parse(storage().getItem(key) ?? "null");
    } catch (error) {
        console.warn(`Could not read ${what}: ${error}`);
        return null;
    }
}
 
/**
 * Keeps `value` as JSON under `key`, if there is storage; a failure, such as a full or blocked storage, is logged as
 * saving `what`.
 * @param {(() => Storage) | null} storage
 * @param {string} key
 * @param {*} value
 * @param {string} what
 */
export function writeStored(storage, key, value, what) {
    if (!storage) return;
    try {
        storage().setItem(key, JSON.stringify(value));
    } catch (error) {
        console.warn(`Could not save ${what}: ${error}`);
    }
}