meses-messaging
Version:
Meses messaging SDK in JavaScript
65 lines (61 loc) • 1.67 kB
JavaScript
import request from 'superagent'
class HttpClient {
/**
* Build url for GET method to be send over HTTP.
*/
static buildApiCallGetUrl(spec, url) {
let specKeys = Object.keys(spec)
if (specKeys == undefined || specKeys.length == 0) {
return url
} else {
let params = []
specKeys.forEach( function(specKey) {
if (Array.isArray(spec[specKey])) {
spec[specKey].forEach(arrVal =>{
let specValue = encodeURI(arrVal)
params.push(
specKey + '=' + specValue
)
})
} else if (spec[specKey] != undefined) {
let specValue = encodeURI(spec[specKey])
params.push(
specKey + '=' + specValue
)
}
})
return url + '?' + params.join('&')
}
}
static executeGet(apiUrl, params, context, callback) {
let apiGetUrl = this.buildApiCallGetUrl(params, apiUrl)
request.get(apiGetUrl).end((err, response) => {
if (err) {
callback(err, null)
} else if (response.body.status != 'SUCCESS') {
callback(response.body.message, null)
} else {
let data = response.body.data
callback(null, data)
}
})
}
static executePost(apiUrl, spec, context, callback) {
let apiCallSpec = { data: spec, context: {} }
request
.post(apiUrl)
.send(apiCallSpec)
.set('Content-Type', 'application/json')
.end((err, response) => {
if (err) {
callback(err, null)
} else if (response.body.status != 'SUCCESS') {
callback(response.body.message, null)
} else {
let data = response.body.data
callback(null, data)
}
})
}
}
export default HttpClient