string.js 995 B

12345678910111213141516171819202122232425262728293031323334353637
  1. 'use strict';
  2. const CastError = require('../error/cast');
  3. /*!
  4. * Given a value, cast it to a string, or throw a `CastError` if the value
  5. * cannot be casted. `null` and `undefined` are considered valid.
  6. *
  7. * @param {Any} value
  8. * @param {String} [path] optional the path to set on the CastError
  9. * @return {string|null|undefined}
  10. * @throws {CastError}
  11. * @api private
  12. */
  13. module.exports = function castString(value, path) {
  14. // If null or undefined
  15. if (value == null) {
  16. return value;
  17. }
  18. // handle documents being passed
  19. if (value._id && typeof value._id === 'string') {
  20. return value._id;
  21. }
  22. // Re: gh-647 and gh-3030, we're ok with casting using `toString()`
  23. // **unless** its the default Object.toString, because "[object Object]"
  24. // doesn't really qualify as useful data
  25. if (value.toString &&
  26. value.toString !== Object.prototype.toString &&
  27. !Array.isArray(value)) {
  28. return value.toString();
  29. }
  30. throw new CastError('string', value, path);
  31. };