UNPKG

fattura24

Version:

Fattura24 nodejs SDK

257 lines (212 loc) 6.17 kB
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); exports.Fattura24 = undefined; var _xmlJs = require('xml-js'); var _xmlJs2 = _interopRequireDefault(_xmlJs); var _https = require('https'); var _https2 = _interopRequireDefault(_https); var _querystring = require('querystring'); var _querystring2 = _interopRequireDefault(_querystring); var _routes = require('./constants/routes'); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } /** * An API client for Fattura24 * * @example * var fattura24 = new Fattura24({ version: '0.3', apiKey: 'AiThae5peeph9aGhie1keeX9thuse1sh' }); * fattura24.posts({ * CustomerName: 'MARIO ROSSI', * CustomerAddress: 'Via Alberti 8', * CustomerPostcode: '06122', * CustomerCity: 'Perugia', * CustomerProvince: 'PG', * CustomerCountry: '', * CustomerFiscalCode: 'MARROS66C44G217W', * CustomerVatCode: '03912377542', * CustomerCellPhone: '335123456789', * CustomerEmail: 'info@rossi.it' * }).then(function( posts ) { * console.log( posts ); * }).catch(function( error ) { * console.error( error ); * }); */ var MODULE_VERSION = '0.2.2'; var API_VERSION = '0.3'; var F24_HOST = 'www.app.fattura24.com'; /** * Fattura24 * Constructor function * * @param {object} options */ function Fattura24(options) { var _ref = options || {}, apiKey = _ref.apiKey, version = _ref.version; // Api Key is mandatory if (!apiKey) { throw new Error('You must specify an apiKey'); } // Enforce `new` if (this instanceof Fattura24 === false) { return new Fattura24(options); } // Api Key this.apiKey = apiKey; // Expose current module version this.moduleVersion = MODULE_VERSION; // Expose current api version this.apiVersion = version || API_VERSION; var handler = { /** * This function is called whenever any property on the Proxy * is called. * * @param target the "parent" object; the object the proxy * virtualizes * @param prop the property called on the Proxy */ get: function get(target, prop) { // No defined property, go on with magic method if (prop in _routes.routes) { return function () { for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) { args[_key] = arguments[_key]; } return target.makeCall.apply(target, [prop].concat(args)); }; } // This will return the property on the "parent" object return target[prop]; } }; // Using proxy we reach a behavior close to php's magic methods return new Proxy(this, handler); } /** * defaultObject * Default object where we will inject payloads */ Fattura24.prototype.defaultObject = { Fattura24: { Document: {} } }; /** * prepareXml * Prepare the data object to xml * * @param {object} data */ Fattura24.prototype.prepareXml = function prepareXml(data) { var response = void 0; try { var body = Object.assign({}, this.defaultObject); body.Fattura24.Document = data; response = _xmlJs2.default.js2xml(body, { spaces: 0, compact: true }); } catch (error) { throw new Error(error); } return response; }; /** * prepareResponse * Prepare the response object from xml * * @param {object} data */ Fattura24.prototype.prepareResponse = function prepareResponse(data) { var result = {}; try { var response = _xmlJs2.default.xml2js(data, { compact: true, ignoreComment: true, textKey: 'text' }); result = this.flatObject(response.root); } catch (error) { throw new Error(error); } return result; }; Fattura24.prototype.flatObject = function flatObject(object) { var _this = this; var flatten = {}; Object.keys(object).forEach(function (key) { if (!object[key].text && !object[key]._cdata) { // eslint-disable-line no-underscore-dangle flatten[key] = _this.flatObject(object[key]); } else if (object[key]._cdata) { // eslint-disable-line no-underscore-dangle flatten[key] = object[key]._cdata; // eslint-disable-line no-underscore-dangle } else { flatten[key] = object[key].text; } }); return flatten; }; /** * makeCall * Perform the actual call to Fattura24 * * @param {string} endpoint * @param {object} body */ Fattura24.prototype.makeCall = function makeCall(endpoint, body, category) { var self = this; var payload = { apiKey: self.apiKey }; if (typeof body === 'object') payload.xml = self.prepareXml(body); if (typeof body === 'string' && !category) payload.docId = body; if (typeof body === 'string' && category) { payload.code = body; payload.category = category; } var postData = _querystring2.default.stringify(payload); var postOptions = { host: F24_HOST, port: '443', path: `/api/v${self.apiVersion}/${_routes.routes[endpoint]}`, method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', 'Content-Length': Buffer.byteLength(postData) } }; // Set up the request return new Promise(function (resolve, reject) { var req = _https2.default.request(postOptions, function (res) { res.setEncoding('utf8'); // Response is in chunks var response = ''; res.on('data', function (chunk) { response += chunk; }); // Done res.on('end', function () { var result = self.prepareResponse(response); return resolve(result); }); // If error in response res.on('error', function (err) { return reject(err); }); }); // req error req.on('error', function (err) { return reject(err); }); // Send POST data req.write(postData); req.end(); }); }; /** * Export Fattura24 module * * aware of usage `export default` for commonjs modules * according to specs of new es6 modules `export default <Statement>` * will be available in commonjs under `require('module').default` name * it will not work as `require('module')` */ exports.Fattura24 = Fattura24;