Initial commit
This commit is contained in:
80
frontend-client/src/lib/stores/app.ts
Normal file
80
frontend-client/src/lib/stores/app.ts
Normal file
@@ -0,0 +1,80 @@
|
||||
import { writable } from 'svelte/store';
|
||||
import { auth } from './auth.js';
|
||||
import { get } from 'svelte/store';
|
||||
import type { Writable } from 'svelte/store';
|
||||
|
||||
// Types
|
||||
export interface Category {
|
||||
id: string;
|
||||
name: string;
|
||||
description: string;
|
||||
is_active: boolean;
|
||||
tenant_id: string;
|
||||
created_at: string;
|
||||
}
|
||||
|
||||
export interface AppState {
|
||||
categories: Category[];
|
||||
isLoading: boolean;
|
||||
error: string | null;
|
||||
}
|
||||
|
||||
// Initial state
|
||||
const initialState: AppState = {
|
||||
categories: [],
|
||||
isLoading: false,
|
||||
error: null
|
||||
};
|
||||
|
||||
// API helper function
|
||||
async function apiCall(endpoint: string, options: RequestInit = {}) {
|
||||
const authState = get(auth);
|
||||
|
||||
const response = await fetch(`/api/v1${endpoint}`, {
|
||||
...options,
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Authorization': `Bearer ${authState.token}`,
|
||||
...options.headers
|
||||
}
|
||||
});
|
||||
|
||||
if (!response.ok) {
|
||||
const error = await response.json();
|
||||
throw new Error(error.detail || 'Request failed');
|
||||
}
|
||||
|
||||
return response.json();
|
||||
}
|
||||
|
||||
// Create app store
|
||||
function createAppStore() {
|
||||
const { subscribe, set, update }: Writable<AppState> = writable(initialState);
|
||||
|
||||
return {
|
||||
subscribe,
|
||||
|
||||
// Load categories
|
||||
loadCategories: async () => {
|
||||
update(state => ({ ...state, isLoading: true, error: null }));
|
||||
|
||||
try {
|
||||
const categories = await apiCall('/categories/');
|
||||
update(state => ({ ...state, categories, isLoading: false }));
|
||||
} catch (error) {
|
||||
update(state => ({
|
||||
...state,
|
||||
isLoading: false,
|
||||
error: error instanceof Error ? error.message : 'Failed to load categories'
|
||||
}));
|
||||
}
|
||||
},
|
||||
|
||||
// Clear error
|
||||
clearError: () => {
|
||||
update(state => ({ ...state, error: null }));
|
||||
}
|
||||
};
|
||||
}
|
||||
|
||||
export const app = createAppStore();
|
||||
Reference in New Issue
Block a user