ontotext-platform-custom-scalars
Version:
A library of customized GraphQL scalars for Ontotext Platform
89 lines (62 loc) • 2.29 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var _graphql = require("graphql");
var _Utilities = require("../Utilities");
var UNSIGNED_LONG = 'UnsignedLong'; // defines max values allowed for the current type - 2^64 -1
var MAX_VALUE_ARRAY = Array.from('18446744073709551615', Number);
function convert(value) {
if (!(0, _Utilities.isNumber)(value)) {
throw new _graphql.GraphQLError("Expected number, but got '".concat(value, "'"));
}
var copy = value;
if (!(0, _Utilities.isInteger)(copy)) {
copy = Math.trunc(copy);
}
if ((0, _Utilities.isNegative)(copy)) {
(0, _Utilities.throwNegativeValueError)(value, UNSIGNED_LONG);
}
if (checkOutOfRange(copy)) {
(0, _Utilities.throwOutOfRangeError)(value, UNSIGNED_LONG);
}
return copy + '';
}
function checkOutOfRange(value) {
var valueArray = Array.from(BigInt(value).toString(), Number);
if (valueArray.length < MAX_VALUE_ARRAY.length) {
return false;
}
if (valueArray.length > MAX_VALUE_ARRAY.length) {
return true;
} // the lengths are equal here so we need to check the actual values
for (var idx = 0; idx < MAX_VALUE_ARRAY.length; idx++) {
var maxValueNum = MAX_VALUE_ARRAY[idx];
var valueNum = valueArray[idx]; // if the number at that position is less then the max number, the whole value should be OK
if (maxValueNum > valueNum) {
return false;
} // if the value number is greater then the max number, the whole value exceeds the limit
if (maxValueNum < valueNum) {
return true;
} // continue with the next number as the max number and the value number are equal at this point
} // the value is equal to the max allowed
return false;
}
/**
* Defines custom GraphQLScalarType for unsigned Long values.
*/
var _default = new _graphql.GraphQLScalarType({
name: UNSIGNED_LONG,
description: "Unsigned 64-bit integer",
serialize: convert,
parseValue: convert,
parseLiteral: function parseLiteral(node) {
var type = node.kind;
if (_graphql.Kind.INT !== type && _graphql.Kind.STRING !== type) {
(0, _Utilities.throwConversionError)(type, UNSIGNED_LONG);
}
return convert(node.value);
}
});
exports["default"] = _default;