-
-
Notifications
You must be signed in to change notification settings - Fork 1.2k
Expand file tree
/
Copy pathapi.ts
More file actions
60 lines (45 loc) · 1.46 KB
/
api.ts
File metadata and controls
60 lines (45 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
import { getGlobal, registerGlobal, unregisterGlobal } from "../utils/globals.js";
import { TimeoutManager } from "./types.js";
const API_NAME = "timeout";
class NoopTimeoutManager implements TimeoutManager {
abortAfterTimeout(timeoutInSeconds?: number): AbortController {
return new AbortController();
}
reset() {}
}
const NOOP_TIMEOUT_MANAGER = new NoopTimeoutManager();
export class TimeoutAPI implements TimeoutManager {
private static _instance?: TimeoutAPI;
private constructor() {}
public static getInstance(): TimeoutAPI {
if (!this._instance) {
this._instance = new TimeoutAPI();
}
return this._instance;
}
public get signal(): AbortSignal | undefined {
return this.#getManager().signal;
}
public abortAfterTimeout(timeoutInSeconds?: number): AbortController {
return this.#getManager().abortAfterTimeout(timeoutInSeconds);
}
public setGlobalManager(manager: TimeoutManager): boolean {
return registerGlobal(API_NAME, manager);
}
public disable() {
unregisterGlobal(API_NAME);
}
public reset() {
this.#getManager().reset();
this.disable();
}
public registerListener(listener: (timeoutInSeconds: number, elapsedTimeInSeconds: number) => void | Promise<void>) {
const manager = this.#getManager();
if (manager.registerListener) {
manager.registerListener(listener);
}
}
#getManager(): TimeoutManager {
return getGlobal(API_NAME) ?? NOOP_TIMEOUT_MANAGER;
}
}