bigint.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. 'use strict';
  2. const { Long } = require('mongodb/lib/bson');
  3. /**
  4. * Given a value, cast it to a BigInt, or throw an `Error` if the value
  5. * cannot be casted. `null` and `undefined` are considered valid.
  6. *
  7. * @param {Any} value
  8. * @return {Number}
  9. * @throws {Error} if `value` is not one of the allowed values
  10. * @api private
  11. */
  12. const MAX_BIGINT = 9223372036854775807n;
  13. const MIN_BIGINT = -9223372036854775808n;
  14. const ERROR_MESSAGE = `Mongoose only supports BigInts between ${MIN_BIGINT} and ${MAX_BIGINT} because MongoDB does not support arbitrary precision integers`;
  15. module.exports = function castBigInt(val) {
  16. if (val == null) {
  17. return val;
  18. }
  19. if (val === '') {
  20. return null;
  21. }
  22. if (typeof val === 'bigint') {
  23. if (val > MAX_BIGINT || val < MIN_BIGINT) {
  24. throw new Error(ERROR_MESSAGE);
  25. }
  26. return val;
  27. }
  28. if (val instanceof Long) {
  29. return val.toBigInt();
  30. }
  31. if (typeof val === 'string' || typeof val === 'number') {
  32. val = BigInt(val);
  33. if (val > MAX_BIGINT || val < MIN_BIGINT) {
  34. throw new Error(ERROR_MESSAGE);
  35. }
  36. return val;
  37. }
  38. throw new Error(`Cannot convert value to BigInt: "${val}"`);
  39. };