badmfck-api-server 1.6.2 → 1.6.3

Sign up to get free protection for your applications and to get access to all the features.
@@ -0,0 +1,16 @@
1
+ export declare class DataProvider<T> {
2
+ private static nextID;
3
+ private name?;
4
+ private busy;
5
+ private lastRequestTime;
6
+ private cacheTime;
7
+ private data;
8
+ private callbacks;
9
+ private wasError;
10
+ private executor;
11
+ constructor(executor: () => Promise<{
12
+ data: T | null | undefined;
13
+ error?: boolean;
14
+ }>, cacheTime?: number, name?: string);
15
+ getData(): Promise<T | null | undefined>;
16
+ }
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.DataProvider = void 0;
7
+ const badmfck_signal_1 = __importDefault(require("badmfck-signal"));
8
+ class DataProvider {
9
+ static nextID = 1;
10
+ name;
11
+ busy = false;
12
+ lastRequestTime = 0;
13
+ cacheTime = 1000 * 60 * 5;
14
+ data;
15
+ callbacks = new badmfck_signal_1.default();
16
+ wasError = false;
17
+ executor;
18
+ constructor(executor, cacheTime, name) {
19
+ this.executor = executor;
20
+ if (cacheTime !== undefined)
21
+ this.cacheTime = +cacheTime;
22
+ if (isNaN(this.cacheTime))
23
+ this.cacheTime = 0;
24
+ if (!this.name)
25
+ this.name = "DataProvider " + (DataProvider.nextID++);
26
+ }
27
+ async getData() {
28
+ if (this.busy)
29
+ return new Promise((resolve, reject) => this.callbacks.subscribe((d) => resolve(d)));
30
+ if (this.lastRequestTime > 0 && !this.wasError) {
31
+ const diff = (+new Date()) - this.lastRequestTime;
32
+ if (diff < this.cacheTime)
33
+ return this.data;
34
+ }
35
+ this.busy = true;
36
+ this.wasError = false;
37
+ const res = await this.executor();
38
+ this.busy = false;
39
+ this.wasError = res.error ?? false;
40
+ this.data = res.data;
41
+ this.lastRequestTime = +new Date();
42
+ this.callbacks.invoke(this.data);
43
+ this.callbacks.removeAll();
44
+ return this.data;
45
+ }
46
+ }
47
+ exports.DataProvider = DataProvider;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "badmfck-api-server",
3
- "version": "1.6.2",
3
+ "version": "1.6.3",
4
4
  "description": "Simple API http server based on express",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",