@zephr/node-sdk
Version:
Zephr Node.js SDK
83 lines (71 loc) • 2.2 kB
JavaScript
const axios = require('axios')
const HmacSigner = require('./HmacSigner')
class AdminApiClient {
constructor(accessKey, secretKey, tenant, environment) {
this.accessKey = accessKey
this.secretKey = secretKey
this.url = `https://${tenant}.admin${!!environment ? `.${environment}.` : '.'}blaize.io`
}
overrideBaseUrl(url) {
this.url = url
return this
}
get(path, headers) {
return httpRequest(this.accessKey, this.secretKey, this.url, path, 'GET', headers)
}
post(path, headers, body) {
return httpRequest(this.accessKey, this.secretKey, this.url, path, 'POST', headers, body)
}
put(path, headers, body) {
return httpRequest(this.accessKey, this.secretKey, this.url, path, 'PUT', headers, body)
}
delete(path, headers) {
return httpRequest(this.accessKey, this.secretKey, this.url, path, 'DELETE', headers)
}
}
function httpRequest(accessKey, secretKey, host, path, method, headers, data) {
if (data && typeof data !== 'string') {
data = JSON.stringify(data)
if (!headers['Content-Type'])
headers = {
...headers,
'Content-Type': 'application/json',
}
}
var query = ''
var startQuery = path.indexOf('?')
if (startQuery !== -1) {
query = path.substring(startQuery + 1)
path = path.substring(0, startQuery)
}
const config = {
url: host + path + (query ? `?${query}` : ''),
method,
data,
headers: {
authorization: HmacSigner.buildAuthHeader(accessKey, secretKey, path.replace(/\?.*/, ''), query, method, data),
...headers,
},
}
return axios(config)
.then((response) => response.data)
.catch((error) => {
return Promise.reject(
new Error(
`Zephr Admin API request (${method} ${path}) failed with status code ${
error.response.status
}:\n${JSON.stringify(error.response.data)}${data ? `\nRequest Body: ${JSON.stringify(data)}` : ''}`,
{
cause: error,
}
)
)
})
}
function build(accessKey, secretKey, tenant, environment) {
return new AdminApiClient(accessKey, secretKey, tenant, environment)
}
module.exports = {
build,
HmacSigner,
}