Skip to content

Instantly share code, notes, and snippets.

@rodrigonehring
Created January 14, 2021 17:16
Show Gist options
  • Save rodrigonehring/30a7b9b57093450cbb5651accfc7e49e to your computer and use it in GitHub Desktop.
Save rodrigonehring/30a7b9b57093450cbb5651accfc7e49e to your computer and use it in GitHub Desktop.
Connect aws elasticsearch
import * as AWS from 'aws-sdk'
import { Connection } from '@elastic/elasticsearch'
class AwsConnector extends Connection {
async request(params, callback) {
const creds = await this.getAWSCredentials()
const req = this.createRequest(params)
const { request: signedRequest } = this.signRequest(req, creds)
super.request(signedRequest, callback)
}
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
req.path += '/?' + req.querystring
delete req.querystring
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: ${err.message}`
}
reject(err)
}
resolve(creds)
})
})
}
signRequest(request, creds) {
const signer = new AWS.Signers.V4(request, 'es')
signer.addAuthorization(creds, new Date())
return signer
}
}
export default AwsConnector
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment