ProductStore, move API calls to separate file

This commit is contained in:
2024-09-18 15:59:16 +02:00
parent 2847bd940f
commit 9ee344f45f
8 changed files with 133 additions and 123 deletions

View File

@@ -0,0 +1,10 @@
import axios from "axios"
let BASE_URL = "http://localhost:3000/products"
/**
* Fetch all products from API
*/
export async function getAllProducts() {
return await axios.get(BASE_URL)
}

View File

@@ -0,0 +1,6 @@
export enum SortOrder {
PRICELOWTOHIGH = "Price: Low to high",
PRICEHIGHTOLOW = "Price: High to low",
NAMEATOZ = "Name: A to Z",
NAMEZTOA = "Name: Z to A"
}

View File

@@ -0,0 +1,73 @@
import { useLocalStorage } from "@vueuse/core";
import { defineStore } from "pinia";
import { ProductModel } from "../models/productModel";
import { getAllProducts } from "../api/productApi";
import { SortOrder } from "../enums/sortOrderEnum";
import { CategoryModel } from "../models/categoryModel";
export const useProductStore = defineStore("productStore", {
state: () => ({
products: useLocalStorage<Array<ProductModel>>("hackmycart/productStore/products", []),
filteredProducts: useLocalStorage<Array<ProductModel>>("hackmycart/productStore/filteredProducts", []),
sortOrder: useLocalStorage<SortOrder>("hackmycart/productStore/sortOrder", SortOrder.NAMEATOZ),
filteredCategory: useLocalStorage<CategoryModel>("hackmycart/productStore/filteredCategory", new CategoryModel()),
onlyDiscounts: useLocalStorage<Boolean>("hackmycart/productStore/onlyDiscounts", false)
}),
actions: {
async fetchAllProducts() {
await getAllProducts()
.then(products => {
this.products = products.data
this.filteredProducts = products.data
})
},
async filterProducts() {
if (this.filteredCategory.id == -1) {
this.filteredProducts = this.products
} else {
this.filteredProducts = this.products.filter((product: ProductModel) =>
product.categoryId == this.filteredCategory.id
)
}
if (this.onlyDiscounts) {
this.filteredProducts = this.filteredProducts.filter((product: ProductModel) =>
product.discount > 0
)
}
},
sortProducts() {
this.filteredProducts.sort((a: ProductModel, b: ProductModel) => {
switch (this.sortOrder)
{
case SortOrder.PRICELOWTOHIGH: {
return a.price - b.price
}
case SortOrder.PRICEHIGHTOLOW: {
return b.price - a.price
}
case SortOrder.NAMEATOZ: {
if (b.name > a.name) {
return -1
}
else {
return 1
}
}
case SortOrder.NAMEZTOA: {
if (b.name < a.name) {
return -1
}
else {
return 1
}
}
}
})
}
}
})