Source: node_modules/mongodb-client-encryption/lib/common.js

  1. 'use strict';
  2. /**
  3. * @ignore
  4. * Helper function for logging. Enabled by setting the environment flag MONGODB_CRYPT_DEBUG.
  5. * @param {*} msg Anything you want to be logged.
  6. */
  7. function debug(msg) {
  8. if (process.env.MONGODB_CRYPT_DEBUG) {
  9. console.log(msg);
  10. }
  11. }
  12. /**
  13. * @ignore
  14. * Gets the database portion of a namespace string
  15. * @param {string} ns A string in the format of a namespace (database.collection)
  16. * @returns {string} The database portion of the namespace
  17. */
  18. function databaseNamespace(ns) {
  19. return ns.split('.')[0];
  20. }
  21. /**
  22. * @ignore
  23. * Gets the colleciton portion of a namespace string
  24. * @param {string} ns A string in the format of a namespace (database.collection)
  25. * @returns {string} The collection portion of the namespace
  26. */
  27. function collectionNamespace(ns) {
  28. return ns
  29. .split('.')
  30. .slice(1)
  31. .join('.');
  32. }
  33. /**
  34. * @class
  35. * An error indicating that something went wrong specifically with MongoDB Client Encryption
  36. */
  37. class MongoCryptError extends Error {
  38. constructor(message) {
  39. super(message);
  40. this.name = 'MongoCryptError';
  41. Error.captureStackTrace(this, this.constructor);
  42. }
  43. }
  44. /**
  45. * @ignore
  46. * A helper function. Invokes a function that takes a callback as the final
  47. * parameter. If a callback is supplied, then it is passed to the function.
  48. * If not, a Promise is returned that resolves/rejects with the result of the
  49. * callback
  50. * @param {Function} [callback] an optional callback.
  51. * @param {Function} fn A function that takes a callback
  52. * @returns {Promise|void} Returns nothing if a callback is supplied, else returns a Promise.
  53. */
  54. function promiseOrCallback(callback, fn) {
  55. if (typeof callback === 'function') {
  56. fn(function(err) {
  57. if (err != null) {
  58. try {
  59. callback(err);
  60. } catch (error) {
  61. return process.nextTick(() => {
  62. throw error;
  63. });
  64. }
  65. return;
  66. }
  67. callback.apply(this, arguments);
  68. });
  69. return;
  70. }
  71. return new Promise((resolve, reject) => {
  72. fn(function(err, res) {
  73. if (err != null) {
  74. return reject(err);
  75. }
  76. if (arguments.length > 2) {
  77. return resolve(Array.prototype.slice.call(arguments, 1));
  78. }
  79. resolve(res);
  80. });
  81. });
  82. }
  83. module.exports = {
  84. debug,
  85. databaseNamespace,
  86. collectionNamespace,
  87. MongoCryptError,
  88. promiseOrCallback
  89. };