api.js 1.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. 'use strict';
  2. const encoders = require('./encoders');
  3. const decoders = require('./decoders');
  4. const inherits = require('inherits');
  5. const api = exports;
  6. api.define = function define(name, body) {
  7. return new Entity(name, body);
  8. };
  9. function Entity(name, body) {
  10. this.name = name;
  11. this.body = body;
  12. this.decoders = {};
  13. this.encoders = {};
  14. }
  15. Entity.prototype._createNamed = function createNamed(Base) {
  16. const name = this.name;
  17. function Generated(entity) {
  18. this._initNamed(entity, name);
  19. }
  20. inherits(Generated, Base);
  21. Generated.prototype._initNamed = function _initNamed(entity, name) {
  22. Base.call(this, entity, name);
  23. };
  24. return new Generated(this);
  25. };
  26. Entity.prototype._getDecoder = function _getDecoder(enc) {
  27. enc = enc || 'der';
  28. // Lazily create decoder
  29. if (!this.decoders.hasOwnProperty(enc))
  30. this.decoders[enc] = this._createNamed(decoders[enc]);
  31. return this.decoders[enc];
  32. };
  33. Entity.prototype.decode = function decode(data, enc, options) {
  34. return this._getDecoder(enc).decode(data, options);
  35. };
  36. Entity.prototype._getEncoder = function _getEncoder(enc) {
  37. enc = enc || 'der';
  38. // Lazily create encoder
  39. if (!this.encoders.hasOwnProperty(enc))
  40. this.encoders[enc] = this._createNamed(encoders[enc]);
  41. return this.encoders[enc];
  42. };
  43. Entity.prototype.encode = function encode(data, enc, /* internal */ reporter) {
  44. return this._getEncoder(enc).encode(data, reporter);
  45. };