-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathCSVTransactionParser.ts
More file actions
57 lines (52 loc) · 1.98 KB
/
Copy pathCSVTransactionParser.ts
File metadata and controls
57 lines (52 loc) · 1.98 KB
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
import moment, {Moment} from "moment";
import TransactionParser from "./TransactionParser";
import Transaction from "./Transaction";
import CSVTransactionParserErrorHandler from "./CSVTransactionParserErrorHandler";
const csv = require('csv-parser');
const fs = require('fs');
export default class CSVTransactionParser extends TransactionParser {
constructor() {
super();
this.errorHandler = new CSVTransactionParserErrorHandler(`ParsingError`);
}
async ParseTransactionsFromFile(fileName: string): Promise<Transaction[]> {
return new Promise<Transaction[]>((resolve) => {
let transactions: Transaction[] = [];
let lineCount: number = 2; // Header isn't processed by 'data' event
fs.createReadStream(fileName)
.pipe(csv())
.on('data', (row: any) => {
try {
transactions.push(this.ParseTransaction(row));
} catch (e: any) {
this.errorHandler.LogAndStoreError(e.message, lineCount);
}
lineCount++;
})
.on('error', (e: Error) => {
this.errorHandler.LogAndStoreError(e.message, lineCount);
lineCount++;
})
.on('end', () => {
resolve(transactions);
});
});
}
ParseTransaction(row: any): Transaction {
const parsedDate: Moment = moment(row.Date, "D/M/YYYY");
if (!parsedDate.isValid()){
throw new Error("Invalid date");
}
const parsedAmount: number = Number(row.Amount);
if (isNaN(parsedAmount)) {
throw new Error("Amount is not a number");
}
return new Transaction(
parsedDate,
row.From,
row.To,
row.Narrative,
parsedAmount
);
}
}