Add lib/options module for typed/easier options storage access

This commit is contained in:
hensm
2019-05-17 14:53:43 +01:00
parent a97e14cb31
commit 964f54a06b
4 changed files with 93 additions and 57 deletions

54
ext/src/lib/options.ts Normal file
View File

@@ -0,0 +1,54 @@
"use strict";
import { Options } from "../defaultOptions";
/**
* Fetches `options` key from storage and returns it as
* Options interface type.
*/
async function getAll (): Promise<Options> {
const { options }: { options: Options } =
await browser.storage.sync.get("options");
return options;
}
/**
* Takes Options object and sets to `options` storage key.
* Returns storage promise.
*/
async function setAll (options: Options): Promise<void> {
return browser.storage.sync.set({ options });
}
/**
* Gets specific option from storage and returns it as its
* type from Options interface type.
*/
async function get<T extends keyof Options> (name: T): Promise<Options[T]> {
const options = await getAll();
if (options.hasOwnProperty(name)) {
return options[name];
}
}
/**
* Sets specific option to storage. Returns storage
* promise.
*/
async function set<T extends keyof Options> (
name: T
, value: Options[T]): Promise<void> {
const options = await getAll();
options[name] = value;
return setAll(options);
}
export default {
get, getAll
, set, setAll
}