static-xform.js 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. "use strict";
  2. const BaseXform = require('./base-xform');
  3. const XmlStream = require('../../utils/xml-stream');
  4. // const model = {
  5. // tag: 'name',
  6. // $: {attr: 'value'},
  7. // c: [
  8. // { tag: 'child' }
  9. // ],
  10. // t: 'some text'
  11. // };
  12. function build(xmlStream, model) {
  13. xmlStream.openNode(model.tag, model.$);
  14. if (model.c) {
  15. model.c.forEach(child => {
  16. build(xmlStream, child);
  17. });
  18. }
  19. if (model.t) {
  20. xmlStream.writeText(model.t);
  21. }
  22. xmlStream.closeNode();
  23. }
  24. class StaticXform extends BaseXform {
  25. constructor(model) {
  26. super();
  27. // This class is an optimisation for static (unimportant and unchanging) xml
  28. // It is stateless - apart from its static model and so can be used as a singleton
  29. // Being stateless - it will only track entry to and exit from it's root xml tag during parsing and nothing else
  30. // Known issues:
  31. // since stateless - parseOpen always returns true. Parent xform must know when to start using this xform
  32. // if the root tag is recursive, the parsing will behave unpredictably
  33. this._model = model;
  34. }
  35. render(xmlStream) {
  36. if (!this._xml) {
  37. const stream = new XmlStream();
  38. build(stream, this._model);
  39. this._xml = stream.xml;
  40. }
  41. xmlStream.writeXml(this._xml);
  42. }
  43. parseOpen() {
  44. return true;
  45. }
  46. parseText() {}
  47. parseClose(name) {
  48. switch (name) {
  49. case this._model.tag:
  50. return false;
  51. default:
  52. return true;
  53. }
  54. }
  55. }
  56. module.exports = StaticXform;
  57. //# sourceMappingURL=static-xform.js.map