@toruslabs/broadcast-channel
Version:
A BroadcastChannel that works in New Browsers, Old Browsers, WebWorkers
36 lines (31 loc) • 1.25 kB
JavaScript
import * as indexedDb from './methods/indexed-db.js';
import * as localstorage from './methods/localstorage.js';
import * as native from './methods/native.js';
import * as server from './methods/server.js';
import * as simulate from './methods/simulate.js';
// order is important
const METHODS = [native,
// fastest
indexedDb, localstorage, server];
function chooseMethod(options) {
let chooseMethods = [].concat(options.methods || [], METHODS).filter(Boolean);
// directly chosen
if (options.type) {
if (options.type === "simulate") {
// only use simulate-method if directly chosen
return simulate;
}
const ret = chooseMethods.find(m => m.type === options.type);
if (!ret) throw new Error(`method-type ${options.type} not found`);else return ret;
}
/**
* if no webworker support is needed,
* remove idb from the list so that localstorage is been chosen
*/
if (!options.webWorkerSupport) {
chooseMethods = chooseMethods.filter(m => m.type !== "idb");
}
const useMethod = chooseMethods.find(method => method.canBeUsed(options));
if (!useMethod) throw new Error(`No useable method found in ${JSON.stringify(METHODS.map(m => m.type))}`);else return useMethod;
}
export { chooseMethod };