json.js
2.19 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
var util = require('../util');
var JsonBuilder = require('../json/builder');
var JsonParser = require('../json/parser');
var populateHostPrefix = require('./helpers').populateHostPrefix;
function buildRequest(req) {
var httpRequest = req.httpRequest;
var api = req.service.api;
var target = api.targetPrefix + '.' + api.operations[req.operation].name;
var version = api.jsonVersion || '1.0';
var input = api.operations[req.operation].input;
var builder = new JsonBuilder();
if (version === 1) version = '1.0';
httpRequest.body = builder.build(req.params || {}, input);
httpRequest.headers['Content-Type'] = 'application/x-amz-json-' + version;
httpRequest.headers['X-Amz-Target'] = target;
populateHostPrefix(req);
}
function extractError(resp) {
var error = {};
var httpResponse = resp.httpResponse;
error.code = httpResponse.headers['x-amzn-errortype'] || 'UnknownError';
if (typeof error.code === 'string') {
error.code = error.code.split(':')[0];
}
if (httpResponse.body.length > 0) {
try {
var e = JSON.parse(httpResponse.body.toString());
var code = e.__type || e.code || e.Code;
if (code) {
error.code = code.split('#').pop();
}
if (error.code === 'RequestEntityTooLarge') {
error.message = 'Request body must be less than 1 MB';
} else {
error.message = (e.message || e.Message || null);
}
} catch (e) {
error.statusCode = httpResponse.statusCode;
error.message = httpResponse.statusMessage;
}
} else {
error.statusCode = httpResponse.statusCode;
error.message = httpResponse.statusCode.toString();
}
resp.error = util.error(new Error(), error);
}
function extractData(resp) {
var body = resp.httpResponse.body.toString() || '{}';
if (resp.request.service.config.convertResponseTypes === false) {
resp.data = JSON.parse(body);
} else {
var operation = resp.request.service.api.operations[resp.request.operation];
var shape = operation.output || {};
var parser = new JsonParser();
resp.data = parser.parse(body, shape);
}
}
/**
* @api private
*/
module.exports = {
buildRequest: buildRequest,
extractError: extractError,
extractData: extractData
};