|
11 | 11 | * |
12 | 12 | */ |
13 | 13 |
|
| 14 | + |
| 15 | +// ordercloud's error responses have a BOM character that causes json parse to fail |
| 16 | + function customJsonParser(res, fn) { |
| 17 | + res.text = ''; |
| 18 | + res.setEncoding('utf8'); |
| 19 | + res.on('data', function(chunk) { |
| 20 | + res.text += chunk; |
| 21 | + }) |
| 22 | + res.on('end', function() { |
| 23 | + var body; |
| 24 | + var err; |
| 25 | + try { |
| 26 | + var text = res.text; |
| 27 | + if(text && text.charCodeAt(0) === 65279) { |
| 28 | + text = text.substr(1) |
| 29 | + } |
| 30 | + body = text && JSON.parse(text); |
| 31 | + } catch (err2) { |
| 32 | + err = err2; |
| 33 | + // issue #675: return the raw response if the response parsing fails |
| 34 | + err.rawResponse = res.text || null; |
| 35 | + // issue #876: return the http status code if the response parsing fails |
| 36 | + err.statusCode = res.statusCode; |
| 37 | + } finally { |
| 38 | + fn(err, body); |
| 39 | + } |
| 40 | + }) |
| 41 | + } |
| 42 | + |
14 | 43 | (function(root, factory) { |
15 | 44 | if (typeof define === 'function' && define.amd) { |
16 | 45 | // AMD. Register as an anonymous module. |
|
344 | 373 | var _this = this; |
345 | 374 | var url = this.buildUrl(path, pathParams); |
346 | 375 | var request = superagent(httpMethod, url); |
| 376 | + request.parse(customJsonParser); |
| 377 | + request.buffer(true) |
347 | 378 |
|
348 | 379 | // apply authentications |
349 | 380 | this.applyAuthToRequest(request, accessToken); |
@@ -415,6 +446,8 @@ exports.prototype.callAuth = function callApi(path, httpMethod, pathParams, |
415 | 446 | var _this = this; |
416 | 447 | var url = _this.baseAuthPath.replace(/\/+$/, '') + path; |
417 | 448 | var request = superagent(httpMethod, url); |
| 449 | + request.parse(customJsonParser); |
| 450 | + request.buffer(true) |
418 | 451 |
|
419 | 452 | // set query parameters |
420 | 453 | request.query(this.normalizeParams(queryParams)); |
|
0 commit comments