index.js 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. 'use strict';
  2. var url = require('url');
  3. //Parse method copied from https://github.com/brianc/node-postgres
  4. //Copyright (c) 2010-2014 Brian Carlson (brian.m.carlson@gmail.com)
  5. //MIT License
  6. //parses a connection string
  7. function parse(str) {
  8. var config;
  9. //unix socket
  10. if(str.charAt(0) === '/') {
  11. config = str.split(' ');
  12. return { host: config[0], database: config[1] };
  13. }
  14. // url parse expects spaces encoded as %20
  15. if(/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str)) {
  16. str = encodeURI(str).replace(/\%25(\d\d)/g, "%$1");
  17. }
  18. var result = url.parse(str, true);
  19. config = {};
  20. if (result.query.application_name) {
  21. config.application_name = result.query.application_name;
  22. }
  23. if (result.query.fallback_application_name) {
  24. config.fallback_application_name = result.query.fallback_application_name;
  25. }
  26. config.port = result.port;
  27. if(result.protocol == 'socket:') {
  28. config.host = decodeURI(result.pathname);
  29. config.database = result.query.db;
  30. config.client_encoding = result.query.encoding;
  31. return config;
  32. }
  33. config.host = result.hostname;
  34. // result.pathname is not always guaranteed to have a '/' prefix (e.g. relative urls)
  35. // only strip the slash if it is present.
  36. var pathname = result.pathname;
  37. if (pathname && pathname.charAt(0) === '/') {
  38. pathname = result.pathname.slice(1) || null;
  39. }
  40. config.database = pathname && decodeURI(pathname);
  41. var auth = (result.auth || ':').split(':');
  42. config.user = auth[0];
  43. config.password = auth.splice(1).join(':');
  44. var ssl = result.query.ssl;
  45. if (ssl === 'true' || ssl === '1') {
  46. config.ssl = true;
  47. }
  48. return config;
  49. }
  50. module.exports = {
  51. parse: parse
  52. };