Created
January 24, 2019 16:07
-
-
Save noctifer20/da8013bbb2cbcb9230ea89c145bec0e5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* ARCA API BaseController. | |
*/ | |
import rp from 'request-promise'; | |
import qs from 'qs'; | |
export default class BaseController { | |
/** | |
* @param {Object} config - API configs. | |
* @param {String} config.mainUrl - API main url. | |
* @param {String} config.userName - API main username. | |
* @param {String} config.password - API main password. | |
*/ | |
constructor(config) { | |
this.mainUrl = config.mainUrl; | |
this.userName = config.userName; | |
this.password = config.password; | |
} | |
/** | |
* Building url for API call. | |
* | |
* @param {String} url - API Main Url. | |
* @param {String} action - API action. | |
* @param {Object} params - Params. | |
* | |
* @returns {String} - Returns constructed url. | |
*/ | |
buildUrl(url, action, params) { | |
return `${url}/${action}.do?${qs.stringify(params)}`; | |
} | |
/** | |
* Request To ARCA API. | |
* | |
* @param {String} action - Action Name. | |
* @param {Object} body - Request Body. | |
* @param {String} method - Request Method. | |
* @returns {Promise<*>} - Returns API Response. | |
*/ | |
async request(action, body, method = 'GET') { | |
try { | |
body = { | |
userName: this.userName, | |
password: this.password, | |
...body | |
}; | |
// Get request url for ARCA API call. | |
const uri = this.buildUrl(this.mainUrl, action, body); | |
//Calling hook BEFORE_REQUEST | |
this.beforeRequest(action, method, body); | |
// Combining all in the request. | |
let response = await rp({ | |
uri, | |
method | |
}); | |
response = JSON.parse(response); | |
// Checking for every possible error -_- GOD DAMN ARCA | |
if ( | |
(response.errorCode && response.errorCode !== '0') || | |
(response.ErrorCode && response.ErrorCode !== '0') | |
) { | |
return new Error(response); | |
} | |
//Calling hook AFTER_REQUEST | |
this.afterRequest(response); | |
return { | |
...response | |
}; | |
} catch (e) { | |
throw e; | |
} | |
} | |
/** | |
* Event triggered before API call. | |
*/ | |
beforeRequest() {} | |
/** | |
* Event triggered after API call. | |
*/ | |
afterRequest() {} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment