Skip to content

Commit aad0fd4

Browse files
author
Schmidely Stéphane
committed
Save CSV or JSON file
1 parent 7d633db commit aad0fd4

1 file changed

Lines changed: 27 additions & 3 deletions

File tree

src/utils/commands/export/utils.ts

Lines changed: 27 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import * as fs from 'fs'
2+
import { parse } from 'json2csv'
23
import * as moment from 'moment'
34
import { EOL } from 'os'
45

@@ -51,13 +52,17 @@ export default class ExportUtils {
5152
const toDate = params.to.replace(/-/g, '')
5253
const project = params.project.replace(/[^a-zA-Z ]/g, '')
5354
const filename = `${project}-${fromDate}-${toDate}.${params.format}`
54-
const writeData = (params.format === 'json') ? JSON.stringify(data) : data
55+
let writeData = null
56+
if (params.format === 'json') {
57+
writeData = this.formatAsJson(data)
58+
} else if (params.format === 'csv') {
59+
writeData = this.formatAsCsv(data)
60+
}
5561
try {
5662
fs.writeFileSync(filename, writeData)
5763
return true
5864
} catch (err) {
59-
// FIXME handle error
60-
console.error(err)
65+
// FIXME handle error (err)
6166
}
6267
}
6368

@@ -72,4 +77,23 @@ export default class ExportUtils {
7277
}).join(EOL)
7378
return `${title}${EOL}${details}`
7479
}
80+
81+
/**
82+
* Stringify data
83+
*/
84+
private formatAsJson(data) {
85+
return JSON.stringify(data)
86+
}
87+
88+
/**
89+
* Convert JSON as CSV
90+
*/
91+
private formatAsCsv(data) {
92+
const headers = ['start', 'end', 'duration', 'project', 'description']
93+
try {
94+
return parse(data, { fields: headers })
95+
} catch (err) {
96+
// FIXME handle error (err)
97+
}
98+
}
7599
}

0 commit comments

Comments
 (0)