|
| 1 | +'use strict'; |
| 2 | + |
| 3 | +const MongooseBuffer = require('../types/buffer'); |
| 4 | + |
| 5 | +const UUID_FORMAT = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}/i; |
| 6 | +const Binary = MongooseBuffer.Binary; |
| 7 | + |
| 8 | +module.exports = function castUUID(value) { |
| 9 | + if (value == null) { |
| 10 | + return value; |
| 11 | + } |
| 12 | + |
| 13 | + function newBuffer(initbuff) { |
| 14 | + const buff = new MongooseBuffer(initbuff); |
| 15 | + buff._subtype = 4; |
| 16 | + return buff; |
| 17 | + } |
| 18 | + |
| 19 | + if (typeof value === 'string') { |
| 20 | + if (UUID_FORMAT.test(value)) { |
| 21 | + return stringToBinary(value); |
| 22 | + } else { |
| 23 | + throw new Error(`"${value}" is not a valid UUID string`); |
| 24 | + } |
| 25 | + } |
| 26 | + |
| 27 | + if (Buffer.isBuffer(value)) { |
| 28 | + return newBuffer(value); |
| 29 | + } |
| 30 | + |
| 31 | + if (value instanceof Binary) { |
| 32 | + return newBuffer(value.value(true)); |
| 33 | + } |
| 34 | + |
| 35 | + // Re: gh-647 and gh-3030, we're ok with casting using `toString()` |
| 36 | + // **unless** its the default Object.toString, because "[object Object]" |
| 37 | + // doesn't really qualify as useful data |
| 38 | + if (value.toString && value.toString !== Object.prototype.toString) { |
| 39 | + if (UUID_FORMAT.test(value.toString())) { |
| 40 | + return stringToBinary(value.toString()); |
| 41 | + } |
| 42 | + } |
| 43 | + |
| 44 | + throw new Error(`"${value}" cannot be casted to a UUID`); |
| 45 | +}; |
| 46 | + |
| 47 | +module.exports.UUID_FORMAT = UUID_FORMAT; |
| 48 | + |
| 49 | +/** |
| 50 | + * Helper function to convert the input hex-string to a buffer |
| 51 | + * @param {String} hex The hex string to convert |
| 52 | + * @returns {Buffer} The hex as buffer |
| 53 | + * @api private |
| 54 | + */ |
| 55 | + |
| 56 | +function hex2buffer(hex) { |
| 57 | + // use buffer built-in function to convert from hex-string to buffer |
| 58 | + const buff = hex != null && Buffer.from(hex, 'hex'); |
| 59 | + return buff; |
| 60 | +} |
| 61 | + |
| 62 | +/** |
| 63 | + * Convert a String to Binary |
| 64 | + * @param {String} uuidStr The value to process |
| 65 | + * @returns {MongooseBuffer} The binary to store |
| 66 | + * @api private |
| 67 | + */ |
| 68 | + |
| 69 | +function stringToBinary(uuidStr) { |
| 70 | + // Protect against undefined & throwing err |
| 71 | + if (typeof uuidStr !== 'string') uuidStr = ''; |
| 72 | + const hex = uuidStr.replace(/[{}-]/g, ''); // remove extra characters |
| 73 | + const bytes = hex2buffer(hex); |
| 74 | + const buff = new MongooseBuffer(bytes); |
| 75 | + buff._subtype = 4; |
| 76 | + |
| 77 | + return buff; |
| 78 | +} |
0 commit comments