api-client/session: pull URL from client
This commit is contained in:
parent
d201deb60a
commit
d3e278660d
1 changed files with 13 additions and 6 deletions
|
@ -1,29 +1,32 @@
|
|||
import { CobaltSession, CobaltResponseType, CobaltSessionResponse } from "../types/response";
|
||||
import { CobaltReachabilityError } from "../types/errors";
|
||||
import type { TurnstileObject } from "turnstile-types";
|
||||
import { CobaltAPIClient } from "../types/interface";
|
||||
|
||||
const currentTime = () => Math.floor(new Date().getTime() / 1000);
|
||||
const EXPIRY_THRESHOLD_SECONDS = 2;
|
||||
|
||||
export default class CobaltSessionHandler {
|
||||
#baseURL: string;
|
||||
#client: CobaltAPIClient;
|
||||
#turnstile: TurnstileObject;
|
||||
#session: CobaltSession | undefined;
|
||||
|
||||
constructor(baseURL: string, turnstile: TurnstileObject) {
|
||||
this.#baseURL = baseURL;
|
||||
constructor(client: CobaltAPIClient, turnstile: TurnstileObject) {
|
||||
this.#client = client;
|
||||
this.#turnstile = turnstile;
|
||||
}
|
||||
|
||||
async #requestSession(): Promise<CobaltSessionResponse> {
|
||||
const endpoint = new URL('/session', this.#baseURL);
|
||||
const baseURL = this.#client.getBaseURL();
|
||||
if (!baseURL) throw "baseURL is undefined";
|
||||
|
||||
const endpoint = new URL('/session', baseURL);
|
||||
const response = await fetch(endpoint, {
|
||||
method: 'POST',
|
||||
redirect: 'manual',
|
||||
signal: AbortSignal.timeout(10000),
|
||||
headers: {
|
||||
'cf-turnstile-response': this.#turnstile.getResponse('turnstile-widget')
|
||||
'cf-turnstile-response': this.#turnstile.getResponse('#turnstile-widget')
|
||||
}
|
||||
})
|
||||
.then(r => r.json())
|
||||
|
@ -46,7 +49,7 @@ export default class CobaltSessionHandler {
|
|||
}
|
||||
}
|
||||
|
||||
this.#turnstile.reset('turnstile-widget');
|
||||
this.#turnstile.reset('#turnstile-widget');
|
||||
|
||||
return response;
|
||||
}
|
||||
|
@ -55,6 +58,10 @@ export default class CobaltSessionHandler {
|
|||
return this.#session && this.#session.exp - EXPIRY_THRESHOLD_SECONDS > currentTime();
|
||||
}
|
||||
|
||||
reset() {
|
||||
this.#session = undefined;
|
||||
}
|
||||
|
||||
async getSession(): Promise<CobaltSessionResponse> {
|
||||
if (this.hasSession()) {
|
||||
return this.#session!;
|
||||
|
|
Loading…
Reference in a new issue