Skip to content
Snippets Groups Projects
API.js 5.1 KiB
Newer Older
Ingrid Martinsheimen Egge's avatar
API
Ingrid Martinsheimen Egge 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";
Ingrid Martinsheimen Egge's avatar
API
Ingrid Martinsheimen Egge committed
export const API = {
Sondre Malerud's avatar
Sondre Malerud committed

Ingrid Martinsheimen Egge's avatar
API
Ingrid Martinsheimen Egge committed
    /**
Sondre Malerud's avatar
Sondre Malerud committed
     * 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
Ingrid Martinsheimen Egge's avatar
API
Ingrid Martinsheimen Egge committed
     */
Sondre Malerud's avatar
Sondre Malerud committed
    login: async (request) => {
        const authStore = useAuthStore();
        let token;

        return axios.post(
            `${import.meta.env.VITE_BACKEND_URL}/login`,
            request,
          )
            .then(async (response) => {
              token = response.data;
              const id = (jwt_decode(token)).id;
Sondre Malerud's avatar
Sondre Malerud committed
              return API.getAccount(id, token)
                .then((user) => {
                  authStore.setUser(user);
                  authStore.setToken(token);
                  return;
                })
                .catch(() => {
                  throw new Error();
                });
            })
            .catch(() => {
              throw new Error();
Ingrid Martinsheimen Egge's avatar
API
Ingrid Martinsheimen Egge committed
            });
Sondre Malerud's avatar
Sondre Malerud committed
        },


    /**
     * 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("/")
Sondre Malerud's avatar
Sondre Malerud committed
          })
          .catch(() => {
            throw new Error("Profile not found or not accessible")
          })


    },

    // 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();
        }

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

            console.log(response.data)
            return response.data
          }).catch(() => {
            throw new Error();
          });
Ingrid Martinsheimen Egge's avatar
Ingrid Martinsheimen Egge committed
     * Deletes account from the
     * @param id
     * @param token
     * @returns {Promise<*>}
    deleteAccount: async (id) => {
        const authStore = useAuthStore();
        if (!authStore.isLoggedIn) {
            throw new Error();
        }

        return axios.delete(`${import.meta.env.VITE_BACKEND_URL}/account/${id}`, {
            headers: { Authorization: `Bearer ${authStore.token}` },
Ingrid Martinsheimen Egge's avatar
Ingrid Martinsheimen Egge committed
        })
            .then(() => {
                authStore.logout()
                router.push('/login')
Ingrid Martinsheimen Egge's avatar
Ingrid Martinsheimen Egge committed
            })
            .catch(() => {
                throw new Error("");
Ingrid Martinsheimen Egge's avatar
Ingrid Martinsheimen Egge committed
            });
Ingrid Martinsheimen Egge's avatar
Ingrid Martinsheimen Egge committed

     *
     * @param id account id
     * @param request password and firstname
     * @returns {Promise<*>}
    updateAccount: async (id, request) => {
        const authStore = useAuthStore();
        if (!authStore.isLoggedIn) {
            throw new Error();
        }

        return axios.put(`${import.meta.env.VITE_BACKEND_URL}/account/${id}`,request, {
                headers: { Authorization: `Bearer ${authStore.token}` },
            })
Ingrid Martinsheimen Egge's avatar
Ingrid Martinsheimen Egge committed
            .then((response) => {
                authStore.setUser(response.data)
Ingrid Martinsheimen Egge's avatar
Ingrid Martinsheimen Egge committed
                return response.data;
            }).catch(() => {
                throw new Error("Error when updating account: ");
    /**
     * Updates the profile name, restriction and profile image
     * @param id profile id
     * @param request
     * @returns {Promise<*>}
     */
Ingrid Martinsheimen Egge's avatar
Ingrid Martinsheimen Egge committed
    updateProfile: async (id, request) => {
        const authStore = useAuthStore();
        if (!authStore.isLoggedIn) {
            throw new Error();
        }
Ingrid Martinsheimen Egge's avatar
Ingrid Martinsheimen Egge committed
        return axios.put(`${import.meta.env.VITE_BACKEND_URL}/profile/${id}`,request, {
            headers: { Authorization: `Bearer ${authStore.token}` },
Ingrid Martinsheimen Egge's avatar
Ingrid Martinsheimen Egge committed
        })
            .then((response) => {
                authStore.setProfile(response.data)
Ingrid Martinsheimen Egge's avatar
Ingrid Martinsheimen Egge committed
                return response.data;
            })
Ingrid Martinsheimen Egge's avatar
Ingrid Martinsheimen Egge committed
            .catch((error) => {
                throw new Error("Error when updating profile: " + error);
Ingrid Martinsheimen Egge's avatar
API
Ingrid Martinsheimen Egge committed
}