utils.js 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. "use strict";
  2. Object.defineProperty(exports, "__esModule", { value: true });
  3. exports.bindAll = void 0;
  4. exports.toString = toString;
  5. exports.runAllChains = runAllChains;
  6. const bindAll = (object) => {
  7. const protoKeys = Object.getOwnPropertyNames(Object.getPrototypeOf(object));
  8. protoKeys.forEach(key => {
  9. const maybeFn = object[key];
  10. if (typeof maybeFn === 'function' && key !== 'constructor') {
  11. object[key] = maybeFn.bind(object);
  12. }
  13. });
  14. return object;
  15. };
  16. exports.bindAll = bindAll;
  17. function toString(value) {
  18. if (value instanceof Date) {
  19. return value.toISOString();
  20. }
  21. else if (value && typeof value === 'object' && value.toString) {
  22. if (typeof value.toString !== 'function') {
  23. return Object.getPrototypeOf(value).toString.call(value);
  24. }
  25. return value.toString();
  26. }
  27. else if (value == null || (isNaN(value) && !value.length)) {
  28. return '';
  29. }
  30. return String(value);
  31. }
  32. /**
  33. * Runs all validation chains, and returns their results.
  34. *
  35. * If one of them has a request-level bail set, the previous chains will be awaited on so that
  36. * results are not skewed, which can be slow.
  37. * If this same chain also contains errors, no further chains are run.
  38. */
  39. async function runAllChains(req, chains, runOpts) {
  40. const promises = [];
  41. for (const chain of chains) {
  42. const bails = chain.builder.build().bail;
  43. if (bails) {
  44. await Promise.all(promises);
  45. }
  46. const resultPromise = chain.run(req, runOpts);
  47. promises.push(resultPromise);
  48. if (bails) {
  49. const result = await resultPromise;
  50. if (!result.isEmpty()) {
  51. break;
  52. }
  53. }
  54. }
  55. return Promise.all(promises);
  56. }