UNPKG

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