@data-fair/lib-node 1.0.1 → 1.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/events-queue.d.ts +9 -0
- package/events-queue.js +43 -0
- package/package.json +1 -1
- package/mongo-types.d.ts +0 -1
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
import { type Event } from '@data-fair/lib-common-types/event/index.js';
|
|
2
|
+
type EventsQueueOptions = {
|
|
3
|
+
eventsUrl: string;
|
|
4
|
+
eventsSecret: string;
|
|
5
|
+
};
|
|
6
|
+
export declare const start: (options: EventsQueueOptions) => Promise<void>;
|
|
7
|
+
export declare const stop: () => Promise<void>;
|
|
8
|
+
export declare const pushEvent: (event: Omit<Event, "date">) => void;
|
|
9
|
+
export {};
|
package/events-queue.js
ADDED
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
import { internalError } from '@data-fair/lib-node/observer.js'
|
|
2
|
+
import axios from './axios.js'
|
|
3
|
+
let _options
|
|
4
|
+
const options = () => {
|
|
5
|
+
if (!_options) { throw new Error('events queue was not initialized') }
|
|
6
|
+
return _options
|
|
7
|
+
}
|
|
8
|
+
let queue = []
|
|
9
|
+
let stopped = false
|
|
10
|
+
let currentDrainPromise
|
|
11
|
+
const loop = async () => {
|
|
12
|
+
// eslint-disable-next-line no-unmodified-loop-condition
|
|
13
|
+
while (!stopped) {
|
|
14
|
+
await new Promise(resolve => setTimeout(resolve, 3000))
|
|
15
|
+
try {
|
|
16
|
+
currentDrainPromise = drain()
|
|
17
|
+
await currentDrainPromise
|
|
18
|
+
currentDrainPromise = undefined
|
|
19
|
+
} catch (err) {
|
|
20
|
+
internalError('events-queue-drain', err)
|
|
21
|
+
}
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const drain = async () => {
|
|
25
|
+
if (queue.length === 0) { return }
|
|
26
|
+
const events = queue
|
|
27
|
+
queue = []
|
|
28
|
+
await axios.post(options().eventsUrl + '/api/events', events, { headers: { 'x-secret-key': options().eventsSecret } })
|
|
29
|
+
}
|
|
30
|
+
export const start = async (options) => {
|
|
31
|
+
_options = options
|
|
32
|
+
loop()
|
|
33
|
+
}
|
|
34
|
+
export const stop = async () => {
|
|
35
|
+
stopped = true
|
|
36
|
+
if (currentDrainPromise) { await currentDrainPromise }
|
|
37
|
+
await drain()
|
|
38
|
+
}
|
|
39
|
+
export const pushEvent = (event) => {
|
|
40
|
+
if (stopped) { throw new Error('events queue as been stopped') }
|
|
41
|
+
queue.push(event)
|
|
42
|
+
event.date = new Date().toISOString()
|
|
43
|
+
}
|
package/package.json
CHANGED
package/mongo-types.d.ts
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export {};
|