PageRenderTime 34ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 1ms

/node_modules/mongoose/lib/schema/string.js

https://gitlab.com/backflips/test
JavaScript | 473 lines | 192 code | 54 blank | 227 comment | 60 complexity | ea7269fa506a67983d847042b084e94e MD5 | raw file
  1. /*!
  2. * Module dependencies.
  3. */
  4. var SchemaType = require('../schematype')
  5. , CastError = SchemaType.CastError
  6. , errorMessages = require('../error').messages
  7. , utils = require('../utils')
  8. , Document
  9. /**
  10. * String SchemaType constructor.
  11. *
  12. * @param {String} key
  13. * @param {Object} options
  14. * @inherits SchemaType
  15. * @api private
  16. */
  17. function SchemaString (key, options) {
  18. this.enumValues = [];
  19. this.regExp = null;
  20. SchemaType.call(this, key, options, 'String');
  21. };
  22. /**
  23. * This schema type's name, to defend against minifiers that mangle
  24. * function names.
  25. *
  26. * @api private
  27. */
  28. SchemaString.schemaName = 'String';
  29. /*!
  30. * Inherits from SchemaType.
  31. */
  32. SchemaString.prototype = Object.create( SchemaType.prototype );
  33. SchemaString.prototype.constructor = SchemaString;
  34. /**
  35. * Adds an enum validator
  36. *
  37. * ####Example:
  38. *
  39. * var states = 'opening open closing closed'.split(' ')
  40. * var s = new Schema({ state: { type: String, enum: states }})
  41. * var M = db.model('M', s)
  42. * var m = new M({ state: 'invalid' })
  43. * m.save(function (err) {
  44. * console.error(String(err)) // ValidationError: `invalid` is not a valid enum value for path `state`.
  45. * m.state = 'open'
  46. * m.save(callback) // success
  47. * })
  48. *
  49. * // or with custom error messages
  50. * var enu = {
  51. * values: 'opening open closing closed'.split(' '),
  52. * message: 'enum validator failed for path `{PATH}` with value `{VALUE}`'
  53. * }
  54. * var s = new Schema({ state: { type: String, enum: enu })
  55. * var M = db.model('M', s)
  56. * var m = new M({ state: 'invalid' })
  57. * m.save(function (err) {
  58. * console.error(String(err)) // ValidationError: enum validator failed for path `state` with value `invalid`
  59. * m.state = 'open'
  60. * m.save(callback) // success
  61. * })
  62. *
  63. * @param {String|Object} [args...] enumeration values
  64. * @return {SchemaType} this
  65. * @see Customized Error Messages #error_messages_MongooseError-messages
  66. * @api public
  67. */
  68. SchemaString.prototype.enum = function () {
  69. if (this.enumValidator) {
  70. this.validators = this.validators.filter(function(v) {
  71. return v.validator != this.enumValidator;
  72. }, this);
  73. this.enumValidator = false;
  74. }
  75. if (undefined === arguments[0] || false === arguments[0]) {
  76. return this;
  77. }
  78. var values;
  79. var errorMessage;
  80. if (utils.isObject(arguments[0])) {
  81. values = arguments[0].values;
  82. errorMessage = arguments[0].message;
  83. } else {
  84. values = arguments;
  85. errorMessage = errorMessages.String.enum;
  86. }
  87. for (var i = 0; i < values.length; i++) {
  88. if (undefined !== values[i]) {
  89. this.enumValues.push(this.cast(values[i]));
  90. }
  91. }
  92. var vals = this.enumValues;
  93. this.enumValidator = function (v) {
  94. return undefined === v || ~vals.indexOf(v);
  95. };
  96. this.validators.push({ validator: this.enumValidator, message: errorMessage, type: 'enum' });
  97. return this;
  98. };
  99. /**
  100. * Adds a lowercase setter.
  101. *
  102. * ####Example:
  103. *
  104. * var s = new Schema({ email: { type: String, lowercase: true }})
  105. * var M = db.model('M', s);
  106. * var m = new M({ email: 'SomeEmail@example.COM' });
  107. * console.log(m.email) // someemail@example.com
  108. *
  109. * @api public
  110. * @return {SchemaType} this
  111. */
  112. SchemaString.prototype.lowercase = function () {
  113. return this.set(function (v, self) {
  114. if ('string' != typeof v) v = self.cast(v)
  115. if (v) return v.toLowerCase();
  116. return v;
  117. });
  118. };
  119. /**
  120. * Adds an uppercase setter.
  121. *
  122. * ####Example:
  123. *
  124. * var s = new Schema({ caps: { type: String, uppercase: true }})
  125. * var M = db.model('M', s);
  126. * var m = new M({ caps: 'an example' });
  127. * console.log(m.caps) // AN EXAMPLE
  128. *
  129. * @api public
  130. * @return {SchemaType} this
  131. */
  132. SchemaString.prototype.uppercase = function () {
  133. return this.set(function (v, self) {
  134. if ('string' != typeof v) v = self.cast(v)
  135. if (v) return v.toUpperCase();
  136. return v;
  137. });
  138. };
  139. /**
  140. * Adds a trim setter.
  141. *
  142. * The string value will be trimmed when set.
  143. *
  144. * ####Example:
  145. *
  146. * var s = new Schema({ name: { type: String, trim: true }})
  147. * var M = db.model('M', s)
  148. * var string = ' some name '
  149. * console.log(string.length) // 11
  150. * var m = new M({ name: string })
  151. * console.log(m.name.length) // 9
  152. *
  153. * @api public
  154. * @return {SchemaType} this
  155. */
  156. SchemaString.prototype.trim = function () {
  157. return this.set(function (v, self) {
  158. if ('string' != typeof v) v = self.cast(v)
  159. if (v) return v.trim();
  160. return v;
  161. });
  162. };
  163. /**
  164. * Sets a minimum length validator.
  165. *
  166. * ####Example:
  167. *
  168. * var schema = new Schema({ postalCode: { type: String, minlength: 5 })
  169. * var Address = db.model('Address', schema)
  170. * var address = new Address({ postalCode: '9512' })
  171. * address.save(function (err) {
  172. * console.error(err) // validator error
  173. * address.postalCode = '95125';
  174. * address.save() // success
  175. * })
  176. *
  177. * // custom error messages
  178. * // We can also use the special {MINLENGTH} token which will be replaced with the invalid value
  179. * var minlength = [10, 'The value of path `{PATH}` (`{VALUE}`) is shorter than the minimum length ({MINLENGTH}).'];
  180. * var schema = new Schema({ postalCode: { type: String, minlength: minlength })
  181. * var Address = mongoose.model('Address', schema);
  182. * var address = new Address({ postalCode: '9512' });
  183. * s.validate(function (err) {
  184. * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512`) is shorter than the minimum length (5).
  185. * })
  186. *
  187. * @param {Number} value minimum string length
  188. * @param {String} [message] optional custom error message
  189. * @return {SchemaType} this
  190. * @see Customized Error Messages #error_messages_MongooseError-messages
  191. * @api public
  192. */
  193. SchemaString.prototype.minlength = function (value, message) {
  194. if (this.minlengthValidator) {
  195. this.validators = this.validators.filter(function (v) {
  196. return v.validator != this.minlengthValidator;
  197. }, this);
  198. }
  199. if (null != value) {
  200. var msg = message || errorMessages.String.minlength;
  201. msg = msg.replace(/{MINLENGTH}/, value);
  202. this.validators.push({
  203. validator: this.minlengthValidator = function (v) {
  204. return v === null || v.length >= value;
  205. },
  206. message: msg,
  207. type: 'minlength'
  208. });
  209. }
  210. return this;
  211. };
  212. /**
  213. * Sets a maximum length validator.
  214. *
  215. * ####Example:
  216. *
  217. * var schema = new Schema({ postalCode: { type: String, maxlength: 9 })
  218. * var Address = db.model('Address', schema)
  219. * var address = new Address({ postalCode: '9512512345' })
  220. * address.save(function (err) {
  221. * console.error(err) // validator error
  222. * address.postalCode = '95125';
  223. * address.save() // success
  224. * })
  225. *
  226. * // custom error messages
  227. * // We can also use the special {MAXLENGTH} token which will be replaced with the invalid value
  228. * var maxlength = [10, 'The value of path `{PATH}` (`{VALUE}`) exceeds the maximum allowed length ({MAXLENGTH}).'];
  229. * var schema = new Schema({ postalCode: { type: String, maxlength: maxlength })
  230. * var Address = mongoose.model('Address', schema);
  231. * var address = new Address({ postalCode: '9512512345' });
  232. * address.validate(function (err) {
  233. * console.log(String(err)) // ValidationError: The value of path `postalCode` (`9512512345`) exceeds the maximum allowed length (10).
  234. * })
  235. *
  236. * @param {Number} value maximum string length
  237. * @param {String} [message] optional custom error message
  238. * @return {SchemaType} this
  239. * @see Customized Error Messages #error_messages_MongooseError-messages
  240. * @api public
  241. */
  242. SchemaString.prototype.maxlength = function (value, message) {
  243. if (this.maxlengthValidator) {
  244. this.validators = this.validators.filter(function(v){
  245. return v.validator != this.maxlengthValidator;
  246. }, this);
  247. }
  248. if (null != value) {
  249. var msg = message || errorMessages.String.maxlength;
  250. msg = msg.replace(/{MAXLENGTH}/, value);
  251. this.validators.push({
  252. validator: this.maxlengthValidator = function(v) {
  253. return v === null || v.length <= value;
  254. },
  255. message: msg,
  256. type: 'maxlength'
  257. });
  258. }
  259. return this;
  260. };
  261. /**
  262. * Sets a regexp validator.
  263. *
  264. * Any value that does not pass `regExp`.test(val) will fail validation.
  265. *
  266. * ####Example:
  267. *
  268. * var s = new Schema({ name: { type: String, match: /^a/ }})
  269. * var M = db.model('M', s)
  270. * var m = new M({ name: 'I am invalid' })
  271. * m.validate(function (err) {
  272. * console.error(String(err)) // "ValidationError: Path `name` is invalid (I am invalid)."
  273. * m.name = 'apples'
  274. * m.validate(function (err) {
  275. * assert.ok(err) // success
  276. * })
  277. * })
  278. *
  279. * // using a custom error message
  280. * var match = [ /\.html$/, "That file doesn't end in .html ({VALUE})" ];
  281. * var s = new Schema({ file: { type: String, match: match }})
  282. * var M = db.model('M', s);
  283. * var m = new M({ file: 'invalid' });
  284. * m.validate(function (err) {
  285. * console.log(String(err)) // "ValidationError: That file doesn't end in .html (invalid)"
  286. * })
  287. *
  288. * Empty strings, `undefined`, and `null` values always pass the match validator. If you require these values, enable the `required` validator also.
  289. *
  290. * var s = new Schema({ name: { type: String, match: /^a/, required: true }})
  291. *
  292. * @param {RegExp} regExp regular expression to test against
  293. * @param {String} [message] optional custom error message
  294. * @return {SchemaType} this
  295. * @see Customized Error Messages #error_messages_MongooseError-messages
  296. * @api public
  297. */
  298. SchemaString.prototype.match = function match (regExp, message) {
  299. // yes, we allow multiple match validators
  300. var msg = message || errorMessages.String.match;
  301. var matchValidator = function(v) {
  302. var ret = ((null != v && '' !== v)
  303. ? regExp.test(v)
  304. : true);
  305. return ret;
  306. };
  307. this.validators.push({ validator: matchValidator, message: msg, type: 'regexp' });
  308. return this;
  309. };
  310. /**
  311. * Check required
  312. *
  313. * @param {String|null|undefined} value
  314. * @api private
  315. */
  316. SchemaString.prototype.checkRequired = function checkRequired (value, doc) {
  317. if (SchemaType._isRef(this, value, doc, true)) {
  318. return null != value;
  319. } else {
  320. return (value instanceof String || typeof value == 'string') && value.length;
  321. }
  322. };
  323. /**
  324. * Casts to String
  325. *
  326. * @api private
  327. */
  328. SchemaString.prototype.cast = function (value, doc, init) {
  329. if (SchemaType._isRef(this, value, doc, init)) {
  330. // wait! we may need to cast this to a document
  331. if (null == value) {
  332. return value;
  333. }
  334. // lazy load
  335. Document || (Document = require('./../document'));
  336. if (value instanceof Document) {
  337. value.$__.wasPopulated = true;
  338. return value;
  339. }
  340. // setting a populated path
  341. if ('string' == typeof value) {
  342. return value;
  343. } else if (Buffer.isBuffer(value) || !utils.isObject(value)) {
  344. throw new CastError('string', value, this.path);
  345. }
  346. // Handle the case where user directly sets a populated
  347. // path to a plain object; cast to the Model used in
  348. // the population query.
  349. var path = doc.$__fullPath(this.path);
  350. var owner = doc.ownerDocument ? doc.ownerDocument() : doc;
  351. var pop = owner.populated(path, true);
  352. var ret = new pop.options.model(value);
  353. ret.$__.wasPopulated = true;
  354. return ret;
  355. }
  356. // If null or undefined
  357. if (value == null) {
  358. return value;
  359. }
  360. if ('undefined' !== typeof value) {
  361. // handle documents being passed
  362. if (value._id && 'string' == typeof value._id) {
  363. return value._id;
  364. }
  365. if (value.toString) {
  366. return value.toString();
  367. }
  368. }
  369. throw new CastError('string', value, this.path);
  370. };
  371. /*!
  372. * ignore
  373. */
  374. function handleSingle (val) {
  375. return this.castForQuery(val);
  376. }
  377. function handleArray (val) {
  378. var self = this;
  379. return val.map(function (m) {
  380. return self.castForQuery(m);
  381. });
  382. }
  383. SchemaString.prototype.$conditionalHandlers =
  384. utils.options(SchemaType.prototype.$conditionalHandlers, {
  385. '$all': handleArray,
  386. '$gt' : handleSingle,
  387. '$gte': handleSingle,
  388. '$in' : handleArray,
  389. '$lt' : handleSingle,
  390. '$lte': handleSingle,
  391. '$ne' : handleSingle,
  392. '$nin': handleArray,
  393. '$options': handleSingle,
  394. '$regex': handleSingle
  395. });
  396. /**
  397. * Casts contents for queries.
  398. *
  399. * @param {String} $conditional
  400. * @param {any} [val]
  401. * @api private
  402. */
  403. SchemaString.prototype.castForQuery = function ($conditional, val) {
  404. var handler;
  405. if (arguments.length === 2) {
  406. handler = this.$conditionalHandlers[$conditional];
  407. if (!handler)
  408. throw new Error("Can't use " + $conditional + " with String.");
  409. return handler.call(this, val);
  410. } else {
  411. val = $conditional;
  412. if (val instanceof RegExp) return val;
  413. return this.cast(val);
  414. }
  415. };
  416. /*!
  417. * Module exports.
  418. */
  419. module.exports = SchemaString;