const Promise = require('bluebird'); const queryString = require('qs'); const xml2js = require('xml2js').parseString; const errors = require('../errors') ,AppError = errors.AppError ,MalResultError = errors.MalResultError; /** Random tools that have nowhere else to go */ export class Tools { constructor() { } /** * [getJSONParser pick the approriate JSON parser based on the content-type, dafault to dummy parser (return data as its)] * @type {[type]} */ public getJSONParser = (contentType, cb = undefined) => { const my = this; return new Promise(function (resolve, reject) { let parser = my.defaultParser; if(!contentType) return reject(new AppError("No Content Type")); if(contentType.indexOf("text/xml") > -1) parser = my.xmlJSONParser; else if(contentType.indexOf("application/json") > -1) parser = my.jsonParser; else if(contentType.indexOf("application/x-www-form-urlencoded") > -1) parser = my.formUrlEncodedJSONParser; return resolve(parser); }).nodeify(cb); } /** * [defaultParser default parsing data toString] * @type {[type]} */ private defaultParser = (data, cb = undefined) => { return new Promise((resolve, reject) => { try{ const parsedData = data.toString(); return resolve(parsedData); }catch(err){ return reject(new MalResultError("Unable to parse results: " + err.mesage)); } }).nodeify(cb); } /** * [xmlJSONParser parse JSON for content-type text/xml] * @return Promise resolving JSON parsed data * or reject with AppError MalResult when fail to parse * Support callback fallback */ private xmlJSONParser = (data, cb = undefined) => { return new Promise((resolve, reject) => { xml2js(data, function (err, finalVal) { if(err) { return reject(new MalResultError("Unable to parse results: " + err.mesage)); } resolve(finalVal); }) }).nodeify(cb); } /** * [jsonParser parse JSON for content-type application/json] * @return Promise resolving JSON parsed data * or reject with AppError MalResult when fail to parse * Support callback fallback */ private jsonParser = (data, cb = undefined) => { return new Promise((resolve, reject) => { try{ const parsedData = JSON.parse(data) return resolve(parsedData); }catch(err){ return reject(new MalResultError("Unable to parse results: " + err.mesage)); } }).nodeify(cb); } /** * [formUrlEncodedJSONParser parse JSON for content-type application/x-www-form-urlencoded] * @return Promise resolving JSON parsed data * or reject with AppError MalResult when fail to parse * Support callback fallback */ private formUrlEncodedJSONParser = (data, cb = undefined) => { return new Promise((resolve, reject) => { try{ const parsedData = queryString.parse(data) return resolve(parsedData); }catch(err){ return reject(new MalResultError("Unable to parse results: " + err.mesage)); } }).nodeify(cb); } }