import type { InfiniteQueryObserverOptions, MutationKey, InfiniteData, } from "@tanstack/query-core"; import { type WeavyType } from "../client/weavy"; import { addCacheItem, getCacheItem, getPendingCacheItem, updateCacheItem, updateCacheItems } from "../utils/query-cache"; import { PostType } from "../types/posts.types"; import { PollOptionType } from "../types/polls.types"; import { CommentType, CommentsResultType, MutateCommentProps } from "../types/comments.types"; import { EntityTypeString } from "../types/app.types"; import { firstPageParam, initialPageParam, lastPageParam, queryPageParams } from "./api"; import { QueryPagingAroundType } from "../types/query.types"; export type CommentsQueryKeyType = ["posts" | "files" | "apps", "comments", number | null, number | undefined]; export function getCommentsOptions( weavy: WeavyType, type: "posts" | "files" | "apps", parentId: number | null, around?: number, options: object = {} ): InfiniteQueryObserverOptions> { const commentsKey: CommentsQueryKeyType = [type, "comments", parentId, around]; return { ...options, initialPageParam: initialPageParam(around), queryKey: commentsKey, queryFn: async (opt) => { const queryParams = queryPageParams(opt.pageParam as QueryPagingAroundType); const url = `/api/${type}/${parentId}/comments?order_by=id&${queryParams.toString()}`; const response = await weavy.fetch(url); const result = await response.json() as CommentsResultType; result.data = result.data || []; return result; }, getPreviousPageParam: firstPageParam(), getNextPageParam: lastPageParam(), }; } export function getUpdateCommentMutationOptions(weavy: WeavyType, mutationKey: MutationKey) { const options = { mutationFn: async (variables: MutateCommentProps) => { const response = await weavy.fetch("/api/comments/" + variables.id, { method: "PATCH", body: JSON.stringify({ text: variables.text, blobs: variables.blobs, attachments: variables.attachments, meeting_id: variables.meeting_id, options: (variables.poll_options || []) .filter((o: PollOptionType) => o.text.trim() !== "") .map((o: PollOptionType) => { return { id: o.id, text: o.text }; }), embed_id: variables.embed_id || null, }), }); return await response.json() as CommentType; }, mutationKey: mutationKey, onSuccess: (data: CommentType, variables: MutateCommentProps) => { if (variables.id) { updateCacheItems(weavy.queryClient, { queryKey: [variables.type, "comments", variables.parent_id], exact: false}, variables.id, () => data); } }, }; return options; } export function getAddCommentMutationOptions(weavy: WeavyType) { const queryClient = weavy.queryClient; const options = { mutationFn: async (variables: MutateCommentProps) => { const response = await weavy.fetch("/api/" + variables.type + "/" + variables.parent_id + "/comments", { method: "POST", body: JSON.stringify({ text: variables.text, blobs: variables.blobs, meeting_id: variables.meeting_id, options: (variables.poll_options || []) .filter((o: PollOptionType) => o.text.trim() !== "") .map((o: PollOptionType) => { return { text: o.text }; }), embed_id: variables.embed_id, context: variables.context }), }); return await response.json() as CommentType; }, onMutate: async (variables: MutateCommentProps) => { const commentsKey = [variables.type, "comments", variables.parent_id]; await queryClient.cancelQueries({ queryKey: commentsKey, exact: false }); const queries = queryClient.getQueryCache().findAll({ queryKey: commentsKey, exact: false }); queries.forEach(({ queryKey }) => { const newest = getPendingCacheItem(weavy.queryClient, queryKey, false); if (variables.user) { const tempData: CommentType = { id: newest ? newest.id - 1 : -1, app: variables.type === "apps" ? { id: variables.parent_id } : { id: -1 }, is_trashed: false, text: variables.text, html: variables.text, plain: variables.text, created_by: variables.user, created_at: new Date().toUTCString(), attachments: { count: 0 }, reactions: { count: 0 }, is_subscribed: false, is_starred: false, }; if (variables.type === "files") { tempData.parent = { type: EntityTypeString.File, id: variables.parent_id }; } else if (variables.type === "posts") { tempData.parent = { type: EntityTypeString.Post, id: variables.parent_id }; } addCacheItem(queryClient, queryKey, tempData, { descending: false }); } }) }, onSuccess: (comment: CommentType, variables: MutateCommentProps) => { const commentsKey = [variables.type, "comments", comment.parent?.id ?? comment.app?.id]; const queries = queryClient.getQueryCache().findAll({ queryKey: commentsKey, exact: false }); let wasChanged = false; queries.forEach(({ queryKey }) => { // check if comment already added const existing = getCacheItem(weavy.queryClient, queryKey, comment.id); if (!existing) { // get oldest pending comment const pending = getPendingCacheItem(weavy.queryClient, queryKey, true); if (pending) { // we found a pending comment - replace it with new data updateCacheItem(weavy.queryClient, queryKey, pending.id, () => comment); } else { // add to cache // REVIEW: behövs { descending: false }? // addCacheItem(queryClient, ["comments", variables.parentId], data, { descending: false }); addCacheItem(weavy.queryClient, queryKey, comment); } wasChanged = true; } }); if (wasChanged) { // update cache with number of comments if (comment.parent?.type === EntityTypeString.Post && comment.app) { updateCacheItems(queryClient, { queryKey: ["posts", comment.app.id], exact: false }, comment.parent.id, (item) => { if (item.comments) { item.comments.count += 1; } else { item.comments = { count: 1 }; } return item; }); updateCacheItems(queryClient, { queryKey: ["posts", "feed"], exact: false }, comment.parent.id, (item) => { if (item.comments) { item.comments.count += 1; } else { item.comments = { count: 1 }; } return item; }); } } }, }; return options; }