serializer.js 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. 'use strict';
  2. const _ = require('lodash');
  3. const Constants = require('./constants');
  4. const defaults = {
  5. line_breaks: 'unix',
  6. keep_quotes: false,
  7. };
  8. class Serializer {
  9. constructor(options = {}) {
  10. this.options = Object.assign({}, defaults, options);
  11. }
  12. needToBeQuoted(value) {
  13. if (this.options.keep_quotes) {
  14. return false;
  15. }
  16. // wrapped with qoutes
  17. if (value.match(/^"[\s\S]*?"$/g)) {
  18. return false;
  19. }
  20. // escaped quote at the end
  21. if (value.match(/^[\s\S]*?\\"$/g)) {
  22. return true;
  23. }
  24. // ends or starts with a quote
  25. if (value.match(/^[\s\S]*?"$/g) || value.match(/^"[\s\S]*?$/g)) {
  26. return false;
  27. }
  28. return true;
  29. }
  30. serialize(content) {
  31. return _.reduce(content, (output, sectionContent, section) => {
  32. output += `[${section}]` + Constants.line_breaks[this.options.line_breaks];
  33. output += this.serializeContent(sectionContent, '');
  34. return output;
  35. }, '');
  36. }
  37. serializeContent(content, path) {
  38. return _.reduce(content, (serialized, subContent, key) => {
  39. if (_.isArray(subContent)) {
  40. for (let value of subContent) {
  41. if (this.needToBeQuoted(value)) {
  42. value = `"${value}"`;
  43. }
  44. serialized += path + (path.length > 0 ? '.' : '') + key + "[]=" + value + Constants.line_breaks[this.options.line_breaks];
  45. }
  46. }
  47. else if (_.isObject(subContent)) {
  48. serialized += this.serializeContent(subContent, path + (path.length > 0 ? '.' : '') + key);
  49. }
  50. else {
  51. if (this.needToBeQuoted(subContent)) {
  52. subContent = `"${subContent}"`;
  53. }
  54. serialized += path + (path.length > 0 ? '.' : '') + key + "=" + subContent + Constants.line_breaks[this.options.line_breaks];
  55. }
  56. return serialized;
  57. }, '');
  58. }
  59. }
  60. module.exports = Serializer;