From c1ca79bc3ecb5dd5110ccba9b21fec8c657f9f06 Mon Sep 17 00:00:00 2001 From: George MacKerron Date: Sun, 23 Jun 2024 14:06:44 +0100 Subject: [PATCH] Custom JSON parsing: return *all* unsafe integers as strings, even if numeric representation as string is the same --- src/db/customJSON.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/src/db/customJSON.ts b/src/db/customJSON.ts index 1ae2dfc..2ea1b55 100644 --- a/src/db/customJSON.ts +++ b/src/db/customJSON.ts @@ -12,10 +12,13 @@ export function enableCustomJSONParsingForLargeNumbers(pg: typeof pgLib) { pg.types.setTypeParser(pg.types.builtins.JSONB, parseJSONWithLargeNumbersAsStrings); } +const { MAX_SAFE_INTEGER, MIN_SAFE_INTEGER } = Number; + function parseJSONWithLargeNumbersAsStrings(str: string) { return parse(str, undefined, function (k, str) { const n = +str; // JSON parser ensures this is an ordinary number, parseInt(str, 10) not needed if (n === Infinity || n === -Infinity) return str; + if ((n < MIN_SAFE_INTEGER || n > MAX_SAFE_INTEGER) && str.indexOf('.') === -1) return str; if (str.length <= 15 || numericStringToExponential(str) === n.toExponential()) return n; return str; });