-
Notifications
You must be signed in to change notification settings - Fork 1
/
vk_api.js
85 lines (73 loc) · 2.38 KB
/
vk_api.js
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
import { monotonicNowMillis } from "./utils.js";
export class VkApiError extends Error {
constructor(code, msg) {
super(`[${code}] ${msg}`);
this.name = 'VkApiError';
this.code = code;
this.msg = msg;
}
}
const MIN_DELAY_MILLIS = 360;
export class VkApiSession {
constructor(transport, context) {
this._transport = transport;
this._context = context;
this._rateLimitCallback = null;
this._lastRequestTimestamp = -Infinity;
this._cancelFlag = false;
}
setRateLimitCallback(fn) {
this._rateLimitCallback = fn;
}
async _limitRate(reason, delayMillis) {
if (this._rateLimitCallback !== null)
this._rateLimitCallback(reason);
await this._context.sleepMillis(delayMillis);
}
async apiRequestForwardErrors(method, params, raw) {
const now = monotonicNowMillis();
const delay = now - this._lastRequestTimestamp;
if (delay < MIN_DELAY_MILLIS)
await this._context.sleepMillis(MIN_DELAY_MILLIS - delay);
this._context.maybeThrowForCancel();
this._lastRequestTimestamp = monotonicNowMillis();
const result = await this._transport.callAPI(method, params);
return raw ? result : result.response;
}
async handleOrThrow(err) {
if (!(err instanceof VkApiError))
throw err;
// https://vk.com/dev/errors
switch (err.code) {
case 6:
await this._limitRate('rateLimit', 3000);
break;
case 9:
await this._limitRate('rateLimitHard', 5000);
break;
case 1:
case 10:
await this._limitRate('serverUnavailable', 1000);
break;
default:
throw err;
}
}
async apiRequest(method, params, raw = false) {
while (true) {
try {
return await this.apiRequestForwardErrors(method, params, raw);
} catch (err) {
await this.handleOrThrow(err);
}
}
}
async apiExecute(params) {
const result = await this.apiRequest('execute', params, /*raw=*/true);
const errors = result.execute_errors || [];
return {
response: result.response,
errors: errors.map(datum => new VkApiError(datum.error_code, datum.error_msg)),
};
}
}