import { ref } from 'vue' import { useAuthStore } from './auth.store.js' const baseUrl = "http://localhost:8080" function useFetch(url) { const data = ref(null); const error = ref(null); const { user } = useAuthStore(); if (user != null) { fetch(url, { method: 'GET', headers: { 'Authorization': 'Bearer ' + user.token } }) .then((res) => res.json()) .then((json) => (data.value = json)) .catch((err) => (error.value = err)); } return { data, error } } export function getMyBooks() { return useFetch(baseUrl + '/mybooks'); } export function getSearchBooks(searchterm) { return useFetch(baseUrl + '/search/' + searchterm); } export function postBook(book) { return genericPostCall('/book', book.value) } export function postLogin(user) { return genericPostCallNoAuth('/auth/login', user.value) } export function postSignUp(user) { return genericPostCallNoAuth('/auth/signup', user.value) } export function genericPostCallNoAuth(apiRoute, object) { return fetch(baseUrl + apiRoute, { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(object) }) } export function genericPostCall(apiRoute, object) { const { user } = useAuthStore(); if (user != null) { return fetch(baseUrl + apiRoute, { method: 'POST', headers: { 'Content-Type': 'application/json', 'Authorization': 'Bearer ' + user.token }, body: JSON.stringify(object) }) } else { return Promise.resolve(); } } export function extractFormErrorFromField(fieldName, errors) { if (errors === null) { return ""; } const titleErr = errors.find((e) => e["field"] === fieldName); if (typeof titleErr !== 'undefined') { return titleErr.error; } else { return ""; } } export function extractGlobalFormError(errors) { if (errors !== null && "error" in errors) { return errors["error"]; } else { return ""; } }