50 lines
1.4 KiB
Markdown
50 lines
1.4 KiB
Markdown
# 6. API Integration
|
|
|
|
Since the project is a monolith where the frontend and backend are served by the same Nuxt instance, we will use the built-in `$fetch` utility for all API calls. This is the recommended, isomorphic way to handle data fetching in Nuxt 4.
|
|
|
|
## Service Layer Pattern
|
|
|
|
To keep components clean and organize API logic, we will use a "service layer" pattern. All API calls will be abstracted into functions within files in the `app/services` directory.
|
|
|
|
**`app/services/cellService.ts` (Example Template)**
|
|
```typescript
|
|
// Using Nuxt's built-in $fetch
|
|
import { $fetch } from 'ofetch';
|
|
|
|
// Define types for API payloads and responses, ideally imported from a shared location
|
|
interface Cell {
|
|
id: string;
|
|
// ... other properties
|
|
}
|
|
|
|
interface CreateCellPayload {
|
|
commonGood: string;
|
|
// ... other properties
|
|
}
|
|
|
|
const BASE_URL = '/api/cells'; // Internal API endpoint
|
|
|
|
export const cellService = {
|
|
/**
|
|
* Fetches the details for a single Cell.
|
|
* @param id The ID of the Cell.
|
|
*/
|
|
async getCellById(id: string): Promise<Cell> {
|
|
return await $fetch<Cell>(`${BASE_URL}/${id}`);
|
|
},
|
|
|
|
/**
|
|
* Creates a new Cell.
|
|
* @param payload The data for the new Cell.
|
|
*/
|
|
async createCell(payload: CreateCellPayload): Promise<Cell> {
|
|
return await $fetch<Cell>(BASE_URL, {
|
|
method: 'POST',
|
|
body: payload,
|
|
});
|
|
},
|
|
|
|
// ... other methods like joinAsConsumer, confirmPayment, etc.
|
|
};
|
|
```
|