/** * This file is part of Haketilo. * * Function: Storage manager. * * Copyright (C) 2021 Wojtek Kosior * Redistribution terms are gathered in the `copyright' file. */ /* * IMPORTS_START * IMPORT raw_storage * IMPORT TYPE_NAME * IMPORT list_prefixes * IMPORT make_lock * IMPORT lock * IMPORT unlock * IMPORT make_once * IMPORT browser * IMPORT observables * IMPORTS_END */ var exports = {}; /* A special case of persisted variable is one that contains list of items. */ async function get_list_var(name) { let list = await raw_storage.get_var(name); return list === undefined ? [] : list; } /* We maintain in-memory copies of some stored lists. */ async function list(prefix) { let name = TYPE_NAME[prefix] + "s"; /* Make plural. */ let map = new Map(); for (let item of await get_list_var(name)) map.set(item, await raw_storage.get(prefix + item)); return {map, prefix, name, observable: observables.make(), lock: make_lock()}; } var list_by_prefix = {}; async function init() { for (let prefix of list_prefixes) list_by_prefix[prefix] = await list(prefix); return exports; } /* * Facilitate listening to changes */ exports.add_change_listener = function (cb, prefixes=list_prefixes) { if (typeof(prefixes) === "string") prefixes = [prefixes]; for (let prefix of prefixes) observables.subscribe(list_by_prefix[prefix].observable, cb); } exports.remove_change_listener = function (cb, prefixes=list_prefixes) { if (typeof(prefixes) === "string") prefixes = [prefixes]; for (let prefix of prefixes) observ