Skip to content
Snippets Groups Projects
API.js 6.08 KiB
Newer Older
Ingrid's avatar
Ingrid committed
import axios from "axios";
Sondre Malerud's avatar
Sondre Malerud committed
import { useAuthStore } from "@/stores/authStore.js";
import jwt_decode from "jwt-decode";
import router from "@/router/index";

export const API = {

    /**
     * API method to send a login request.
     * If login succeeds, the logged in User and their token
     * is saved to the Pinia AuthStore
     *
     * @param email email address of the user to log in as
     * @param password password to log in with
     * @returns a Result with whether the login attempt succeeded
     */
    login: async (request) => {
        const authStore = useAuthStore();
        let token;
Sondre Malerud's avatar
Sondre Malerud committed
        authStore.logout(); //in case someone for some reason is logged in
Sondre Malerud's avatar
Sondre Malerud committed

        return axios.post(
            `${import.meta.env.VITE_BACKEND_URL}/login`,
            request,
          )
            .then(async (response) => {
              token = response.data;
              const id = (jwt_decode(token)).id;
Ingrid's avatar
Ingrid committed

Sondre Malerud's avatar
Sondre Malerud committed
              return API.getAccount(id, token)
                .then((user) => {
Sondre Malerud's avatar
Sondre Malerud committed
                  authStore.setAccount(user);
Sondre Malerud's avatar
Sondre Malerud committed
                  authStore.setToken(token);
Sondre Malerud's avatar
Sondre Malerud committed
                  API.getProfiles()
                    .then(response => {authStore.setProfiles(response)})
                    .catch(() => {throw new Error()})
Sondre Malerud's avatar
Sondre Malerud committed
                  return;
                })
                .catch(() => {
                  throw new Error();
                });
            })
            .catch(() => {
              throw new Error();
            });
        },


    /**
     * API method to get a account by their ID
     * @param id ID number of the account to retrieve
     * @returns A promise that resolves to a User if the API call succeeds,
     * or is rejected if the API call fails
     */
    getAccount: async (id, token) => {
        return axios.get(`${import.meta.env.VITE_BACKEND_URL}/account/${id}`, {
            headers: { Authorization: `Bearer ${token}` },
          })
          .then((response) => {
            return response.data;
          })
          .catch(() => {
            throw new Error("Account not found or not accessible");
          });
      },

    // Sends the user into the home page logged in as the profile they clicked on
    selectProfile: async (id) => {
        const authStore = useAuthStore()
        return axios.get(`${import.meta.env.VITE_BACKEND_URL}/profile/${id}`, {
            headers: { Authorization: `Bearer ${authStore.token}` },
          })
          .then((response) => {
            authStore.setProfile(response.data)
            router.push("/")
Ingrid's avatar
Ingrid committed

Sondre Malerud's avatar
Sondre Malerud committed
          })
          .catch(() => {
            throw new Error("Profile not found or not accessible")
          })


    },

Ingrid's avatar
Ingrid committed
    // Sends the user into the "register profile" view
Sondre Malerud's avatar
Sondre Malerud committed
    addProfile: async () => {
        console.log("todo");
    },

    // Returns all profiles to the logged in user
    getProfiles: async () => {
        const authStore = useAuthStore();
        if (!authStore.isLoggedIn) {
            throw new Error();
        }

        return axios.get(import.meta.env.VITE_BACKEND_URL + '/profile', {
            headers: { Authorization: "Bearer " + authStore.token },
          },
        )
          .then(response => {
            return response.data
          }).catch(() => {
            throw new Error();
          });
Sondre Malerud's avatar
Sondre Malerud committed
    },

    // Registers a new account and logs into it
    addAccount: async (request) => {
        const authStore = useAuthStore();

        axios.post(import.meta.env.VITE_BACKEND_URL + '/account', request)
        .then(() => {
            API.login({email: request.email, password: request.password})
                .catch(err => {console.log(err)})
        })
        .catch(() => {throw new Error()})
Ingrid's avatar
Ingrid committed
    /**
     * fetches all fridge items belonging to user
     * @returns {Promise<*>}
Ingrid's avatar
Ingrid committed
     */
    getFridgeItems: async () =>{
        const authStore = useAuthStore();

        return axios.get(`${import.meta.env.VITE_BACKEND_URL}/fridge`, {
            headers: { Authorization: `Bearer ${authStore.token}` },
        })
Ingrid's avatar
Ingrid committed
            .then((response) => {
                return response.data;
            }).catch(() => {
                throw new Error("Could not fetch fridge items");
            });
    },

    //returns fridgeItem of specific id
    getFridgeItem: async (id) =>{
        const authStore = useAuthStore();

        axios.get(`${import.meta.env.VITE_BACKEND_URL}/fridge/${id}`, {
            headers: { Authorization: `Bearer ${authStore.token}` },
        })
            .then((response) => {
                return response.data;
            })
            .catch(() => {
                throw new Error("Could not fetch fridge item");
Ingrid's avatar
Ingrid committed
            });
    },

    /**
     * Adds item(s) to the fridge
     * @param request List<Ingredient> listOfIngredients
     * @returns {Promise<void>}
     */
    addToFridge: async(request) =>{
        const authStore = useAuthStore();
        axios.post(`${import.meta.env.VITE_BACKEND_URL}/fridge`, request,{
            headers: { Authorization: `Bearer ${authStore.token}` },
        }).then((response) => {
            return response.data;
        }).catch(()=> {
            throw new Error("Could not add item to fridge: ");
        })

},

    /**
     * Array(3) [ {…}, {…}, {…} ]
     * 0: Object { name: "Tomat", ean: "7040512550214", shelfLife: 10, … }
     * allergens: Array []
     * amount: Object { quantity: 4, unit: "stk" }
     * quantity: 4
     * unit: "stk"
     * <prototype>: Object { … }
     * ean: "7040512550214"
     * image_url: "https://bilder.ngdata.no/7040512550818/meny/large.jpg"
     * name: "Tomat"
     * nutrition: Array(11) [ {…}, {…}, {…}, … ]
     * shelfLife: 10
     * store: null
     */

    /**
     * Searches for available items
     * @param searchPhrase
     * @returns {Promise<*>}
    searchItems: async(searchPhrase)=> {
        return axios.get(`${import.meta.env.VITE_BACKEND_URL}/item/search?name=${searchPhrase}`, {
        }).then((response) => {
            console.log(response.data.content);
            return response.data.content;
        }).catch(()=> {
            throw new Error("Error when searching for item ");
        })
Ingrid's avatar
Ingrid committed
    }

Ingrid's avatar
Ingrid committed
}