index.js 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980
  1. (function () {
  2. var _ = require('underscore');
  3. function sanitize_input(input) {
  4. // http://www.postgresql.org/docs/9.0/static/sql-syntax-lexical.html [4.1.2.1-4.1.2.2]
  5. // single quotes (') must be replaced with double single quotes ('')
  6. input = input.replace(/'/g, '\'\'');
  7. // backslashes (\) must be replaced with double backslashes (\\)
  8. input = input.replace(/\\/g, '\\\\');
  9. // double quotes (") must be replaced with escaped quotes (\\")
  10. input = input.replace(/"/g, '\\"');
  11. return input;
  12. }
  13. function to_string(input, sanitize) {
  14. switch(typeof input) {
  15. case 'boolean':
  16. case 'number':
  17. case 'object':
  18. return String(input);
  19. case 'string':
  20. return sanitize ? sanitize_input(input) : input;
  21. default:
  22. return '';
  23. }
  24. }
  25. module.exports = function (options) {
  26. options = _.defaults({}, options, { sanitize: false });
  27. return {
  28. stringify: function (data, callback) {
  29. var hstore = Object.keys(data).map(function (key) {
  30. if (data[key] === null) {
  31. return '"'+to_string(key, options.sanitize)+'"=>NULL';
  32. } else {
  33. return '"'+to_string(key, options.sanitize)+'"=>"'+to_string(data[key], options.sanitize)+'"';
  34. }
  35. });
  36. var joined = hstore.join();
  37. if (!callback || callback === null) return joined;
  38. callback(joined);
  39. },
  40. parse: function(string, callback) {
  41. var result = {},
  42. //using [\s\S] to match any character, including line feed and carriage return,
  43. r = /(["])(?:\\\1|\\\\|[\s\S])*?\1|NULL/g,
  44. matches = string.match(r),
  45. i,
  46. l,
  47. clean = function (value) {
  48. // Remove leading double quotes
  49. value = value.replace(/^\"|\"$/g, "");
  50. // Unescape quotes
  51. value = value.replace(/\\"/g, "\"");
  52. //Unescape backslashes
  53. value = value.replace(/\\\\/g,"\\");
  54. //Unescape single quotes
  55. value = value.replace(/''/g,"'");
  56. return value;
  57. };
  58. if(matches) {
  59. for (i = 0, l = matches.length; i < l; i+= 2) {
  60. if (matches[i] && matches[i + 1]) {
  61. var key = clean(matches[i]);
  62. var value = matches[i + 1];
  63. result[key] = value=="NULL"?null:clean(value);
  64. }
  65. }
  66. }
  67. if (!callback || callback === null) return result;
  68. callback(result);
  69. }
  70. };
  71. };
  72. })();