|
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
2 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
4 'use strict'; |
|
5 |
|
6 module.metadata = { |
|
7 "stability": "stable" |
|
8 }; |
|
9 |
|
10 const { search, remove, store } = require("./passwords/utils"); |
|
11 const { defer, delay } = require("./lang/functional"); |
|
12 |
|
13 /** |
|
14 * Utility function that returns `onComplete` and `onError` callbacks form the |
|
15 * given `options` objects. Also properties are removed from the passed |
|
16 * `options` objects. |
|
17 * @param {Object} options |
|
18 * Object that is passed to the exported functions of this module. |
|
19 * @returns {Function[]} |
|
20 * Array with two elements `onComplete` and `onError` functions. |
|
21 */ |
|
22 function getCallbacks(options) { |
|
23 let value = [ |
|
24 'onComplete' in options ? options.onComplete : null, |
|
25 'onError' in options ? defer(options.onError) : console.exception |
|
26 ]; |
|
27 |
|
28 delete options.onComplete; |
|
29 delete options.onError; |
|
30 |
|
31 return value; |
|
32 }; |
|
33 |
|
34 /** |
|
35 * Creates a wrapper function that tries to call `onComplete` with a return |
|
36 * value of the wrapped function or falls back to `onError` if wrapped function |
|
37 * throws an exception. |
|
38 */ |
|
39 function createWrapperMethod(wrapped) { |
|
40 return function (options) { |
|
41 let [ onComplete, onError ] = getCallbacks(options); |
|
42 try { |
|
43 let value = wrapped(options); |
|
44 if (onComplete) { |
|
45 delay(function() { |
|
46 try { |
|
47 onComplete(value); |
|
48 } catch (exception) { |
|
49 onError(exception); |
|
50 } |
|
51 }); |
|
52 } |
|
53 } catch (exception) { |
|
54 onError(exception); |
|
55 } |
|
56 }; |
|
57 } |
|
58 |
|
59 exports.search = createWrapperMethod(search); |
|
60 exports.store = createWrapperMethod(store); |
|
61 exports.remove = createWrapperMethod(remove); |