feat: Implement server-side loading for exchange rates with authentication and error handling
This commit is contained in:
@@ -0,0 +1,36 @@
|
||||
import type { PageServerLoad } from './$types';
|
||||
import { getAuthTokens, authenticatedFetch } from '$lib/server/api';
|
||||
|
||||
export const load: PageServerLoad = async ({ cookies, fetch, url, parent }) => {
|
||||
await parent();
|
||||
const { accessToken } = getAuthTokens(cookies);
|
||||
|
||||
if (!accessToken) {
|
||||
return { error: 'No authenticated', exchangeRates: { items: [], total: 0, page: 1, page_size: 50, pages: 0 } };
|
||||
}
|
||||
|
||||
try {
|
||||
const page = Number(url.searchParams.get('page')) || 1;
|
||||
const pageSize = Number(url.searchParams.get('pageSize')) || 50;
|
||||
const filters: Record<string, string> = {};
|
||||
const date = url.searchParams.get('date');
|
||||
const localCurrency = url.searchParams.get('local_currency');
|
||||
const foreignCurrency = url.searchParams.get('foreign_currency');
|
||||
|
||||
if (date) filters.date = date;
|
||||
if (localCurrency) filters.local_currency = localCurrency;
|
||||
if (foreignCurrency) filters.foreign_currency = foreignCurrency;
|
||||
|
||||
const queryParams = new URLSearchParams({ page: page.toString(), page_size: pageSize.toString(), ...filters });
|
||||
const response = await authenticatedFetch(`v1/a76/exchange-rate?${queryParams.toString()}`, { method: 'GET' }, cookies, fetch);
|
||||
|
||||
if (!response.ok) {
|
||||
return { error: 'Failed to load', exchangeRates: { items: [], total: 0, page, page_size: pageSize, pages: 0 } };
|
||||
}
|
||||
|
||||
return { exchangeRates: await response.json() };
|
||||
} catch (error) {
|
||||
console.error('Error loading exchange rates:', error);
|
||||
return { error: 'Error loading', exchangeRates: { items: [], total: 0, page: 1, page_size: 50, pages: 0 } };
|
||||
}
|
||||
};
|
||||
@@ -13,9 +13,11 @@
|
||||
import { getExchangeRates } from '$lib/api/dashboard/a76/general_catalogs/exchange-rate';
|
||||
import { companyStore } from '$lib/stores/company.svelte';
|
||||
|
||||
let allItems = $state<ExchangeRate[]>([]);
|
||||
let { data } = $props();
|
||||
|
||||
let allItems = $state<ExchangeRate[]>(data.exchangeRates?.items || []);
|
||||
let loading = $state(false);
|
||||
let error = $state<string | null>(null);
|
||||
let error = $state<string | null>(data.error || null);
|
||||
let currentPage = $state(1);
|
||||
const pageSize = 50;
|
||||
|
||||
@@ -97,9 +99,9 @@
|
||||
const response = await getExchangeRates(companyId, filters);
|
||||
|
||||
if (page === 1) {
|
||||
allItems = response.data.items;
|
||||
allItems = response.items;
|
||||
} else {
|
||||
allItems = [...allItems, ...response.data.items];
|
||||
allItems = [...allItems, ...response.items];
|
||||
}
|
||||
|
||||
currentPage = page;
|
||||
|
||||
Reference in New Issue
Block a user