Files
SweetHome/app/utils/api.js

111 lines
3.0 KiB
JavaScript
Raw Normal View History

const API_BASE = process.env.NEXT_PUBLIC_API_URL || 'http://45.93.137.91/api';
async function apiFetch(endpoint, options = {}) {
const token = typeof window !== 'undefined' ? localStorage.getItem('token') : null;
const headers = {
'Content-Type': 'application/json',
...(token && { Authorization: `Bearer ${token}` }),
...options.headers,
};
const res = await fetch(`${API_BASE}${endpoint}`, {
...options,
headers,
});
if (!res.ok) {
const text = await res.text().catch(() => '');
throw new Error(`API ${res.status}: ${text || res.statusText}`);
}
const text = await res.text();
if (!text) return null;
try {
const json = JSON.parse(text);
// API wraps responses in { data, errors, isSuccess, isFailure, statusCode }
if (json && typeof json === 'object' && 'data' in json) {
return json.data;
}
return json;
} catch {
return text;
}
}
// ─── Rent Properties ───
export async function getRentProperties() {
return apiFetch('/RentProperties/GetRentProperties');
}
export async function getRentProperty(id) {
return apiFetch(`/RentProperties/GetRentProperties?id=${id}`);
}
export async function getRentPropertyLocations(params = {}) {
const qs = new URLSearchParams();
if (params.maxOffset != null) qs.set('maxOffset', params.maxOffset);
if (params.minOffset != null) qs.set('minOffset', params.minOffset);
const query = qs.toString();
return apiFetch(`/RentProperties/GetRentPropertiesLocations${query ? `?${query}` : ''}`);
}
// ─── Sale Properties ───
export async function getSaleProperties() {
return apiFetch('/SaleProperties/GetSaleProperties');
}
export async function getSaleProperty(id) {
return apiFetch(`/SaleProperties/GetSaleProperties?id=${id}`);
}
// ─── Properties (generic) ───
export async function getProperty(id) {
return apiFetch(`/Properties/Get/${id}`);
}
// ─── Recommendations ───
export async function getRecommendations() {
return apiFetch('/Recommendations/GetRecommendations');
}
export async function getTopRecommendations(count = 10) {
return apiFetch(`/Recommendations/GetTopRecommendations?count=${count}`);
}
// ─── Reservations ───
export async function getReservations() {
return apiFetch('/Reservations/GetReservations');
}
export async function getReservation(id) {
return apiFetch(`/Reservations/GetReservation?id=${id}`);
}
export async function checkAvailability(propertyId, fromDate = null, toDate = null) {
const qs = new URLSearchParams();
if (fromDate) qs.set('fromDate', fromDate);
if (toDate) qs.set('toDate', toDate);
const query = qs.toString();
return apiFetch(`/Reservations/GetAvailable/${propertyId}${query ? `?${query}` : ''}`);
}
export async function bookReservation(data) {
return apiFetch('/Reservations/Book', {
method: 'POST',
body: JSON.stringify(data),
});
}
// ─── Terms ───
export async function getTerms() {
return apiFetch('/Terms/GetTerms');
}