rewrite node-fetch-cookies for flumm-fetch

This commit is contained in:
2019-07-22 22:42:38 +02:00
parent ef39af34a9
commit f2ccce9d0e
5 changed files with 48 additions and 24 deletions

35
src/fetch.mjs Normal file
View File

@ -0,0 +1,35 @@
import http from "http";
import https from "https";
import url from "url";
import querystring from "querystring";
const readdata = (res, mode, data = "") => new Promise((resolve, reject) => res
.setEncoding("utf8")
.on("data", chunk => data += chunk)
.on("end", () => {
switch(mode) {
case "text": resolve(data); break;
case "json": try { resolve(JSON.parse(data)); } catch(err) { reject(data); } break;
case "buffer": resolve(new Buffer.from(data)); break;
default: reject("lol no D:"); break;
}
}));
export default (a, options = {}, link = url.parse(a), body = "") => new Promise((resolve, reject) => {
options = {...{ hostname: link.hostname, path: link.path, method: "GET" }, ...options};
if(options.method === "POST") {
body = querystring.stringify(options.body);
delete options.body;
options.headers = {...options.headers, ...{
"Content-Type": "application/x-www-form-urlencoded",
"Content-Length": Buffer.byteLength(body)
}};
}
(link.protocol === "https:"?https:http).request(options, res => resolve({
body: res,
headers: res.headers,
text: () => readdata(res, "text"),
json: () => readdata(res, "json"),
buffer: () => readdata(res, "buffer")
})).on("error", err => reject(err)).end(body);
});

View File

@ -1,4 +1,4 @@
import fetch from "node-fetch";
import fetch from "./fetch";
import CookieJar from "./cookie-jar";
import Cookie from "./cookie";
@ -35,8 +35,7 @@ async function cookieFetch(cookieJars, url, options) {
options.headers.cookie = cookies.slice(0, -2);
}
const result = await fetch(url, options);
// i cannot use headers.get() here because it joins the cookies to a string
cookies = result.headers[Object.getOwnPropertySymbols(result.headers)[0]]["set-cookie"];
cookies = result.headers["set-cookie"]);
if(cookies && cookieJars) {
if(Array.isArray(cookieJars)) {
cookieJars.forEach(jar => {