Small utility for serialising JS objects to query strings for use in URLs

index.js 2.3KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. "use strict";
  2. var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) { return typeof obj; } : function (obj) { return obj && typeof Symbol === "function" && obj.constructor === Symbol ? "symbol" : typeof obj; };
  3. module.exports = {
  4. _defaults: {
  5. "warn_on_invalid": true
  6. },
  7. convert: function convert(data, options) {
  8. if ((typeof data === "undefined" ? "undefined" : _typeof(data)) === 'object') {
  9. this._merge_options(this._defaults, options);
  10. var result = "?";
  11. Object.keys(data).map(function (query_key) {
  12. var query_data = data[query_key];
  13. var query_data_processed = void 0;
  14. if (query_data === 'null') {
  15. if (options.warn_on_invalid) {
  16. console.warn("Attempted to convert null to query string!");
  17. }
  18. } else if (typeof query_data === 'number') {
  19. query_data_processed = query_data.toString();
  20. } else if (typeof query_data === 'string') {
  21. query_data_processed = query_data;
  22. } else if (typeof query_data === 'boolean') {
  23. query_data_processed = query_data.toString();
  24. } else if ((typeof query_data === "undefined" ? "undefined" : _typeof(query_data)) === 'object') {
  25. query_data_processed = JSON.stringify(query_data);
  26. } else if (typeof query_data === 'undefined') {
  27. if (options.warn_on_invalid) {
  28. console.warn("Attempted to convert undefined to query string!");
  29. }
  30. } else {
  31. if (options.warn_on_invalid) {
  32. console.warn("Attempted to convert function or symbol to query string!");
  33. }
  34. }
  35. if (query_data_processed !== 'undefined') {
  36. var append = query_key + "=" + encodeURIComponent(query_data_processed) + "&";
  37. result += append;
  38. }
  39. });
  40. return result.substring(0, result.length - 1);
  41. } else {
  42. if (options.warn_on_invalid) {
  43. console.warn("Attempted to convert non-object to query string!");
  44. return "";
  45. }
  46. }
  47. },
  48. _merge_options: function _merge_options(obj1, obj2) {
  49. var obj3 = {};
  50. Object.keys(obj1).map(function (attrname) {
  51. obj3[attrname] = obj1[attrname];
  52. });
  53. Object.keys(obj2).map(function (attrname) {
  54. obj3[attrname] = obj2[attrname];
  55. });
  56. return obj3;
  57. }
  58. };