michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: 'use strict'; michael@0: michael@0: module.metadata = { michael@0: "stability": "stable" michael@0: }; michael@0: michael@0: const { search, remove, store } = require("./passwords/utils"); michael@0: const { defer, delay } = require("./lang/functional"); michael@0: michael@0: /** michael@0: * Utility function that returns `onComplete` and `onError` callbacks form the michael@0: * given `options` objects. Also properties are removed from the passed michael@0: * `options` objects. michael@0: * @param {Object} options michael@0: * Object that is passed to the exported functions of this module. michael@0: * @returns {Function[]} michael@0: * Array with two elements `onComplete` and `onError` functions. michael@0: */ michael@0: function getCallbacks(options) { michael@0: let value = [ michael@0: 'onComplete' in options ? options.onComplete : null, michael@0: 'onError' in options ? defer(options.onError) : console.exception michael@0: ]; michael@0: michael@0: delete options.onComplete; michael@0: delete options.onError; michael@0: michael@0: return value; michael@0: }; michael@0: michael@0: /** michael@0: * Creates a wrapper function that tries to call `onComplete` with a return michael@0: * value of the wrapped function or falls back to `onError` if wrapped function michael@0: * throws an exception. michael@0: */ michael@0: function createWrapperMethod(wrapped) { michael@0: return function (options) { michael@0: let [ onComplete, onError ] = getCallbacks(options); michael@0: try { michael@0: let value = wrapped(options); michael@0: if (onComplete) { michael@0: delay(function() { michael@0: try { michael@0: onComplete(value); michael@0: } catch (exception) { michael@0: onError(exception); michael@0: } michael@0: }); michael@0: } michael@0: } catch (exception) { michael@0: onError(exception); michael@0: } michael@0: }; michael@0: } michael@0: michael@0: exports.search = createWrapperMethod(search); michael@0: exports.store = createWrapperMethod(store); michael@0: exports.remove = createWrapperMethod(remove);