UNPKG

1.26 kBJavaScriptView Raw
1const path = require(`path`)
2const {
3 appendFileSync,
4 readFileSync,
5 renameSync,
6 existsSync,
7 unlinkSync,
8} = require(`fs`)
9
10module.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 //ignore
20 }
21 }
22
23 async startFlushEvents(flushOperation) {
24 // Unique temporary file name across multiple concurrent Gatsby instances
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 // There is still a chance process dies while sending data and some events are lost
39 // This will be ok for now, however
40 success = await flushOperation(contents)
41 } catch (e) {
42 // ignore
43 // TODO: Log this event
44 } finally {
45 // if sending fails, we write the data back to the log
46 if (!success) {
47 this.appendToBuffer(contents)
48 }
49 }
50 }
51}