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