index.js 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  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. //unix socket
  9. if(str.charAt(0) === '/') {
  10. var config = str.split(' ');
  11. return { host: config[0], database: config[1] };
  12. }
  13. // url parse expects spaces encoded as %20
  14. var result = url.parse(/ |%[^a-f0-9]|%[a-f0-9][^a-f0-9]/i.test(str) ? encodeURI(str).replace(/\%25(\d\d)/g, "%$1") : str, true);
  15. var config = result.query;
  16. for (var k in config) {
  17. if (Array.isArray(config[k])) {
  18. config[k] = config[k][config[k].length-1];
  19. }
  20. }
  21. config.port = result.port;
  22. if(result.protocol == 'socket:') {
  23. config.host = decodeURI(result.pathname);
  24. config.database = result.query.db;
  25. config.client_encoding = result.query.encoding;
  26. return config;
  27. }
  28. config.host = result.hostname;
  29. // result.pathname is not always guaranteed to have a '/' prefix (e.g. relative urls)
  30. // only strip the slash if it is present.
  31. var pathname = result.pathname;
  32. if (pathname && pathname.charAt(0) === '/') {
  33. pathname = result.pathname.slice(1) || null;
  34. }
  35. config.database = pathname && decodeURI(pathname);
  36. var auth = (result.auth || ':').split(':');
  37. config.user = auth[0];
  38. config.password = auth.splice(1).join(':');
  39. if (config.ssl === 'true' || config.ssl === '1') {
  40. config.ssl = true;
  41. }
  42. return config;
  43. }
  44. module.exports = parse;
  45. parse.parse = parse;