forked from valeriangalliat/fetch-cookie
-
Notifications
You must be signed in to change notification settings - Fork 1
/
index.js
43 lines (36 loc) · 1.17 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
var denodeify = require('es6-denodeify')(Promise)
var tough = require('tough-cookie')
module.exports = function fetchCookieDecorator (fetch, jar) {
fetch = fetch || window.fetch
jar = jar || new tough.CookieJar()
var getCookieString = denodeify(jar.getCookieString.bind(jar))
var setCookie = denodeify(jar.setCookie.bind(jar))
return function fetchCookie (url, opts) {
opts = opts || {}
return getCookieString(url)
.then(function (cookie) {
return fetch(url, Object.assign(opts, {
headers: Object.assign(opts.headers || {}, (cookie ? { cookie: cookie } : {}))
}))
})
.then(function (res) {
var cookies
if (res.headers.getAll) {
// node-fetch v1
cookies = res.headers.getAll('set-cookie')
} else {
// node-fetch v2
var cookie = res.headers.get('set-cookie')
cookies = cookie && cookie.split(',') || []
}
if (!cookies.length) {
return res
}
return Promise.all(cookies.map(function (cookie) {
return setCookie(cookie, res.url)
})).then(function () {
return res
})
})
}
}