validators.js 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. 'use strict';
  2. // This file is a proxy of the original file located at:
  3. // https://github.com/nodejs/node/blob/main/lib/internal/validators.js
  4. // Every addition or modification to this file must be evaluated
  5. // during the PR review.
  6. const {
  7. ArrayIsArray,
  8. ArrayPrototypeIncludes,
  9. ArrayPrototypeJoin,
  10. } = require('./primordials');
  11. const {
  12. codes: {
  13. ERR_INVALID_ARG_TYPE
  14. }
  15. } = require('./errors');
  16. function validateString(value, name) {
  17. if (typeof value !== 'string') {
  18. throw new ERR_INVALID_ARG_TYPE(name, 'String', value);
  19. }
  20. }
  21. function validateUnion(value, name, union) {
  22. if (!ArrayPrototypeIncludes(union, value)) {
  23. throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value);
  24. }
  25. }
  26. function validateBoolean(value, name) {
  27. if (typeof value !== 'boolean') {
  28. throw new ERR_INVALID_ARG_TYPE(name, 'Boolean', value);
  29. }
  30. }
  31. function validateArray(value, name) {
  32. if (!ArrayIsArray(value)) {
  33. throw new ERR_INVALID_ARG_TYPE(name, 'Array', value);
  34. }
  35. }
  36. function validateStringArray(value, name) {
  37. validateArray(value, name);
  38. for (let i = 0; i < value.length; i++) {
  39. validateString(value[i], `${name}[${i}]`);
  40. }
  41. }
  42. function validateBooleanArray(value, name) {
  43. validateArray(value, name);
  44. for (let i = 0; i < value.length; i++) {
  45. validateBoolean(value[i], `${name}[${i}]`);
  46. }
  47. }
  48. /**
  49. * @param {unknown} value
  50. * @param {string} name
  51. * @param {{
  52. * allowArray?: boolean,
  53. * allowFunction?: boolean,
  54. * nullable?: boolean
  55. * }} [options]
  56. */
  57. function validateObject(value, name, options) {
  58. const useDefaultOptions = options == null;
  59. const allowArray = useDefaultOptions ? false : options.allowArray;
  60. const allowFunction = useDefaultOptions ? false : options.allowFunction;
  61. const nullable = useDefaultOptions ? false : options.nullable;
  62. if ((!nullable && value === null) ||
  63. (!allowArray && ArrayIsArray(value)) ||
  64. (typeof value !== 'object' && (
  65. !allowFunction || typeof value !== 'function'
  66. ))) {
  67. throw new ERR_INVALID_ARG_TYPE(name, 'Object', value);
  68. }
  69. }
  70. module.exports = {
  71. validateArray,
  72. validateObject,
  73. validateString,
  74. validateStringArray,
  75. validateUnion,
  76. validateBoolean,
  77. validateBooleanArray,
  78. };