Cache YNAB data responses

This commit is contained in:
2020-12-10 22:13:20 -06:00
commit eb07185d6e
5 changed files with 268 additions and 0 deletions

71
index.js Normal file
View File

@@ -0,0 +1,71 @@
const ynab = require("ynab");
const { argv } = require('yargs');
const fs = require('fs');
const { pat, cacheDir } = require('./config');
const ynabAPI = new ynab.API(pat);
const ensureDataDir = async function(path) {
if (!fs.existsSync(path)) {
await fs.promises.mkdir(path);
}
}
const getCachedJsonOrHydrate = async function(fileName, hydrator) {
const filePath = `${cacheDir}/${fileName}`
if (fs.existsSync(filePath)) {
return JSON.parse(await fs.promises.readFile(filePath));
}
const data = await hydrator();
await ensureDataDir(cacheDir);
await fs.promises.writeFile(filePath, JSON.stringify(data));
return data;
}
const getBudgetId = async function(budgetName) {
const budgets = await getCachedJsonOrHydrate("budgets.json", async () => {
console.log("Grabbing budgets from YNAB");
const budgetsResponse = await ynabAPI.budgets.getBudgets();
return budgetsResponse.data.budgets;
});
const budgetId = budgets.filter(b => { return b.name === budgetName; })[0].id;
return budgetId;
}
const getAccountId = async function(budgetId, accountName) {
let accounts = await getCachedJsonOrHydrate("accounts.json", async () => {
console.log("Grabbing accounts from YNAB");
const accountsResponse = await ynabAPI.accounts.getAccounts(budgetId);
return accountsResponse.data.accounts;
});
const accountId = accounts.filter(a => { return a.name === accountName; })[0].id;
return accountId;
}
const getTransactions = async function(budgetId, accountId) {
const date = new Date();
const jsonFile = `${date.getFullYear()}-${date.getMonth()}-${date.getDate()}-transactions.json`;
let transactions = await getCachedJsonOrHydrate(jsonFile, async () => {
console.log("Grabbing transactions from YNAB");
const transactionsResponse = await ynabAPI.transactions.getTransactionsByAccount(budgetId, accountId);
return transactionsResponse.data.transactions;
});
return transactions;
}
const main = async function(budgetName, accountName) {
console.log(`Looking for account '${accountName}' in budget named '${budgetName}'.`);
const budgetId = await getBudgetId(budgetName);
const accountId = await getAccountId(budgetId, accountName);
const transactions = await getTransactions(budgetId, accountId);
console.log(transactions.length);
console.log(transactions[transactions.length - 1]);
};
main(argv.budgetName, argv.accountName);