67 lines
1.6 KiB
TypeScript
67 lines
1.6 KiB
TypeScript
// imports
|
|
|
|
import { useInfiniteQuery } from "@tanstack/vue-query";
|
|
import { API_ENDPOINTS, QUERY_KEYS } from "~/constants";
|
|
import { useAuth } from "~/composables/api/auth/useAuth";
|
|
|
|
// types
|
|
|
|
export type GetChatResponse = ApiPaginated<Chat>;
|
|
|
|
const useGetChat = (productId: string | number, enabled: Ref<boolean>) => {
|
|
// state
|
|
|
|
const { $axios: axios } = useNuxtApp();
|
|
|
|
const { isLoggedIn } = useAuth();
|
|
|
|
const isEnabled = computed(() => {
|
|
return enabled.value && isLoggedIn.value;
|
|
});
|
|
|
|
// methods
|
|
|
|
const handleGetChat = async ({
|
|
productId,
|
|
limit,
|
|
offset,
|
|
}: {
|
|
productId: number | string;
|
|
limit: number;
|
|
offset: number;
|
|
}) => {
|
|
const { data } = await axios.get<GetChatResponse>(`${API_ENDPOINTS.chat.messages}/${productId}`, {
|
|
params: {
|
|
offset,
|
|
limit,
|
|
},
|
|
});
|
|
return data;
|
|
};
|
|
|
|
return useInfiniteQuery({
|
|
enabled: isEnabled,
|
|
queryKey: [QUERY_KEYS.chat],
|
|
initialPageParam: {
|
|
limit: 10,
|
|
offset: 0,
|
|
},
|
|
queryFn: ({ pageParam }) =>
|
|
handleGetChat({
|
|
limit: pageParam.limit,
|
|
offset: pageParam.offset,
|
|
productId: productId,
|
|
}),
|
|
getNextPageParam: (lastPage, pages) => {
|
|
if (!lastPage.next) return undefined;
|
|
|
|
return {
|
|
limit: 10,
|
|
offset: pages.length * 10,
|
|
};
|
|
},
|
|
});
|
|
};
|
|
|
|
export default useGetChat;
|