import { config } from '../config.js';
import { City, CreateCityRequest, UpdateCityRequest } from '../types/city.js';
import { CityResponse, CitiesResponse, DeleteResponse } from '../types/api-responses.js';
const API_BASE_URL = `http://${config.api.host}:${config.api.port}/api`;
/**
* Client for communicating with the CRUD API
*/
export class ApiClient {
/**
* Create a new city
*/
async createCity(nome: string): Promise<City> {
const request: CreateCityRequest = { nome };
const response = await fetch(`${API_BASE_URL}/cities`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
});
const data: CityResponse = await response.json();
if (!data.success || !data.data) {
throw new Error(data.error || 'Failed to create city');
}
return data.data;
}
/**
* Get all cities
*/
async getAllCities(): Promise<City[]> {
const response = await fetch(`${API_BASE_URL}/cities`);
const data: CitiesResponse = await response.json();
if (!data.success || !data.data) {
throw new Error(data.error || 'Failed to fetch cities');
}
return data.data;
}
/**
* Get a city by ID
*/
async getCityById(id: string): Promise<City> {
const response = await fetch(`${API_BASE_URL}/cities/${id}`);
const data: CityResponse = await response.json();
if (!data.success || !data.data) {
throw new Error(data.error || 'City not found');
}
return data.data;
}
/**
* Search cities by name
*/
async searchCities(name: string): Promise<City[]> {
const response = await fetch(`${API_BASE_URL}/cities/search/${encodeURIComponent(name)}`);
const data: CitiesResponse = await response.json();
if (!data.success || !data.data) {
throw new Error(data.error || 'Failed to search cities');
}
return data.data;
}
/**
* Update a city
*/
async updateCity(id: string, nome: string): Promise<City> {
const request: UpdateCityRequest = { nome };
const response = await fetch(`${API_BASE_URL}/cities/${id}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(request),
});
const data: CityResponse = await response.json();
if (!data.success || !data.data) {
throw new Error(data.error || 'Failed to update city');
}
return data.data;
}
/**
* Delete a city
*/
async deleteCity(id: string): Promise<void> {
const response = await fetch(`${API_BASE_URL}/cities/${id}`, {
method: 'DELETE',
});
const data: DeleteResponse = await response.json();
if (!data.success) {
throw new Error(data.message || 'Failed to delete city');
}
}
}