-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.js
50 lines (43 loc) · 1.14 KB
/
index.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
'use strict'
const { URL } = require('url')
const AWS = require('aws-sdk')
const aws4 = require('aws4')
const axios = require('axios')
module.exports = function signedAxios (request) {
const { headers = {} } = request
const { host, pathname, search } = new URL(request.url)
const [, hostHeader] =
Object.entries(headers).find(
([prop, value]) => prop.toLowerCase() === 'host'
) || []
request.host = hostHeader || host
request.path = pathname + search
let body = request.data
if (body) {
if (typeof body === 'object') {
body = JSON.stringify(body)
request.data = body
request.headers = request.headers || {}
request.headers['Content-Type'] = 'application/json'
}
}
const { secretAccessKey, accessKeyId, sessionToken } = AWS.config.credentials || {}
const signedRequest = aws4.sign(
{
...request,
body
},
{
secretAccessKey,
accessKeyId,
sessionToken
}
)
if (signedRequest.headers) {
if (!hostHeader) {
delete signedRequest.headers.Host
delete signedRequest.headers['Content-Length']
}
}
return axios.request(signedRequest)
}