* Create a JSON parse function * * @param {object} [options] * @return {function} * @private
(options)
| 69 | * @private |
| 70 | */ |
| 71 | function createJsonParser (options) { |
| 72 | const reviver = options?.reviver |
| 73 | const strict = options?.strict !== false |
| 74 | |
| 75 | if (strict) { |
| 76 | return function parse (body) { |
| 77 | if (body.length === 0) { |
| 78 | // special-case empty json body, as it's a common client-side mistake |
| 79 | // TODO: maybe make this configurable or part of "strict" option |
| 80 | return {} |
| 81 | } |
| 82 | |
| 83 | const first = firstchar(body) |
| 84 | if (first !== '{' && first !== '[') { |
| 85 | debug('strict violation') |
| 86 | throw createStrictSyntaxError(body, first) |
| 87 | } |
| 88 | |
| 89 | try { |
| 90 | debug('parse json') |
| 91 | return JSON.parse(body, reviver) |
| 92 | } catch (e) { |
| 93 | throw normalizeJsonSyntaxError(e, { |
| 94 | message: e.message, |
| 95 | stack: e.stack |
| 96 | }) |
| 97 | } |
| 98 | } |
| 99 | } |
| 100 | |
| 101 | return function parse (body) { |
| 102 | if (body.length === 0) { |
| 103 | // special-case empty json body, as it's a common client-side mistake |
| 104 | // TODO: maybe make this configurable or part of "strict" option |
| 105 | return {} |
| 106 | } |
| 107 | |
| 108 | try { |
| 109 | debug('parse json') |
| 110 | return JSON.parse(body, reviver) |
| 111 | } catch (e) { |
| 112 | throw normalizeJsonSyntaxError(e, { |
| 113 | message: e.message, |
| 114 | stack: e.stack |
| 115 | }) |
| 116 | } |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | /** |
| 121 | * Create strict violation syntax error matching native error. |
no test coverage detected
searching dependent graphs…