-
Notifications
You must be signed in to change notification settings - Fork 0
/
service-writer.js
58 lines (49 loc) · 1.45 KB
/
service-writer.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
/*
*
* A script to simulate the real world by repeatedly
* emitting account transaction events for a set of user ids.
*
*/
const fs = require("fs");
function main() {
const { database } = cliOptions(); // get db name from cli arguments
const stream = fs.createWriteStream(database, { flags: 'a' }); // open db for writing
let serialNumber = lineCount(database) || 0; // get first event id
setInterval(() => emit(stream, serialNumber++), 500) // emit new event every 500ms
}
function cliOptions() {
const ix = process.argv.indexOf("--database") + 1;
if (ix == 0 || !process.argv[ix]) {
console.error("Missing --database option");
process.exit(1);
}
const database = process.argv[ix];
return { database };
}
function lineCount(path) {
try {
const content = fs.readFileSync(path, { encoding: 'utf8', flag: 'r' });
const newlines = content.split("\n").length;
return newlines - 1;
} catch {
return 0;
}
}
function emit(stream, id) {
const event = createEvent(id);
save(event, stream);
}
function createEvent(id) {
const amount = between(-1000, 1000);
const user_id = between(1, 10);
const posix_time = Date.now() / 1000;
return { id, user_id, amount, posix_time }
}
function between(min, max) {
return min + Math.floor(Math.random() * (max - min))
}
function save(event, stream) {
const line = JSON.stringify(event) + "\n"
stream.write(line);
}
main();