addon-sdk/source/lib/sdk/passwords.js

changeset 0
6474c204b198
     1.1 --- /dev/null	Thu Jan 01 00:00:00 1970 +0000
     1.2 +++ b/addon-sdk/source/lib/sdk/passwords.js	Wed Dec 31 06:09:35 2014 +0100
     1.3 @@ -0,0 +1,61 @@
     1.4 +/* This Source Code Form is subject to the terms of the Mozilla Public
     1.5 + * License, v. 2.0. If a copy of the MPL was not distributed with this
     1.6 + * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
     1.7 +'use strict';
     1.8 +
     1.9 +module.metadata = {
    1.10 +  "stability": "stable"
    1.11 +};
    1.12 +
    1.13 +const { search, remove, store } = require("./passwords/utils");
    1.14 +const { defer, delay } = require("./lang/functional");
    1.15 +
    1.16 +/**
    1.17 + * Utility function that returns `onComplete` and `onError` callbacks form the
    1.18 + * given `options` objects. Also properties are removed from the passed
    1.19 + * `options` objects.
    1.20 + * @param {Object} options
    1.21 + *    Object that is passed to the exported functions of this module.
    1.22 + * @returns {Function[]}
    1.23 + *    Array with two elements `onComplete` and `onError` functions.
    1.24 + */
    1.25 +function getCallbacks(options) {
    1.26 +  let value = [
    1.27 +    'onComplete' in options ? options.onComplete : null,
    1.28 +    'onError' in options ? defer(options.onError) : console.exception
    1.29 +  ];
    1.30 +
    1.31 +  delete options.onComplete;
    1.32 +  delete options.onError;
    1.33 +
    1.34 +  return value;
    1.35 +};
    1.36 +
    1.37 +/**
    1.38 + * Creates a wrapper function that tries to call `onComplete` with a return
    1.39 + * value of the wrapped function or falls back to `onError` if wrapped function
    1.40 + * throws an exception.
    1.41 + */
    1.42 +function createWrapperMethod(wrapped) {
    1.43 +  return function (options) {
    1.44 +    let [ onComplete, onError ] = getCallbacks(options);
    1.45 +    try {
    1.46 +      let value = wrapped(options);
    1.47 +      if (onComplete) {
    1.48 +        delay(function() {
    1.49 +          try {
    1.50 +            onComplete(value);
    1.51 +          } catch (exception) {
    1.52 +            onError(exception);
    1.53 +          }
    1.54 +        });
    1.55 +      }
    1.56 +    } catch (exception) {
    1.57 +      onError(exception);
    1.58 +    }
    1.59 +  };
    1.60 +}
    1.61 +
    1.62 +exports.search = createWrapperMethod(search);
    1.63 +exports.store = createWrapperMethod(store);
    1.64 +exports.remove = createWrapperMethod(remove);

mercurial