schon/storefront/app/composables/orders/useOrders.ts
2026-02-27 21:59:51 +03:00

78 lines
1.6 KiB
TypeScript

import { orderStatuses } from '@appConstants';
import { GET_ORDERS } from '@graphql/queries/standalone/orders';
import type { IOrdersResponse } from '@types';
interface IOrdersArguments {
userEmail: string;
status?: string;
after?: string;
search: string;
}
interface IOrderVars {
status: string;
userEmail: string;
first: number;
after?: string;
search: string;
}
export async function useOrders(args: IOrdersArguments) {
const cartStore = useCartStore();
const variables = reactive<IOrderVars>({
status: args.status || '',
userEmail: args.userEmail,
first: 10,
after: args.after,
search: args.search,
});
const { pending, data, error, refresh } = await useAsyncQuery<IOrdersResponse>(GET_ORDERS, variables);
const orders = ref(
data.value?.orders.edges.filter((order) => order.node.status !== orderStatuses.PENDING) ?? [],
);
const pageInfo = computed(() => data.value?.orders.pageInfo ?? null);
if (!error.value && data.value?.orders.edges) {
if (args.status === orderStatuses.PENDING) {
cartStore.setCurrentOrders(data.value?.orders.edges[0].node);
}
}
watch(
() => variables.after,
async (newCursor, oldCursor) => {
if (!newCursor || newCursor === oldCursor) return;
await refresh();
const newEdges = data.value?.orders.edges ?? [];
orders.value.push(...newEdges);
},
);
watch(
[
() => variables.status,
() => variables.search,
],
async () => {
variables.after = '';
await refresh();
orders.value = data.value?.orders.edges ?? [];
},
);
watch(error, (err) => {
if (err) {
console.error('useOrders error:', err);
}
});
return {
pending,
orders,
pageInfo,
variables,
};
}