Newer
Older
job-tracker / frontend / src / api.js
import axios from 'axios';
const api=axios.create({
    baseURL: "/api",  // proxy forwards to http://localhost:8080/api
});

export async function apiGet(path) {
    const token = localStorage.getItem('token');
    const headers = { 'Content-Type': 'application/json' };
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
    const res = await fetch(path, { headers });
    if (!res.ok) throw new Error(await res.text());
    return res.json();
}

export async function apiExport(path) {
  const token = localStorage.getItem('token');
  const headers = {};
  if (token) {
    headers['Authorization'] = `Bearer ${token}`;
  }
  const res = await fetch(path, { headers });
  if (!res.ok) throw new Error('Export failed');
  return res;
}

export async function apiPost(path, body) {
    const token = localStorage.getItem('token');
    const headers = { 'Content-Type': 'application/json' };
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
    const res = await fetch(path, {
        method: "POST",
        headers,
        body: JSON.stringify(body)
    });
    if(!res.ok) throw new Error(await res.text());
    return res.json();
}

export async function apiPut(path, body) {
    const token = localStorage.getItem('token');
    const headers = { 'Content-Type': 'application/json' };
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
    const res = await fetch(path, {
        method: "PUT",
        headers,
        body: JSON.stringify(body)
    });
    if(!res.ok) throw new Error(await res.text());
    return res.json();
}

export async function apiDelete(path) {
    const token = localStorage.getItem('token');
    const headers = {};
    if (token) {
      headers['Authorization'] = `Bearer ${token}`;
    }
    const response = await fetch(path, {
        method: 'DELETE',
        headers
    });
    if (!response.ok) {
        throw new Error(`DELETE ${path} failed: ${response.statusText}`);
    }
    return true;
}
export default api;