Skip to content

Commit

Permalink
Only fetch one year worth of data for autocomplete suggestions
Browse files Browse the repository at this point in the history
This makes the suggestions more relevant and faster to load, for accounts with many years worth of data.
  • Loading branch information
BrunoBernardino committed Jul 19, 2023
1 parent b83d9be commit bc5f2c4
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 8 deletions.
21 changes: 21 additions & 0 deletions lib/data-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -378,6 +378,27 @@ export async function getExpensesByMonth(userId: string, month: string) {
return expenses;
}

export async function getExpensesForLastYear(userId: string) {
const twelveMonthsAgoMonth = new Date(new Date().setUTCMonth(new Date().getUTCMonth() - 12)).toISOString().substring(
0,
7,
);
const currentMonth = new Date().toISOString().substring(0, 7);

const expenses = await db.query<Expense>(
sql`SELECT * FROM "budgetzen_expenses"
WHERE "user_id" = $1 AND
"date" >= '${twelveMonthsAgoMonth}-01' AND
"date" <= '${currentMonth}-31'
ORDER BY "date" DESC, "id" DESC`,
[
userId,
],
);

return expenses;
}

export async function createExpense(expense: Omit<Expense, 'id'>) {
const newExpense = (await db.query<Expense>(
sql`INSERT INTO "budgetzen_expenses" (
Expand Down
15 changes: 12 additions & 3 deletions pages/api/expenses.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import {
deleteExpense,
getAllExpenses,
getExpensesByMonth,
getExpensesForLastYear,
monthRegExp,
updateExpense,
validateUserAndSession,
Expand Down Expand Up @@ -80,13 +81,21 @@ export async function pageContent(request: Request, _match: URLPatternResult) {
const userId = urlSearchParams.get('user_id');
const month = urlSearchParams.get('month');

if (!sessionId || !userId || !month || (!monthRegExp.test(month) && month !== 'all')) {
if (!sessionId || !userId || !month || (!monthRegExp.test(month) && month !== 'all' && month !== 'year')) {
return new Response('Bad Request', { status: 400 });
}

const { user } = await validateUserAndSession(userId, sessionId);

const events = await (month === 'all' ? getAllExpenses(user.id) : getExpensesByMonth(user.id, month));
let expenses: Expense[] = [];

return new Response(JSON.stringify(events), { headers: { 'Content-Type': 'application/json; charset=utf-8' } });
if (month === 'all') {
expenses = await getAllExpenses(user.id);
} else if (month === 'year') {
expenses = await getExpensesForLastYear(user.id);
} else {
expenses = await getExpensesByMonth(user.id, month);
}

return new Response(JSON.stringify(expenses), { headers: { 'Content-Type': 'application/json; charset=utf-8' } });
}
1 change: 1 addition & 0 deletions public/css/style.css
Original file line number Diff line number Diff line change
Expand Up @@ -555,6 +555,7 @@ a.button.secondary:focus {
.expenses-wrapper .expenses-filter-wrapper {
display: flex;
margin: 20px 0.5rem;
justify-content: space-between;
}

#expenses-filter .input-wrapper {
Expand Down
10 changes: 5 additions & 5 deletions public/ts/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -207,11 +207,11 @@ document.addEventListener('app-loaded', async () => {

// IIFE because we don't want to wait for all expenses in the main event-loop, but need it to get unique names
(async () => {
const allExpenses = await fetchExpenses('all');
const allExpenseNames: string[] = []; // This is necessary because you can't sort a Set, but it follows insertion order
allExpenses.forEach((expense) => allExpenseNames.push(expense.description));
allExpenseNames.sort();
allExpenseNames.forEach((expenseName) => uniqueExpenseNames.add(expenseName));
const yearExpenses = await fetchExpenses('year');
const recentExpenseNames: string[] = []; // This is necessary because you can't sort a Set, but it follows insertion order
yearExpenses.forEach((expense) => recentExpenseNames.push(expense.description));
recentExpenseNames.sort();
recentExpenseNames.forEach((expenseName) => uniqueExpenseNames.add(expenseName));
})();

const budgetOptions = new Set([{ name: 'Misc' }, ...allBudgets].map((budget) => budget.name));
Expand Down

0 comments on commit bc5f2c4

Please sign in to comment.