Skip to content

API Service

The ApiService class provides a generic interface for performing CRUD operations against a Laravel-style REST API.


import { ApiService } from '@ion-components/packages/services/api.service';
// Create a service instance for a specific resource
const userService = new ApiService<User>('users', axiosInstance);

constructor(
resource: string,
api: AxiosInstance
)
ParameterTypeDescription
resourcestringThe API resource name (e.g., 'users', 'orders')
apiAxiosInstancePre-configured Axios instance

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);

Fetch a single resource by ID.

async show(id?: number): Promise<T>
ParameterTypeDescription
idnumberOptional resource ID (appended to URL)

Example:

// GET /api/users/123
const user = await userService.show(123);
console.log('User:', user);
// GET /api/users (when ID not needed)
const currentUser = await userService.show();

Create a new resource.

async create(payload: T): Promise<T>
ParameterTypeDescription
payloadTResource data to create

Example:

const newUser = await userService.create({
name: 'John Doe',
role: 'user',
});
console.log('Created user ID:', newUser.id);

Update an existing resource.

async update(id: number, payload: T): Promise<T>
ParameterTypeDescription
idnumberResource ID to update
payloadTUpdated resource data

Example:

const updated = await userService.update(123, {
...existingUser,
name: 'Jane Doe',
});
console.log('Updated:', updated);

Delete a resource.

async delete(id: number): Promise<void>
ParameterTypeDescription
idnumberResource ID to delete

Example:

await userService.delete(123);
console.log('User deleted');

import axios from 'axios';
import { ApiService } from '@ion-components/packages/services/api.service';
// Define your resource type
interface Product {
id: number;
name: string;
price: number;
category: string;
active: boolean;
}
// Create Axios instance with auth
const api = axios.create({
baseURL: 'https://api.example.com',
headers: {
'Authorization': `Bearer ${token}`,
'X-Tenant-ID': tenantId,
},
});
// Create service
const productService = new ApiService<Product>('products', api);
// Usage in Vue component
const 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);
}

packages/services/api.service.ts
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}`);
}
}