UNPKG

@cran/gql.core

Version:

Cran/GraphQL Core Utilities

63 lines (62 loc) 1.92 kB
/* eslint-disable prefer-template */ import { createScalar } from "../utilities/createScalar"; // Simplification of logic is possible due to Number // and BigInt internal error mechanisms function castInt(value) { switch (typeof value) { case "string": if ((/e/iu).test(value)) { value = "" + Number(value); } // Parse float down to an integer // TODO configuration allow strict return value.replace(/\.\d*$/u, ""); case "number": return value | 0; default: // invariant return undefined; } } function createAsInt(bits) { function asInt(value, invalid) { const bigint = BigInt(castInt(value)); const clamped = BigInt.asIntN(bits, bigint); // TODO config allow clamping if (bigint !== clamped) { return invalid("range"); } return "" + value; } return { string: asInt, number: asInt, boolean(value) { return "" + (+value); }, }; } export const Int2Scalar = createScalar("int2", "small-range integer", createAsInt(16)); export const Int4Scalar = createScalar("int4", "integer", createAsInt(32)); export const Int8Scalar = createScalar("int8", "large-range integer", createAsInt(64)); export const RealScalar = createScalar("real", "variable-precision, exact", { string(value, invalid) { if ((/e/iu).test(value)) { const number = Number(value); if (isNaN(number)) { invalid(); } return "" + number; } if (!(/[+-]?\d+(\.\d+)?/u).test(value)) { invalid(); } return invalid(); }, number(value, invalid) { return isNaN(value) ? invalid() : ("" + value); }, boolean(value) { return "" + (+value); }, });