salix/back/models/mrw-config.js

36 lines
1.2 KiB
JavaScript

module.exports = Self => {
require('../methods/mrw-config/createShipment')(Self);
require('../methods/mrw-config/getLabel')(Self);
require('../methods/mrw-config/cancelShipment')(Self);
const fs = require('fs');
const ejs = require('ejs');
const UserError = require('vn-loopback/util/user-error');
const {DOMParser} = require('xmldom');
const axios = require('axios');
Self.getConfig = async function() {
const mrw = await Self.app.models.MrwConfig.findOne(null);
if (!mrw) throw new UserError(`MRW service is not configured`);
return mrw;
};
Self.getTextByTag = function(xmlDoc, tag) {
return xmlDoc?.getElementsByTagName(tag)[0]?.textContent;
};
Self.sendXmlDoc = async function(path, params, contentType) {
const parser = new DOMParser();
const xmlTemplate = fs.readFileSync(path, 'utf-8');
const renderedTemplate = ejs.render(xmlTemplate, params);
const data = await axios.post(params.mrw.url, renderedTemplate, {
headers: {
'Content-Type': `${contentType}; charset=utf-8`
}
});
return parser.parseFromString(data.data, 'text/xml');
};
};