use a global cookie jar instead of specifying the cookie jar every time

This commit is contained in:
jkhsjdhjs 2019-07-22 23:22:53 +02:00
parent f2ccce9d0e
commit f75cb67979
Signed by: jkhsjdhjs
GPG Key ID: BAC6ADBAB7D576CC

View File

@ -2,28 +2,14 @@ import fetch from "./fetch";
import CookieJar from "./cookie-jar"; import CookieJar from "./cookie-jar";
import Cookie from "./cookie"; import Cookie from "./cookie";
async function cookieFetch(cookieJars, url, options) { const cookieJar = new CookieJar("rw");
export default async function cookieFetch(url, options) {
let cookies = ""; let cookies = "";
if(cookieJars) { cookieJar.forEach(c => {
if(Array.isArray(cookieJars) && cookieJars.every(c => c instanceof CookieJar)) {
cookieJars.forEach(jar => {
if(!jar.flags.includes("r"))
return;
jar.forEach(c => {
if(c.isValidForRequest(url)) if(c.isValidForRequest(url))
cookies += c.serialize() + "; "; cookies += c.serialize() + "; ";
}); });
});
}
else if(cookieJars instanceof CookieJar && cookieJars.flags.includes("r")) {
cookieJars.forEach(c => {
if(c.isValidForRequest(url))
cookies += c.serialize() + "; ";
});
}
else
throw new TypeError("First paramter is neither a cookie jar nor an array of cookie jars!");
}
if(cookies.length !== 0) { if(cookies.length !== 0) {
if(!options) { if(!options) {
options = { options = {
@ -35,20 +21,8 @@ async function cookieFetch(cookieJars, url, options) {
options.headers.cookie = cookies.slice(0, -2); options.headers.cookie = cookies.slice(0, -2);
} }
const result = await fetch(url, options); const result = await fetch(url, options);
cookies = result.headers["set-cookie"]); cookies = result.headers["set-cookie"];
if(cookies && cookieJars) { if(cookies)
if(Array.isArray(cookieJars)) { cookies.forEach(c => cookieJar.addCookie(c, url));
cookieJars.forEach(jar => {
if(!jar.flags.includes("w"))
return;
cookies.forEach(c => jar.addCookie(c, url));
});
}
else if(cookieJars.flags.includes("w")) {
cookies.forEach(c => cookieJars.addCookie(c, url));
}
}
return result; return result;
} }
export {cookieFetch as fetch, CookieJar, Cookie};