Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 | 3x 21x 21x 21x 21x 21x 21x 21x 1x 1x 21x 2x 19x 3x 13x 3x 1x 3x 1x 3x 1x 3x 1x 3x 3x 3x 2x 3x 1x 3x 1x 3x 3x 3x 3x 3x 3x 3x | /**
* src/db/api.js — REST API client for the Next.js backend
*
* Todas as funções fazem fetch para /api/* (proxiado pelo Vite para o Next.js
* em localhost:3001 em dev, e configurado no servidor em produção).
*/
const BASE = '/api';
async function http(method, path, body, extraHeaders = {}) {
const token = typeof window !== 'undefined' ? localStorage.getItem('auth_token') : null;
const isAuthEndpoint = path.startsWith('/users/login') || path.startsWith('/users/register');
const options = {
method,
headers: {
'Content-Type': 'application/json',
...(token && !isAuthEndpoint ? { Authorization: `Bearer ${token}` } : {}),
...extraHeaders,
},
};
if (body !== undefined) options.body = JSON.stringify(body);
const res = await fetch(`${BASE}${path}`, options);
const data = await res.json().catch(() => ({}));
if (res.status === 401 && typeof window !== 'undefined') {
localStorage.removeItem('auth_user');
localStorage.removeItem('auth_token');
}
if (!res.ok) {
throw new Error(data.error || `HTTP ${res.status}`);
}
return data;
}
// ── Products ──────────────────────────────────────────────────────────────────
export const getProducts = (category) =>
http('GET', `/products${category ? `?category=${encodeURIComponent(category)}` : ''}`);
export const getProductById = (id) =>
http('GET', `/products/${id}`);
// ── Users ────────────────────────────────────────────────────────────────────
export const registerUser = (userData) =>
http('POST', '/users/register', userData);
export const getUserByEmail = (email) =>
http('POST', '/users/login-lookup', { email });
export const loginUser = ({ email, password }) =>
http('POST', '/users/login', { email, password });
export const getMe = () =>
http('GET', '/users/me');
export const updateMyAddress = (payload) =>
http('PUT', '/users/me/address', payload);
// ── Cart ─────────────────────────────────────────────────────────────────────
export const getCartItems = (userId) =>
http('GET', `/cart?userId=${userId}`);
export const upsertCartItem = (products) =>
http('POST', '/cart', { products });
export const removeCartItem = (cartItemId) =>
http('DELETE', '/cart', { cartItemId });
// ── Orders ───────────────────────────────────────────────────────────────────
export const createOrder = ({
shippingTotal = 0,
discountTotal = 0,
paymentMethod = null,
shippingAddress = null,
billingInfo = null,
items = null,
idempotencyKey = null,
} = {}) => {
const headers = {};
if (idempotencyKey) {
headers['Idempotency-Key'] = idempotencyKey;
}
return http(
'POST',
'/orders',
{
shippingTotal,
discountTotal,
paymentMethod,
shippingAddress,
billingInfo,
items,
},
headers
);
};
export const getOrders = (params = {}) => {
const search = new URLSearchParams();
Object.entries(params).forEach(([key, value]) => {
if (value !== undefined && value !== null && value !== '') {
search.set(key, String(value));
}
});
const query = search.toString();
return http('GET', `/orders${query ? `?${query}` : ''}`);
};
export const getOrderById = (id) =>
http('GET', `/orders/${id}`);
export const createOrderPayment = (orderId, payload = {}) =>
http('POST', `/orders/${orderId}/payments`, payload);
export const getOrderPaymentStatus = (orderId, paymentId) =>
http('GET', `/orders/${orderId}/payments/${paymentId}`);
// ── Account helpers ──────────────────────────────────────────────────────────
export const getMyOrders = (params = {}) =>
getOrders(params);
export const getMyOrderById = (id) =>
getOrderById(id);
|