string.js 958 B

1234567891011121314151617181920212223242526272829303132333435
  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 && value.toString !== Object.prototype.toString) {
  26. return value.toString();
  27. }
  28. throw new CastError('string', value, path);
  29. };