- Replace `src/Cookie.ts` with direct `Browser` and `Page` management in `Bandai` class. - Implement lazy initialization for the browser instance to avoid redundant startup costs. - Update `loginBandai` to accept an existing `browserAndPage` context rather than creating a new one. - Improve login status verification by checking for the login button ID instead of generic text. - Add `getCartList` to parse cart HTML using `cheerio` and `set-cookie-parser`. - Add `order` and `open` methods to navigate and interact with specific URLs via Puppeteer. - Update `puppeteer-utils` to save cookies automatically on page load. - Remove legacy `src/Cookie.ts` and `src/Cookie.ts` usage. - Bump `set-cookie-parser` dependency to `^3.1.0`.
57 lines
1.5 KiB
TypeScript
57 lines
1.5 KiB
TypeScript
import type { Cookie } from "puppeteer";
|
|
import { getBandaiRawCookieRedisKey, redis } from "./utils";
|
|
import { parseSetCookie } from "set-cookie-parser";
|
|
|
|
export default class BandaiCookie {
|
|
#cookieMap = new Map<string, Cookie>();
|
|
|
|
#id: string;
|
|
|
|
constructor(email: string) {
|
|
this.#id = email;
|
|
}
|
|
|
|
async init() {
|
|
const cache = await redis.get(getBandaiRawCookieRedisKey(this.#id));
|
|
if (!cache) return;
|
|
const cookies: Cookie[] = JSON.parse(cache);
|
|
cookies.map(cookie => {
|
|
this.#cookieMap.set(cookie.name, cookie);
|
|
});
|
|
}
|
|
|
|
updateCookie(headers: Headers) {
|
|
const setCookie = headers.getSetCookie();
|
|
const cookies = parseSetCookie(setCookie);
|
|
cookies.forEach(cookie => {
|
|
const value = this.#cookieMap.get(cookie.name);
|
|
if (!value) {
|
|
console.debug('Cookie %s not found', cookie.name);
|
|
return;
|
|
}
|
|
this.#cookieMap.set(cookie.name, {
|
|
...value,
|
|
value: cookie.value,
|
|
domain: cookie.domain ?? value.domain,
|
|
expires: cookie.expires?.getTime() || value.expires,
|
|
});
|
|
});
|
|
}
|
|
|
|
getCookie() {
|
|
return this.#cookieMap.values()
|
|
.toArray()
|
|
.map((v) => `${v.name}=${v.value}`)
|
|
.join('; ');
|
|
}
|
|
|
|
getRawCookie(): Cookie[] {
|
|
const cookies = this.#cookieMap.values().toArray();
|
|
return cookies;
|
|
}
|
|
|
|
async saveCookie() {
|
|
const cookieString = JSON.stringify(this.#cookieMap.values().toArray());
|
|
await redis.set(getBandaiRawCookieRedisKey(this.#id), cookieString);
|
|
}
|
|
} |