UNPKG

yog-ral

Version:

node-ral with mcpack and nshead

74 lines (64 loc) 1.74 kB
/* * fis * http://fis.baidu.com/ * 2014/8/14 */ 'use strict'; var Converter = require('node-ral').Converter; var logger = require('node-ral').Logger('McPackConverter'); var util = require('util'); var mcpack; var iconv = require('iconv-lite'); try { mcpack = require('@baidu/mcpack'); } catch (e) { logger.warning('mcpack module load failed'); } function McPackConverter() { Converter.call(this); } util.inherits(McPackConverter, Converter); McPackConverter.prototype.unpack = function (config, data) { try { if (!mcpack) { throw new Error('mcpack is not ready'); } if (!data) { throw new Error('invalid data data=' + data); } var obj = mcpack.decode(data, { encoding: config.encoding }); logger.trace('unpack mcpack data succ ServiceID=' + config.serviceID); return obj; } catch (ex) { logger.notice('unpack mcpack data failed ServiceID=' + config.serviceID); throw ex; } }; McPackConverter.prototype.pack = function (config, data) { data = data || {}; var buffer; try { if (!mcpack) { throw new Error('mcpack is not ready'); } //check if encoding is supported iconv.getCodec(config.encoding); buffer = mcpack.encode(data, { encoding: config.encoding }); } catch (e) { logger.notice('pack json data failed data=' + data + ' ServiceID=' + config.serviceID); throw e; } logger.trace('pack json data succ ServiceID=' + config.serviceID); return buffer; }; McPackConverter.prototype.getName = function () { return 'mcpack2'; }; module.exports = McPackConverter;