UNPKG

@toruslabs/broadcast-channel

Version:

A BroadcastChannel that works in New Browsers, Old Browsers, WebWorkers

36 lines (32 loc) 1.26 kB
'use strict'; var indexedDb = require('./methods/indexed-db.js'); var localstorage = require('./methods/localstorage.js'); var native = require('./methods/native.js'); var server = require('./methods/server.js'); var simulate = require('./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; } exports.chooseMethod = chooseMethod;