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

index.js 2.1KB

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