uuid.js 955 B

1234567891011121314151617181920212223242526272829303132333435
  1. 'use strict';
  2. const UUID = require('mongodb/lib/bson').UUID;
  3. 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;
  4. module.exports = function castUUID(value) {
  5. if (value == null) {
  6. return value;
  7. }
  8. if (value instanceof UUID) {
  9. return value;
  10. }
  11. if (typeof value === 'string') {
  12. if (UUID_FORMAT.test(value)) {
  13. return new UUID(value);
  14. } else {
  15. throw new Error(`"${value}" is not a valid UUID string`);
  16. }
  17. }
  18. // Re: gh-647 and gh-3030, we're ok with casting using `toString()`
  19. // **unless** its the default Object.toString, because "[object Object]"
  20. // doesn't really qualify as useful data
  21. if (value.toString && value.toString !== Object.prototype.toString) {
  22. if (UUID_FORMAT.test(value.toString())) {
  23. return new UUID(value.toString());
  24. }
  25. }
  26. throw new Error(`"${value}" cannot be casted to a UUID`);
  27. };
  28. module.exports.UUID_FORMAT = UUID_FORMAT;