const moment = require('moment'); const axios = require('axios'); export default class STConnector { public config: any; public models: any; private self : this; constructor(config, models) { this.config = config; this.models = models; this._getData = this._getData; this.getDataAPI = this.getDataAPI this.getDataBQI = this.getDataBQI this.getHeaders = this.getHeaders this.getHeadersMain = this.getHeadersMain return this } public getDataAPI(args) { return this._getData(this.config.api, args) } public getDataBQI(args) { return this._getData(this.config.bqi, args) } public async _getData(type, args) { const { config , models , getHeaders , getHeadersMain } = this; const Op = models.sequelize.Sequelize.Op; let tokenItem = await models.tokenStockAndTrace.findOne({ where: { token: { [Op.ne]: null } }, order: [['id', 'DESC']] }) let token = "" if (tokenItem) { token = tokenItem.token } let result = await axios .get( config.url + type + args, { headers: getHeaders(token) }) .then(function (response) { if (!Array.isArray(response.data)) throw { response: { status: 401 } }; return response.data }) .catch(function (error) { if (error.response.status === 404) { return [] } return axios.get( config.url, { headers: getHeadersMain(config) }) .then(function (response) { if (response.data.statusCode === 202) { models.tokenStockAndTrace.create({ token: response.data.token }) return axios.get( config.url + type + args, { headers: getHeaders(response.data.token) }) .then(function (response) { return response.data }) .catch(function (error) { return [] }) } else { return [] } }) .catch(function (error) { return [] }) }) return result } public getHeaders(token) { return { 'Content-Type': 'application/json', 'Authorization': 'WSSE profile=\"UsernameToken\"', 'X-WSSE': '/UsernameToken Token=\"' + token + '\"' } } public getHeadersMain( config ) { const CURRENT_DATE = moment().format('YYYY-MM-DD HH:mm:ss Z'); const NONCE = moment().format('YYMMDDHHmmss'); return { 'Authorization': 'WSSE profile=\"UsernameToken\"', 'X-WSSE': '/UsernameToken Username=\"' + config.user + '\",Password=\"' + config.pass + '\",Nonce=\"' + NONCE + '\",Created=\"' + CURRENT_DATE + '\"', } } }