UNPKG

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