cea-core
Version:
basic cea api
66 lines (65 loc) • 2.02 kB
JavaScript
import fetch from "node-fetch";
import { cookieParse, cookieStr } from "./cookie-helper.js";
export default class FetchWithCookie {
constructor(headers) {
this.headers = headers;
}
async get(url, options = {}) {
return await this.fetch(url, options);
}
async post(url, options) {
options.isPost = true;
return await this.fetch(url, options);
}
async follow(options) {
let res;
if (this.redirectUrl) {
res = await this.fetch(this.redirectUrl, options || {});
await this.follow(options || {});
}
res = this.lastRes;
return new Promise((resolve) => resolve(res));
}
async fetch(url, options) {
const { host, origin } = new URL(url);
const { type, body } = options;
const { headers } = this;
headers.origin = origin;
headers.referer = origin;
headers.host = host;
headers.cookie = this.cookieMap ? cookieStr(host, this.cookieMap) : "";
headers["Content-Type"] = type === "form" ? "application/x-www-form-urlencoded" : "application/json";
if (!type && headers["Content-Type"]) {
Reflect.deleteProperty(headers, "Content-Type");
}
const res = await fetch(url, {
headers,
method: type ? "POST" : void 0,
body,
redirect: "manual"
}).catch(console.error);
this.lastRedirectUrl = this.redirectUrl;
this.redirectUrl = res.headers.get("location") || void 0;
this.lastRes = res;
this.updateMap(cookieParse(host, res.headers));
return res;
}
getCookieObj() {
let obj = {};
for (const [key, val] of this.cookieMap.entries()) {
obj[key] = [...val].reduce((str, e) => `${str}${e.join("=")}; `, "");
}
return obj;
}
updateMap(newMap) {
if (!this.cookieMap) {
this.cookieMap = newMap;
} else {
for (const [key, val] of newMap.entries()) {
const oldVal = this.cookieMap.get(key);
this.cookieMap.set(key, new Map(oldVal ? [...val, ...oldVal] : val));
}
}
}
}
//# sourceMappingURL=fetch-helper.js.map