@sanity/util
Version:
Utilities shared across projects of Sanity
1 lines • 1.66 kB
Source Map (JSON)
{"version":3,"file":"createSafeJsonParser.mjs","sources":["../src/createSafeJsonParser.ts"],"sourcesContent":["interface Options {\n errorLabel: string\n}\n\ntype Parser<Type> = (line: string) => Type\n\n/**\n * Create a safe JSON parser that is able to handle lines interrupted by an error object.\n *\n * This may occur when streaming NDJSON from the Export HTTP API.\n *\n * @internal\n * @see {@link https://github.com/sanity-io/sanity/pull/1787 | Initial pull request}\n */\nexport function createSafeJsonParser<Type>({errorLabel}: Options): Parser<Type> {\n return function safeJsonParser(line) {\n try {\n return JSON.parse(line)\n } catch (err) {\n // Catch half-done lines with an error at the end\n const errorPosition = line.lastIndexOf('{\"error\":')\n if (errorPosition === -1) {\n err.message = `${err.message} (${line})`\n throw err\n }\n\n const errorJson = line.slice(errorPosition)\n const errorLine = JSON.parse(errorJson)\n const error = errorLine && errorLine.error\n if (error && error.description) {\n throw new Error(`${errorLabel}: ${error.description}\\n\\n${errorJson}\\n`)\n }\n\n throw err\n }\n }\n}\n"],"names":[],"mappings":"AAcO,SAAS,qBAA2B,EAAC,cAAoC;AAC9E,SAAO,SAAwB,MAAM;AACnC,QAAI;AACF,aAAO,KAAK,MAAM,IAAI;AAAA,IACxB,SAAS,KAAK;AAEZ,YAAM,gBAAgB,KAAK,YAAY,WAAW;AAClD,UAAI,kBAAkB;AACpB,cAAA,IAAI,UAAU,GAAG,IAAI,OAAO,KAAK,IAAI,KAC/B;AAGR,YAAM,YAAY,KAAK,MAAM,aAAa,GACpC,YAAY,KAAK,MAAM,SAAS,GAChC,QAAQ,aAAa,UAAU;AACrC,YAAI,SAAS,MAAM,cACX,IAAI,MAAM,GAAG,UAAU,KAAK,MAAM,WAAW;AAAA;AAAA,EAAO,SAAS;AAAA,CAAI,IAGnE;AAAA,IACR;AAAA,EACF;AACF;"}