cbp-lib
Version:
Libraries for cbp
71 lines (65 loc) • 2 kB
JavaScript
import axios from 'axios'
import { ArgumentError } from './custom-error';
/**
* Helper function:
* Make a call to the specified requestPath, and when the
* results are done, invoke the callback.
*
* @param {String} requestMethod - the HTTP method (GET, POST, etc)
* @param {String} requestPath - the request path (e.g., /lists, /items, etc)
* @param {String} postData - a JSON string (must be well-formed) containing any
* data that is to be sent in the request body
* @param {Object} headers - additional HTTP headers
*
*/
export const httpRequest = (requestMethod, requestPath, postData=null, headers) => {
let options = ''
if (requestMethod == 'GET') {
options = {
...headers
}
return new Promise((resolve, reject) => {
axios.get(requestPath, options)
.then(result => {
resolve(result.data)
})
.catch(error => {
reject(error)
})
})
}
else {
options = {
method: requestMethod,
url: requestPath,
data: postData,
...headers
}
return new Promise((resolve, reject) => {
axios.request(options)
.then(result => {
resolve(result.data)
})
.catch(error => {
reject(error)
})
})
}
}
export const authBearerHeader = (token) => {
if (!token) {
throw new ArgumentError('missing token')
}
return {
"Authorization": `Bearer ${token}`
}
}
export const authBasicHeader = (username, password) => {
if (!client_id && !client_secret) {
throw new ArgumentError('missing client_id & client_secret')
}
return {
"Authorization": `Basic ${Buffer.from(`${client_id}:${client_secret}`).toString('base64')}`,
"content-type": "application/json"
}
}