Name: js-handler/node_modules/restify/lib/clients/json_client.js
| 1: | // Copyright 2012 Mark Cavage, Inc. All rights reserved. |
| 2: | |
| 3: | var crypto = require('crypto'); |
| 4: | var util = require('util'); |
| 5: | |
| 6: | var assert = require('assert-plus'); |
| 7: | |
| 8: | var codeToHttpError = require('../errors/http_error').codeToHttpError; |
| 9: | var RestError = require('../errors').RestError; |
| 10: | var StringClient = require('./string_client'); |
| 11: | |
| 12: | |
| 13: | |
| 14: | ///--- API |
| 15: | |
| 16: | function JsonClient(options) { |
| 17: | assert.object(options, 'options'); |
| 18: | |
| 19: | options.accept = 'application/json'; |
| 20: | options.name = options.name || 'JsonClient'; |
| 21: | options.contentType = 'application/json'; |
| 22: | |
| 23: | StringClient.call(this, options); |
| 24: | |
| 25: | this._super = StringClient.prototype; |
| 26: | } |
| 27: | util.inherits(JsonClient, StringClient); |
| 28: | module.exports = JsonClient; |
| 29: | |
| 30: | |
| 31: | JsonClient.prototype.write = function write(options, body, callback) { |
| 32: | assert.ok(body !== undefined, 'body'); |
| 33: | assert.object(body, 'body'); |
| 34: | |
| 35: | body = JSON.stringify(body !== null ? body : {}); |
| 36: | return (this._super.write.call(this, options, body, callback)); |
| 37: | }; |
| 38: | |
| 39: | |
| 40: | JsonClient.prototype.parse = function parse(req, callback) { |
| 41: | var log = this.log; |
| 42: | function parseResponse(err, req2, res, data) { |
| 43: | var obj; |
| 44: | try { |
| 45: | if (data && !/^\s*$/.test(data)) |
| 46: | obj = JSON.parse(data); |
| 47: | } catch (e) { |
| 48: | // Not really sure what else we can do here, besides |
| 49: | // make the client just keep going. |
| 50: | log.trace(e, 'Invalid JSON in response'); |
| 51: | } |
| 52: | obj = obj || {}; |
| 53: | |
| 54: | if (res && res.statusCode >= 400) { |
| 55: | // Upcast error to a RestError (if we can) |
| 56: | // Be nice and handle errors like |
| 57: | // { error: { code: '', message: '' } } |
| 58: | // in addition to { code: '', message: '' }. |
| 59: | if (obj.code || (obj.error && obj.error.code)) { |
| 60: | var _c = obj.code || |
| 61: | (obj.error ? obj.error.code : '') || |
| 62: | ''; |
| 63: | var _m = obj.message || |
| 64: | (obj.error ? obj.error.message : '') || |
| 65: | ''; |
| 66: | |
| 67: | err = new RestError({ |
| 68: | message: _m, |
| 69: | restCode: _c, |
| 70: | statusCode: res.statusCode |
| 71: | }); |
| 72: | err.name = err.restCode; |
| 73: | if (!/Error$/.test(err.name)) |
| 74: | err.name += 'Error'; |
| 75: | } else if (!err) { |
| 76: | err = codeToHttpError(res.statusCode, |
| 77: | obj.message || '', data); |
| 78: | } |
| 79: | } |
| 80: | |
| 81: | if (err) |
| 82: | err.body = obj; |
| 83: | |
| 84: | callback((err || null), req2, res, obj); |
| 85: | } |
| 86: | |
| 87: | return (this._super.parse.call(this, req, parseResponse)); |
| 88: | }; |
