Skip to content

Commit

Permalink
feat: get accounts as csv
Browse files Browse the repository at this point in the history
  • Loading branch information
acifani committed May 23, 2024
1 parent bd7e598 commit 33ef5ab
Showing 1 changed file with 34 additions and 13 deletions.
47 changes: 34 additions & 13 deletions routes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -29,15 +29,25 @@ router.get('/budget/:month', async (req, res) => {
res.status(200).json(budget);
});

router.get('/accounts', async (_, res) => {
const accounts = await actual.getAccounts();
res.status(200).json(accounts);
});
router.get(
'/accounts',
async (_, res, next) => {
const accounts = await actual.getAccounts();
res.locals.data = accounts;
next();
},
formatHandler,
);

router.get('/accounts/:accountid', async (req, res) => {
const account = await actual.getAccount(req.params.accountid);
res.status(200).json(account);
});
router.get(
'/accounts/:accountid',
async (req, res, next) => {
const account = await actual.getAccount(req.params.accountid);
res.locals.data = account;
next();
},
formatHandler,
);

router.get(
'/accounts/:accountid/transactions',
Expand Down Expand Up @@ -65,13 +75,24 @@ export { router };

function jsonToCSV(data: any) {
let csv = '';
csv += Object.keys(data?.[0]).join(',') + '\n';

for (const row of data) {
csv += Object.values(row)
const unpackHeaders = (x: object) => Object.keys(x).join(',') + '\n';
const unpackValues = (x: object) =>
Object.values(x)
.map((v) => JSON.stringify(v))
.join(',');
csv += '\n';
.join(',') + '\n';

// object
if (!Array.isArray(data)) {
csv += unpackHeaders(data);
csv += unpackValues(data);
return csv;
}

// array
csv += unpackHeaders(data?.[0]);
for (const row of data) {
csv += unpackValues(row);
}

return csv;
Expand Down

0 comments on commit 33ef5ab

Please sign in to comment.