UNPKG

btnexus-node

Version:
95 lines (83 loc) 2.6 kB
/** * Blackout Technologies, btnexus API * @author Marc Fiedler * @copyright 2020 Blackout Technologies, all rights reserved */ // Use Strict mode ECMA Script 5+ "use_strict"; // local imports const Api = require('./request'); // Globals const BLACKOUT_PROTOCOL_VERSION = "5.0"; module.exports = class BTRequest { /** * Make requests to Blackout Api's * @param {String} instanceUrl * @param {String} accessToken (Optional) */ constructor(instanceUrl, accessToken){ if( instanceUrl.indexOf("http") == -1 ){ // Make Protocoll optional instanceUrl = "https://"+instanceUrl } this.instanceUrl = instanceUrl; this.accessToken = accessToken; // prepare API this.api = new Api(); this.extraHeaders = []; } /** * Set extra header if needed * @param {Object} header */ setExtraHeaders(header){ this.extraHeaders.push(header); } /** * Post request to Blackout API * @param {String} intent * @param {Object} contextData * @param {Function} callback */ post(intent, contextData, callback){ // prepare contents with btHeader var data = { api: { version: BLACKOUT_PROTOCOL_VERSION, intent: intent } } // prepare HTTP Header var headers = {} if( this.accessToken != undefined ){ // if a topen is given, we are sure that it must be JSON headers["Content-Type"] = "application/json"; headers["blackout-token"] = this.accessToken; } for(var i in this.extraHeaders ){ var header = this.extraHeaders[i]; var key = Object.keys(header)[0]; headers[key] = header[key]; } // merge objects with custom content Object.assign(data, contextData); // post this.api.post(this.instanceUrl+'/api', data, {headers: headers}, (success, response, code) => { if( !success ){ callback(false, response); }else{ if( code == 200 ){ // filter for btNexus level validation if( response.success ){ callback(true, response); }else{ callback(false, response.error); } }else{ // empty contents callback(false, response); } } }); } }