1 | "use strict";
|
2 |
|
3 | const path = require(`path`);
|
4 |
|
5 | const {
|
6 | appendFileSync,
|
7 | readFileSync,
|
8 | renameSync,
|
9 | existsSync,
|
10 | unlinkSync
|
11 | } = require(`fs`);
|
12 |
|
13 | module.exports = class Store {
|
14 | constructor(baseDir) {
|
15 | this.bufferFilePath = path.join(baseDir, `events.json`);
|
16 | }
|
17 |
|
18 | appendToBuffer(event) {
|
19 | try {
|
20 | appendFileSync(this.bufferFilePath, event, `utf8`);
|
21 | } catch (e) {
|
22 | }
|
23 | }
|
24 |
|
25 | async startFlushEvents(flushOperation) {
|
26 |
|
27 | const now = `${Date.now()}-${process.pid}`;
|
28 | let success = false;
|
29 | let contents = ``;
|
30 |
|
31 | try {
|
32 | if (!existsSync(this.bufferFilePath)) {
|
33 | return;
|
34 | }
|
35 |
|
36 | const newPath = `${this.bufferFilePath}-${now}`;
|
37 | renameSync(this.bufferFilePath, newPath);
|
38 | contents = readFileSync(newPath, `utf8`);
|
39 | unlinkSync(newPath);
|
40 |
|
41 |
|
42 | success = await flushOperation(contents);
|
43 | } catch (e) {
|
44 |
|
45 | } finally {
|
46 |
|
47 | if (!success) {
|
48 | this.appendToBuffer(contents);
|
49 | }
|
50 | }
|
51 | }
|
52 |
|
53 | }; |
\ | No newline at end of file |