-
Notifications
You must be signed in to change notification settings - Fork 10
/
encoder.js
69 lines (49 loc) · 1.66 KB
/
encoder.js
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
'use strict';
let zlib = require('zlib');
class Encoder {
constructor(encoders) {
this._encoders = encoders;
}
serializeRequest(request) {
let contentType = request.headers['content-type'];
if (!contentType) {
throw new Error('HttpRequest does not have Content-Type header set');
}
let encoder = this._encoder(contentType);
if (!encoder) {
throw new Error(`Unable to serialize request with Content-Type ${contentType}. Supported encodings are ${this.supportedEncodings()}`);
}
let contentEncoding = request.headers['content-encoding'];
let encoded = encoder.encode(request);
if (contentEncoding === 'gzip') {
return zlib.gzipSync(encoded);
}
return encoded;
}
deserializeResponse(responseBody, headers) {
let contentType = headers['content-type'];
if (!contentType) {
throw new Error('HttpRequest does not have Content-Type header set');
}
// Forcing Lowercase to ensure deserializing happens properly
contentType = contentType.toLowerCase();
let encoder = this._encoder(contentType);
if (!encoder) {
throw new Error(`Unable to deserialize response with Content-Type ${contentType}. Supported decodings are ${this.supportedEncodings()}`);
}
return encoder.decode(responseBody);
}
supportedEncodings() {
return '[' + this._encoders.map(e => e.contentType().toString()).join(', ') + ']';
}
_encoder(contentType) {
for (let i = 0; i < this._encoders.length; i++) {
let enc = this._encoders[i];
if (enc.contentType().test(contentType)) {
return enc;
}
}
return null;
}
}
module.exports = {Encoder: Encoder};