-
Notifications
You must be signed in to change notification settings - Fork 0
/
AWSConnection.js
63 lines (52 loc) · 1.72 KB
/
AWSConnection.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
const AWS = require('aws-sdk');
const { Connection } = require('@elastic/elasticsearch');
class AWSConnection extends Connection {
async request(params, callback) {
try {
const creds = await this._getAWSCredentials();
const req = this._createRequest(params);
const { request: signedRequest } = this._signRequest(req, creds);
super.request(signedRequest, callback);
} catch (error) {
throw error;
}
}
_createRequest(params) {
const endpoint = new AWS.Endpoint(this.url.href);
let req = new AWS.HttpRequest(endpoint);
Object.assign(req, params);
req.region = AWS.config.region;
if (!req.headers) {
req.headers = {};
}
let body = params.body;
if (body) {
let contentLength = Buffer.isBuffer(body)
? body.length
: Buffer.byteLength(body);
req.headers['Content-Length'] = contentLength;
req.body = body;
}
req.headers['Host'] = endpoint.host;
return req;
}
_getAWSCredentials() {
return new Promise((resolve, reject) => {
AWS.config.getCredentials((err, creds) => {
if (err) {
if (err && err.message) {
err.message = `AWS Credentials error: ${e.message}`;
}
reject(err);
}
resolve(creds);
});
});
}
_signRequest(request, creds) {
const signer = new AWS.Signers.V4(request, 'es');
signer.addAuthorization(creds, new Date());
return signer;
}
}
module.exports = { AWSConnection };