cookies.js 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. var optional = require('./optional')
  2. , tough = optional('tough-cookie')
  3. , Cookie = tough && tough.Cookie
  4. , CookieJar = tough && tough.CookieJar
  5. ;
  6. exports.parse = function(str) {
  7. if (str && str.uri) str = str.uri
  8. if (typeof str !== 'string') throw new Error("The cookie function only accepts STRING as param")
  9. if (!Cookie) {
  10. return null;
  11. }
  12. return Cookie.parse(str)
  13. };
  14. // Adapt the sometimes-Async api of tough.CookieJar to our requirements
  15. function RequestJar() {
  16. this._jar = new CookieJar();
  17. }
  18. RequestJar.prototype.setCookie = function(cookieOrStr, uri, options) {
  19. return this._jar.setCookieSync(cookieOrStr, uri, options || {});
  20. };
  21. RequestJar.prototype.getCookieString = function(uri) {
  22. return this._jar.getCookieStringSync(uri);
  23. };
  24. RequestJar.prototype.getCookies = function(uri) {
  25. return this._jar.getCookiesSync(uri);
  26. };
  27. exports.jar = function() {
  28. if (!CookieJar) {
  29. // tough-cookie not loaded, return a stub object:
  30. return {
  31. setCookie: function(){},
  32. getCookieString: function(){},
  33. getCookies: function(){}
  34. };
  35. }
  36. return new RequestJar();
  37. };