-
Notifications
You must be signed in to change notification settings - Fork 87
/
chain.ts
88 lines (71 loc) · 1.97 KB
/
chain.ts
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
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { inspectable } from 'inspectable';
import { VKError } from '../errors';
import { API } from '../api';
import { APIRequest } from '../api/request';
import { IExecutesPayload, executeRequests } from './executes';
export interface IChainOptions {
api: API;
}
export class Chain {
public started = false;
protected api: API;
protected queue: APIRequest[] = [];
/**
* Constructor
*/
public constructor({ api }: IChainOptions) {
this.api = api;
}
/**
* Returns custom tag
*/
public get [Symbol.toStringTag](): string {
return this.constructor.name;
}
/**
* Adds method to queue
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public append<T = any>(method: string, params: object): Promise<T> {
if (this.started) {
return Promise.reject(new VKError({
message: 'Chain already started',
code: 'ALREADY_STARTED',
}));
}
const request = new APIRequest({
api: this.api,
method,
params,
});
this.queue.push(request);
return request.promise as Promise<T>;
}
/**
* Promise based
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any
public then(thenFn: (value: IExecutesPayload) => unknown, catchFn: (reason: unknown) => unknown): Promise<unknown> {
return this.run().then(thenFn, catchFn);
}
/**
* Starts the chain
*/
public async run(): Promise<IExecutesPayload> {
if (this.started) {
throw new VKError({
message: 'Chain already started',
code: 'ALREADY_STARTED',
});
}
this.started = true;
return executeRequests(this.api, this.queue);
}
}
inspectable(Chain, {
// @ts-expect-error queue is private
serialize: ({ started, queue }) => ({
started,
queue,
}),
});