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

index.js 2.5KB

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