@scayle/storefront-nuxt
Version:
Nuxt integration for the SCAYLE Commerce Engine and Storefront API
93 lines (92 loc) • 2.67 kB
JavaScript
import { useNuxtApp } from "nuxt/app";
import { useRpc } from "../core/useRpc.js";
import { extendPromise } from "../../utils/promise.js";
import { computed, toValue, toRef } from "vue";
import { useRpcCall } from "../core/useRpcCall.js";
export function useWishlist({ params } = {}, key = "useWishlist") {
const nuxtApp = useNuxtApp();
const addItemToWishlistRpc = useRpcCall("addItemToWishlist");
const removeItemFromWishlistRpc = useRpcCall("removeItemFromWishlist");
const clearWishlistRpc = useRpcCall("clearWishlist");
const asyncData = useRpc("getWishlist", key, params, {
server: false,
// NOTE: In some cases it might be ok to fetch on server
watch: [toRef(params)],
dedupe: "defer",
getCachedData: (key2) => {
return toValue(nuxtApp._asyncData[key2]?.data) ?? void 0;
}
});
const { data, error, status, refresh } = asyncData;
const addItem = async (item) => {
data.value = await addItemToWishlistRpc({
...item,
with: toValue(params)
});
};
const findItem = (item) => {
return data.value?.items?.find((entry) => {
if ("variantId" in item) {
return entry.variant?.id === item.variantId;
}
return entry.product?.id === item.productId;
});
};
const removeItem = async (item) => {
const element = findItem(item);
if (!element) {
throw new Error("Could not find wishlist item.");
}
data.value = await removeItemFromWishlistRpc({
itemKey: element.key,
with: toValue(params)
});
};
const replaceItem = async (item, newItem) => {
const element = findItem(item);
if (!element) {
throw new Error(
`Could not find wishlist item by: ${JSON.stringify(item)}`
);
}
await removeItemFromWishlistRpc({
with: toValue(params),
itemKey: element.key
});
data.value = await addItemToWishlistRpc({
...newItem,
with: toValue(params)
});
};
const clear = async () => {
data.value = await clearWishlistRpc();
};
const contains = (item) => {
return findItem(item) !== void 0;
};
const toggleItem = async (item) => {
const element = findItem(item);
await (element ? removeItem(item) : addItem(item));
};
const count = computed(() => data.value?.items.length);
const items = computed(() => data.value?.items);
const products = computed(() => {
return items.value?.map((item) => item.product) || [];
});
return extendPromise(asyncData, {
data,
count,
items,
products,
addItem,
removeItem,
replaceItem,
clear,
refresh,
toggleItem,
findItem,
contains,
error,
status
});
}