passwords.js 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. module.metadata = {
  6. "stability": "stable"
  7. };
  8. const { search, remove, store } = require("./passwords/utils");
  9. const { defer, delay } = require("./lang/functional");
  10. /**
  11. * Utility function that returns `onComplete` and `onError` callbacks form the
  12. * given `options` objects. Also properties are removed from the passed
  13. * `options` objects.
  14. * @param {Object} options
  15. * Object that is passed to the exported functions of this module.
  16. * @returns {Function[]}
  17. * Array with two elements `onComplete` and `onError` functions.
  18. */
  19. function getCallbacks(options) {
  20. let value = [
  21. 'onComplete' in options ? options.onComplete : null,
  22. 'onError' in options ? defer(options.onError) : console.exception
  23. ];
  24. delete options.onComplete;
  25. delete options.onError;
  26. return value;
  27. };
  28. /**
  29. * Creates a wrapper function that tries to call `onComplete` with a return
  30. * value of the wrapped function or falls back to `onError` if wrapped function
  31. * throws an exception.
  32. */
  33. function createWrapperMethod(wrapped) {
  34. return function (options) {
  35. let [ onComplete, onError ] = getCallbacks(options);
  36. try {
  37. let value = wrapped(options);
  38. if (onComplete) {
  39. delay(function() {
  40. try {
  41. onComplete(value);
  42. } catch (exception) {
  43. onError(exception);
  44. }
  45. });
  46. }
  47. } catch (exception) {
  48. onError(exception);
  49. }
  50. };
  51. }
  52. exports.search = createWrapperMethod(search);
  53. exports.store = createWrapperMethod(store);
  54. exports.remove = createWrapperMethod(remove);