UNPKG

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