index.js 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. 'use strict';
  2. const processFn = (fn, opts) => function () {
  3. const P = opts.promiseModule;
  4. const args = new Array(arguments.length);
  5. for (let i = 0; i < arguments.length; i++) {
  6. args[i] = arguments[i];
  7. }
  8. return new P((resolve, reject) => {
  9. if (opts.errorFirst) {
  10. args.push(function (err, result) {
  11. if (opts.multiArgs) {
  12. const results = new Array(arguments.length - 1);
  13. for (let i = 1; i < arguments.length; i++) {
  14. results[i - 1] = arguments[i];
  15. }
  16. if (err) {
  17. results.unshift(err);
  18. reject(results);
  19. } else {
  20. resolve(results);
  21. }
  22. } else if (err) {
  23. reject(err);
  24. } else {
  25. resolve(result);
  26. }
  27. });
  28. } else {
  29. args.push(function (result) {
  30. if (opts.multiArgs) {
  31. const results = new Array(arguments.length - 1);
  32. for (let i = 0; i < arguments.length; i++) {
  33. results[i] = arguments[i];
  34. }
  35. resolve(results);
  36. } else {
  37. resolve(result);
  38. }
  39. });
  40. }
  41. fn.apply(this, args);
  42. });
  43. };
  44. module.exports = (obj, opts) => {
  45. opts = Object.assign({
  46. exclude: [/.+(Sync|Stream)$/],
  47. errorFirst: true,
  48. promiseModule: Promise
  49. }, opts);
  50. const filter = key => {
  51. const match = pattern => typeof pattern === 'string' ? key === pattern : pattern.test(key);
  52. return opts.include ? opts.include.some(match) : !opts.exclude.some(match);
  53. };
  54. let ret;
  55. if (typeof obj === 'function') {
  56. ret = function () {
  57. if (opts.excludeMain) {
  58. return obj.apply(this, arguments);
  59. }
  60. return processFn(obj, opts).apply(this, arguments);
  61. };
  62. } else {
  63. ret = Object.create(Object.getPrototypeOf(obj));
  64. }
  65. for (const key in obj) { // eslint-disable-line guard-for-in
  66. const x = obj[key];
  67. ret[key] = typeof x === 'function' && filter(key) ? processFn(x, opts) : x;
  68. }
  69. return ret;
  70. };