API Service
API Service
Section titled “API Service”The ApiService class provides a generic interface for performing CRUD operations against a Laravel-style REST API.
Overview
Section titled “Overview”import { ApiService } from '@ion-components/packages/services/api.service';
// Create a service instance for a specific resourceconst userService = new ApiService<User>('users', axiosInstance);Constructor
Section titled “Constructor”constructor( resource: string, api: AxiosInstance)| Parameter | Type | Description |
|---|---|---|
resource | string | The API resource name (e.g., 'users', 'orders') |
api | AxiosInstance | Pre-configured Axios instance |
Methods
Section titled “Methods”list()
Section titled “list()”Fetch all resources with pagination.
async list(): Promise<LaravelResponse<T>>Response Structure:
interface LaravelResponse<T> { data?: Array<T>; meta?: { filter: string; search: string | null; sort_by: string; sort_order: string; count: number; total_pages: number; current_page: number; per_page: number; total: number; // ... };}Example:
const userService = new ApiService<User>('users', api);
const response = await userService.list();console.log('Users:', response.data);console.log('Total:', response.meta?.total);console.log('Page:', response.meta?.current_page);show(id?)
Section titled “show(id?)”Fetch a single resource by ID.
async show(id?: number): Promise<T>| Parameter | Type | Description |
|---|---|---|
id | number | Optional resource ID (appended to URL) |
Example:
// GET /api/users/123const user = await userService.show(123);console.log('User:', user);
// GET /api/users (when ID not needed)const currentUser = await userService.show();create(payload)
Section titled “create(payload)”Create a new resource.
async create(payload: T): Promise<T>| Parameter | Type | Description |
|---|---|---|
payload | T | Resource data to create |
Example:
const newUser = await userService.create({ name: 'John Doe', role: 'user',});console.log('Created user ID:', newUser.id);update(id, payload)
Section titled “update(id, payload)”Update an existing resource.
async update(id: number, payload: T): Promise<T>| Parameter | Type | Description |
|---|---|---|
id | number | Resource ID to update |
payload | T | Updated resource data |
Example:
const updated = await userService.update(123, { ...existingUser, name: 'Jane Doe',});console.log('Updated:', updated);delete(id)
Section titled “delete(id)”Delete a resource.
async delete(id: number): Promise<void>| Parameter | Type | Description |
|---|---|---|
id | number | Resource ID to delete |
Example:
await userService.delete(123);console.log('User deleted');Complete Example
Section titled “Complete Example”import axios from 'axios';import { ApiService } from '@ion-components/packages/services/api.service';
// Define your resource typeinterface Product { id: number; name: string; price: number; category: string; active: boolean;}
// Create Axios instance with authconst api = axios.create({ baseURL: 'https://api.example.com', headers: { 'Authorization': `Bearer ${token}`, 'X-Tenant-ID': tenantId, },});
// Create serviceconst productService = new ApiService<Product>('products', api);
// Usage in Vue componentconst products = ref<Product[]>([]);const loading = ref(false);
async function loadProducts() { loading.value = true; try { const response = await productService.list(); products.value = response.data ?? []; } catch (error) { console.error('Failed to load products:', error); } finally { loading.value = false; }}
async function createProduct(data: Partial<Product>) { const created = await productService.create(data as Product); products.value.push(created); return created;}
async function updateProduct(id: number, data: Partial<Product>) { const updated = await productService.update(id, data as Product); const index = products.value.findIndex(p => p.id === id); if (index !== -1) { products.value[index] = updated; } return updated;}
async function deleteProduct(id: number) { await productService.delete(id); products.value = products.value.filter(p => p.id !== id);}Source Code
Section titled “Source Code”import type { AxiosInstance } from 'axios';import type { LaravelResponse } from '../models/api.model';
export class ApiService<T> { protected resource: string; protected api: AxiosInstance;
constructor(resource: string, api: AxiosInstance) { this.resource = resource; this.api = api; }
async list(): Promise<LaravelResponse<T>> { const response = await this.api.get<LaravelResponse<T>>(this.resource); return response.data; }
async show(id?: number): Promise<T> { const url = id ? `${this.resource}/${id}` : this.resource; const response = await this.api.get<T>(url); return response.data; }
async create(payload: T): Promise<T> { const response = await this.api.post<T>(this.resource, payload); return response.data; }
async update(id: number, payload: T): Promise<T> { const response = await this.api.put<T>(`${this.resource}/${id}`, payload); return response.data; }
async delete(id: number): Promise<void> { await this.api.delete(`${this.resource}/${id}`); }}