date-xform.js 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. const BaseXform = require('../base-xform');
  2. class DateXform extends BaseXform {
  3. constructor(options) {
  4. super();
  5. this.tag = options.tag;
  6. this.attr = options.attr;
  7. this.attrs = options.attrs;
  8. this._format =
  9. options.format ||
  10. function(dt) {
  11. try {
  12. if (Number.isNaN(dt.getTime())) return '';
  13. return dt.toISOString();
  14. } catch (e) {
  15. return '';
  16. }
  17. };
  18. this._parse =
  19. options.parse ||
  20. function(str) {
  21. return new Date(str);
  22. };
  23. }
  24. render(xmlStream, model) {
  25. if (model) {
  26. xmlStream.openNode(this.tag);
  27. if (this.attrs) {
  28. xmlStream.addAttributes(this.attrs);
  29. }
  30. if (this.attr) {
  31. xmlStream.addAttribute(this.attr, this._format(model));
  32. } else {
  33. xmlStream.writeText(this._format(model));
  34. }
  35. xmlStream.closeNode();
  36. }
  37. }
  38. parseOpen(node) {
  39. if (node.name === this.tag) {
  40. if (this.attr) {
  41. this.model = this._parse(node.attributes[this.attr]);
  42. } else {
  43. this.text = [];
  44. }
  45. }
  46. }
  47. parseText(text) {
  48. if (!this.attr) {
  49. this.text.push(text);
  50. }
  51. }
  52. parseClose() {
  53. if (!this.attr) {
  54. this.model = this._parse(this.text.join(''));
  55. }
  56. return false;
  57. }
  58. }
  59. module.exports = DateXform;