-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
util.ts
71 lines (63 loc) · 1.62 KB
/
util.ts
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
import papaparse from "papaparse";
import fs from "fs";
/*
< {
< orderid: 'D01-7098770-3645007',
< items: 'Elf; ',
< categories: '',
< to: '0',
< date: '2021-12-17',
< total: '0',
< shipping: '0',
< shipping_refund: '0',
< gift: '0',
< tax: '3.99',
< refund: '0',
< payments: '2021-12-17: $0.00; '
< }
*/
export interface AmazonTransaction {
orderid: string;
items: string;
categories: string;
to: string;
date: string;
total: string;
shipping: string;
shipping_refund: string;
gift: string;
tax: string;
refund: string;
payments: string;
}
export const readJSONFile = (path: string): any | null => {
if (fs.existsSync(path)) {
return JSON.parse(fs.readFileSync(path, "utf8"));
}
return null;
};
// TODO should type the resulting object here for better checking downstream
export const readCSV = async (
filePath: string,
): Promise<AmazonTransaction[]> => {
const csvFile = fs.readFileSync(filePath);
const csvData = csvFile.toString();
return new Promise((resolve) => {
papaparse.parse(csvData, {
header: true,
skipEmptyLines: true,
// 'Original Description' => 'OriginalDescription'
transformHeader: (header: string) => header.replace(/\s/g, ""),
complete: (results) => {
resolve(results.data);
},
} as papaparse.ParseConfig<AmazonTransaction>);
});
};
export const writeCSV = (csvRows: any, filePath: string) => {
const csvContent = papaparse.unparse(csvRows);
fs.writeFileSync(filePath, csvContent);
};
export function prettyJSON(json: Object, returnString = false): string {
return JSON.stringify(json, null, 2);
}