| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305 |
- /*!
- * Module dependencies.
- */
- 'use strict';
- const SchemaType = require('../schemaType');
- const CastError = SchemaType.CastError;
- const castUUID = require('../cast/uuid');
- const createJSONSchemaTypeDefinition = require('../helpers/createJSONSchemaTypeDefinition');
- const utils = require('../utils');
- const handleBitwiseOperator = require('./operators/bitwise');
- const UUID_FORMAT = castUUID.UUID_FORMAT;
- /**
- * Convert binary to a uuid string
- * @param {Buffer|Binary|String} uuidBin The value to process
- * @returns {String} The completed uuid-string
- * @api private
- */
- function binaryToString(uuidBin) {
- // i(hasezoey) dont quite know why, but "uuidBin" may sometimes also be the already processed string
- let hex;
- if (typeof uuidBin !== 'string' && uuidBin != null) {
- hex = uuidBin.toString('hex');
- const uuidStr = hex.substring(0, 8) + '-' + hex.substring(8, 8 + 4) + '-' + hex.substring(12, 12 + 4) + '-' + hex.substring(16, 16 + 4) + '-' + hex.substring(20, 20 + 12);
- return uuidStr;
- }
- return uuidBin;
- }
- /**
- * UUIDv1 SchemaType constructor.
- *
- * @param {String} key
- * @param {Object} options
- * @param {Object} _schemaOptions
- * @param {Schema} parentSchema
- * @inherits SchemaType
- * @api public
- */
- function SchemaUUID(key, options, _schemaOptions, parentSchema) {
- SchemaType.call(this, key, options, 'UUID', parentSchema);
- }
- /**
- * This schema type's name, to defend against minifiers that mangle
- * function names.
- *
- * @api public
- */
- SchemaUUID.schemaName = 'UUID';
- SchemaUUID.defaultOptions = {};
- /*!
- * Inherits from SchemaType.
- */
- SchemaUUID.prototype = Object.create(SchemaType.prototype);
- SchemaUUID.prototype.constructor = SchemaUUID;
- /*!
- * ignore
- */
- SchemaUUID._cast = castUUID;
- /**
- * Attaches a getter for all UUID instances.
- *
- * #### Example:
- *
- * // Note that `v` is a string by default
- * mongoose.Schema.UUID.get(v => v.toUpperCase());
- *
- * const Model = mongoose.model('Test', new Schema({ test: 'UUID' }));
- * new Model({ test: uuid.v4() }).test; // UUID with all uppercase
- *
- * @param {Function} getter
- * @return {this}
- * @function get
- * @static
- * @api public
- */
- SchemaUUID.get = SchemaType.get;
- /**
- * Sets a default option for all UUID instances.
- *
- * #### Example:
- *
- * // Make all UUIDs have `required` of true by default.
- * mongoose.Schema.UUID.set('required', true);
- *
- * const User = mongoose.model('User', new Schema({ test: mongoose.UUID }));
- * new User({ }).validateSync().errors.test.message; // Path `test` is required.
- *
- * @param {String} option The option you'd like to set the value for
- * @param {Any} value value for option
- * @return {undefined}
- * @function set
- * @static
- * @api public
- */
- SchemaUUID.set = SchemaType.set;
- SchemaUUID.setters = [];
- /**
- * Get/set the function used to cast arbitrary values to UUIDs.
- *
- * #### Example:
- *
- * // Make Mongoose refuse to cast UUIDs with 0 length
- * const original = mongoose.Schema.Types.UUID.cast();
- * mongoose.UUID.cast(v => {
- * assert.ok(typeof v === "string" && v.length > 0);
- * return original(v);
- * });
- *
- * // Or disable casting entirely
- * mongoose.UUID.cast(false);
- *
- * @param {Function} [caster]
- * @return {Function}
- * @function get
- * @static
- * @api public
- */
- SchemaUUID.cast = function cast(caster) {
- if (arguments.length === 0) {
- return this._cast;
- }
- if (caster === false) {
- caster = this._defaultCaster;
- }
- this._cast = caster;
- return this._cast;
- };
- /*!
- * ignore
- */
- SchemaUUID._checkRequired = v => v != null;
- /**
- * Override the function the required validator uses to check whether a string
- * passes the `required` check.
- *
- * @param {Function} fn
- * @return {Function}
- * @function checkRequired
- * @static
- * @api public
- */
- SchemaUUID.checkRequired = SchemaType.checkRequired;
- /**
- * Check if the given value satisfies a required validator.
- *
- * @param {Any} value
- * @return {Boolean}
- * @api public
- */
- SchemaUUID.prototype.checkRequired = function checkRequired(value) {
- if (Buffer.isBuffer(value)) {
- value = binaryToString(value);
- }
- return value != null && UUID_FORMAT.test(value);
- };
- /**
- * Casts to UUID
- *
- * @param {Object} value
- * @param {Object} doc
- * @param {Boolean} init whether this is an initialization cast
- * @api private
- */
- SchemaUUID.prototype.cast = function(value, doc, init, prev, options) {
- if (utils.isNonBuiltinObject(value) &&
- SchemaType._isRef(this, value, doc, init)) {
- return this._castRef(value, doc, init, options);
- }
- let castFn;
- if (typeof this._castFunction === 'function') {
- castFn = this._castFunction;
- } else if (typeof this.constructor.cast === 'function') {
- castFn = this.constructor.cast();
- } else {
- castFn = SchemaUUID.cast();
- }
- try {
- return castFn(value);
- } catch (error) {
- throw new CastError(SchemaUUID.schemaName, value, this.path, error, this);
- }
- };
- /*!
- * ignore
- */
- function handleSingle(val) {
- return this.cast(val);
- }
- /*!
- * ignore
- */
- function handleArray(val) {
- return val.map((m) => {
- return this.cast(m);
- });
- }
- const $conditionalHandlers = {
- ...SchemaType.prototype.$conditionalHandlers,
- $bitsAllClear: handleBitwiseOperator,
- $bitsAnyClear: handleBitwiseOperator,
- $bitsAllSet: handleBitwiseOperator,
- $bitsAnySet: handleBitwiseOperator,
- $all: handleArray,
- $in: handleArray,
- $ne: handleSingle,
- $nin: handleArray
- };
- /**
- * Contains the handlers for different query operators for this schema type.
- * For example, `$conditionalHandlers.$exists` is the function Mongoose calls to cast `$exists` filter operators.
- *
- * @property $conditionalHandlers
- * @memberOf SchemaUUID
- * @instance
- * @api public
- */
- Object.defineProperty(SchemaUUID.prototype, '$conditionalHandlers', {
- enumerable: false,
- value: $conditionalHandlers
- });
- /**
- * Casts contents for queries.
- *
- * @param {String} $conditional
- * @param {any} val
- * @api private
- */
- SchemaUUID.prototype.castForQuery = function($conditional, val, context) {
- let handler;
- if ($conditional != null) {
- handler = this.$conditionalHandlers[$conditional];
- if (!handler)
- throw new Error('Can\'t use ' + $conditional + ' with UUID.');
- return handler.call(this, val, context);
- }
- try {
- return this.applySetters(val, context);
- } catch (err) {
- if (err instanceof CastError && err.path === this.path && this.$fullPath != null) {
- err.path = this.$fullPath;
- }
- throw err;
- }
- };
- /**
- * Returns this schema type's representation in a JSON schema.
- *
- * @param [options]
- * @param [options.useBsonType=false] If true, return a representation with `bsonType` for use with MongoDB's `$jsonSchema`.
- * @returns {Object} JSON schema properties
- */
- SchemaUUID.prototype.toJSONSchema = function toJSONSchema(options) {
- const isRequired = this.options.required && typeof this.options.required !== 'function';
- return createJSONSchemaTypeDefinition('string', 'binData', options?.useBsonType, isRequired);
- };
- SchemaUUID.prototype.autoEncryptionType = function autoEncryptionType() {
- return 'binData';
- };
- /*!
- * Module exports.
- */
- module.exports = SchemaUUID;
|