forked from punkave/albedo
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalbedo.js
145 lines (132 loc) · 4.23 KB
/
albedo.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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
const { Transform } = require('stream');
const CSVTransform = require('json2csv').Transform;
const mysql = require('mysql');
const fs = require('fs');
const moment = require('moment');
const _ = require('underscore');
module.exports = {
/**
* Processes a report for the given options
*
* @param {obj} options
* @param {function} callback
*/
processReport(options, callback) {
if (!options) {
return callback('processReport requires options, see documentation');
}
if (options.connection.type !== 'mysql') {
return callback('The selected database type is not yet supported');
}
const connection = mysql.createConnection({
host: options.connection.host,
user: options.connection.user,
password: options.connection.password,
database: options.connection.database,
insecureAuth: true,
});
// set up input, csv, and output streams
const fileName = `${options.name}_${moment().format('YYYY-MM-DD_HH-mm-ss')}.csv`;
const outputPath = `${options.location}/${fileName}`;
const input = connection.query(options.query).stream({ highWaterMark: 64 });
const output = fs.createWriteStream(outputPath, { encoding: 'utf8' });
const json2csv = new CSVTransform(null, { objectMode: true });
// handle row transformations
let empty = true;
const rowTransform = new Transform({
writableObjectMode: true,
readableObjectMode: true,
transform(chunk, enc, handler) {
try {
let row = chunk;
if (_.isArray(options.process_row)) {
_.each(options.process_row, (func) => {
row = func(row);
});
} else if (_.isFunction(options.process_row)) {
row = options.process_row(row);
}
handler(null, row);
empty = false;
} catch (e) {
handler(e);
}
},
});
// route errors from streams to callback
let wasError = false;
function forwardError(e) {
wasError = true;
callback(e);
}
input.on('error', forwardError);
rowTransform.on('error', forwardError);
json2csv.on('error', forwardError);
output.on('error', forwardError);
// route output stream finish event to callback
output.on('close', () => {
if (empty) {
// don't leave empty report files if there were no results
fs.unlink(outputPath, (e) => {
if (e) {
callback(`Failed to remove empty report file: ${e}`);
}
});
if (!wasError) {
callback('No records for query');
}
return;
}
if (wasError) {
// suppress final report info callback on errors
return;
}
// prune older reports only after successful export
if (options.hasOwnProperty('removeOlderThan')) {
rmDir(options.location, options, outputPath);
}
// finally return new report info
const reportInfo = {
name: fileName,
path: `${options.location}/`,
};
callback(null, reportInfo);
});
// stream query results through processing pipeline
input.pipe(rowTransform).pipe(json2csv).pipe(output);
connection.end();
},
};
function rmDir(dirPath, options, outputPath) {
// TODO: rejigger this whole thing to operate async
let files;
try {
files = fs.readdirSync(dirPath);
} catch (e) {
console.err('Could not delete files');
return;
}
files.forEach((fileName) => {
const filePath = `${dirPath}/${fileName}`;
if (filePath === outputPath) {
console.log(`ignoring: ${filePath}`);
return;
}
if (fs.statSync(filePath).isFile()) {
const now = moment().unix();
const daysAgo = now - (parseInt(options.removeOlderThan, 10) * 86400);
const fileTime = moment(fs.statSync(filePath).mtime).unix();
// get the full name of the report from the file by removing the datetime and extension
if (fileName.slice(0, 0-'_YYYY-MM-DD_HH-mm-ss.csv'.length) === options.name) {
if (fileTime < daysAgo) {
fs.unlinkSync(filePath);
console.log(`deleted: ${filePath}`);
} else {
console.log(`kept: ${filePath}`);
}
}
} else {
rmDir(filePath, options, outputPath);
}
});
}