-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJSONTransactionParser.ts
More file actions
48 lines (44 loc) · 1.68 KB
/
JSONTransactionParser.ts
File metadata and controls
48 lines (44 loc) · 1.68 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
import moment, {Moment} from "moment";
import Transaction from "./Transaction";
import TransactionParser from "./TransactionParser";
const fs = require('fs');
export default class JSONTransactionParser extends TransactionParser {
async ParseTransactionsFromFile(fileName: string): Promise<Transaction[]> {
return new Promise<Transaction[]>((resolve) => {
let transactions: Transaction[] = [];
let lineCount: number = 1;
let transactionObjects: any[] = []
try {
transactionObjects = JSON.parse(fs.readFileSync(fileName));
} catch (e: any) {
this.errorHandler.LogAndStoreError(`Error parsing JSON file: ${e.message}`);
}
transactionObjects.forEach((record => {
try {
transactions.push(this.ParseTransaction(record));
} catch (e: any) {
this.errorHandler.LogAndStoreError(e.message, lineCount);
}
lineCount++;
}));
resolve(transactions);
});
}
ParseTransaction(record: any): Transaction {
const parsedDate: Moment = moment(record.Date, moment.ISO_8601);
if (!parsedDate.isValid()){
throw new Error("Invalid date");
}
const parsedAmount: number = Number(record.Amount);
if (isNaN(parsedAmount)) {
throw new Error("Amount is not a number");
}
return new Transaction(
parsedDate,
record.FromAccount,
record.ToAccount,
record.Narrative,
parsedAmount
);
}
}