diff --git a/src/components/DocFeedbackNote.tsx b/src/components/DocFeedbackNote.tsx index a0918a5d8..5ed139401 100644 --- a/src/components/DocFeedbackNote.tsx +++ b/src/components/DocFeedbackNote.tsx @@ -1,11 +1,7 @@ import * as React from 'react' import { twMerge } from 'tailwind-merge' -import { useMutation, useQueryClient } from '@tanstack/react-query' -import { - deleteDocFeedback, - updateDocFeedback, - updateDocFeedbackCollapsed, -} from '~/utils/docFeedback.functions' +import { useMutation } from '@tanstack/react-query' +import { docFeedbackMutations } from '~/queries/docFeedback' import type { DocFeedback } from '~/db/types' import { CaretDownIcon, @@ -23,23 +19,11 @@ interface DocFeedbackNoteProps { inline?: boolean } -// Types for the query cache data structures -interface DocPageCacheData { - userFeedback: DocFeedback[] -} - -interface AccountPageCacheData { - feedback: DocFeedback[] -} - -type DocFeedbackCacheData = DocPageCacheData | AccountPageCacheData | unknown - export function DocFeedbackNote({ note, anchorName, inline = false, }: DocFeedbackNoteProps) { - const queryClient = useQueryClient() const [isDeleting, setIsDeleting] = React.useState(false) const [deleteError, setDeleteError] = React.useState(null) const [content, setContent] = React.useState(note.content) @@ -86,197 +70,33 @@ export function DocFeedbackNote({ const preview = firstLine.length > 60 ? firstLine.substring(0, 60) + '...' : firstLine - const deleteMutation = useMutation({ - mutationFn: deleteDocFeedback, - onMutate: async () => { - // Cancel any outgoing refetches - await queryClient.cancelQueries({ queryKey: ['docFeedback'] }) - - // Snapshot the previous value - const previousData = queryClient.getQueriesData({ - queryKey: ['docFeedback'], - }) - - // Optimistically remove the note from all matching queries - queryClient.setQueriesData( - { queryKey: ['docFeedback'] }, - (old: DocFeedbackCacheData) => { - if (!old || typeof old !== 'object') return old - - // Handle doc page structure (userFeedback) - if ('userFeedback' in old && Array.isArray(old.userFeedback)) { - return { - ...old, - userFeedback: old.userFeedback.filter( - (f: DocFeedback) => f.id !== note.id, - ), - } - } - - // Handle account/notes page structure (feedback) - if ('feedback' in old && Array.isArray(old.feedback)) { - return { - ...old, - feedback: old.feedback.filter( - (f: DocFeedback) => f.id !== note.id, - ), - } - } - - return old - }, - ) - - return { previousData } - }, - onError: (error: Error, variables, context) => { - // Rollback on error - if (context?.previousData) { - context.previousData.forEach(([queryKey, data]) => { - queryClient.setQueryData(queryKey, data) - }) - } - setDeleteError(error.message) - setIsDeleting(false) - }, - onSettled: () => { - queryClient.invalidateQueries({ queryKey: ['docFeedback'] }) - }, - }) - - const updateMutation = useMutation({ - mutationFn: updateDocFeedback, - onMutate: async (variables) => { - // Cancel any outgoing refetches - await queryClient.cancelQueries({ queryKey: ['docFeedback'] }) - - // Snapshot the previous value - const previousData = queryClient.getQueriesData({ - queryKey: ['docFeedback'], - }) - - // Optimistically update the note content - queryClient.setQueriesData( - { queryKey: ['docFeedback'] }, - (old: DocFeedbackCacheData) => { - if (!old || typeof old !== 'object') return old - - // Handle doc page structure (userFeedback) - if ('userFeedback' in old && Array.isArray(old.userFeedback)) { - return { - ...old, - userFeedback: old.userFeedback.map((f: DocFeedback) => - f.id === note.id - ? { - ...f, - content: variables.data.content, - updatedAt: new Date(), - } - : f, - ), - } - } - - // Handle account/notes page structure (feedback) - if ('feedback' in old && Array.isArray(old.feedback)) { - return { - ...old, - feedback: old.feedback.map((f: DocFeedback) => - f.id === note.id - ? { - ...f, - content: variables.data.content, - updatedAt: new Date(), - } - : f, - ), - } - } - - return old - }, - ) - - return { previousData } - }, - onSuccess: () => { - setIsSaving(false) - setSaveError(null) - }, - onError: (error: Error, variables, context) => { - // Rollback on error - if (context?.previousData) { - context.previousData.forEach(([queryKey, data]) => { - queryClient.setQueryData(queryKey, data) - }) - } - setSaveError(error.message) - setIsSaving(false) - }, - onSettled: () => { - queryClient.invalidateQueries({ queryKey: ['docFeedback'] }) - }, - }) - - const collapsedMutation = useMutation({ - mutationFn: updateDocFeedbackCollapsed, - onMutate: async (variables) => { - // Cancel any outgoing refetches - await queryClient.cancelQueries({ queryKey: ['docFeedback'] }) - - // Snapshot the previous value - const previousData = queryClient.getQueriesData({ - queryKey: ['docFeedback'], - }) - - // Optimistically toggle collapsed state - queryClient.setQueriesData( - { queryKey: ['docFeedback'] }, - (old: DocFeedbackCacheData) => { - if (!old || typeof old !== 'object') return old - - // Handle doc page structure (userFeedback) - if ('userFeedback' in old && Array.isArray(old.userFeedback)) { - return { - ...old, - userFeedback: old.userFeedback.map((f: DocFeedback) => - f.id === note.id - ? { ...f, isCollapsed: variables.data.isCollapsed } - : f, - ), - } - } - - // Handle account/notes page structure (feedback) - if ('feedback' in old && Array.isArray(old.feedback)) { - return { - ...old, - feedback: old.feedback.map((f: DocFeedback) => - f.id === note.id - ? { ...f, isCollapsed: variables.data.isCollapsed } - : f, - ), - } - } + const deleteMutation = useMutation( + docFeedbackMutations.delete({ + noteId: note.id, + onError: (error) => { + setDeleteError(error.message) + setIsDeleting(false) + }, + }), + ) - return old - }, - ) + const updateMutation = useMutation( + docFeedbackMutations.update({ + noteId: note.id, + onSuccess: () => { + setIsSaving(false) + setSaveError(null) + }, + onError: (error) => { + setSaveError(error.message) + setIsSaving(false) + }, + }), + ) - return { previousData } - }, - onError: (error, variables, context) => { - // Rollback on error - if (context?.previousData) { - context.previousData.forEach(([queryKey, data]) => { - queryClient.setQueryData(queryKey, data) - }) - } - }, - onSettled: () => { - queryClient.invalidateQueries({ queryKey: ['docFeedback'] }) - }, - }) + const collapsedMutation = useMutation( + docFeedbackMutations.updateCollapsed({ noteId: note.id }), + ) const handleToggle = () => { collapsedMutation.mutate({ diff --git a/src/components/DocFeedbackProvider.tsx b/src/components/DocFeedbackProvider.tsx index 26125bcba..88729d8b3 100644 --- a/src/components/DocFeedbackProvider.tsx +++ b/src/components/DocFeedbackProvider.tsx @@ -1,11 +1,10 @@ import * as React from 'react' import * as ReactDOM from 'react-dom' -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' +import { useQuery, useMutation } from '@tanstack/react-query' import { twMerge } from 'tailwind-merge' import { DocFeedbackNote } from './DocFeedbackNote' import { DocFeedbackFloatingButton } from './DocFeedbackFloatingButton' -import { getDocFeedbackForPageQueryOptions } from '~/queries/docFeedback' -import { createDocFeedback } from '~/utils/docFeedback.functions' +import { docFeedbackMutations, docFeedbackQueries } from '~/queries/docFeedback' import { useCurrentUser } from '~/hooks/useCurrentUser' import { useLoginModal } from '~/contexts/LoginModalContext' import { @@ -58,7 +57,7 @@ export function DocFeedbackProvider({ // Fetch feedback for this page const { data: feedbackData } = useQuery( - getDocFeedbackForPageQueryOptions({ + docFeedbackQueries.page({ pagePath, libraryVersion, }), @@ -566,7 +565,6 @@ function CreatingFeedbackNote({ libraryVersion: string onClose: () => void }) { - const queryClient = useQueryClient() const [content, setContent] = React.useState('') const [isSaving, setIsSaving] = React.useState(false) const [error, setError] = React.useState(null) @@ -601,72 +599,17 @@ function CreatingFeedbackNote({ text: 'text-blue-800 dark:text-blue-300', } - const createMutation = useMutation({ - mutationFn: createDocFeedback, - onMutate: async (variables) => { - // Cancel any outgoing refetches - await queryClient.cancelQueries({ queryKey: ['docFeedback'] }) - - // Snapshot the previous value - const previousData = queryClient.getQueriesData({ - queryKey: ['docFeedback'], - }) - - // Create a temporary optimistic note - const tempNote: DocFeedback = { - id: `temp-${Date.now()}`, - userId: '', // Will be filled by server - type: variables.data.type, - content: variables.data.content, - characterCount: variables.data.content.length, - pagePath: variables.data.pagePath, - libraryId: variables.data.libraryId, - libraryVersion: variables.data.libraryVersion, - blockSelector: variables.data.blockSelector, - blockContentHash: variables.data.blockContentHash || null, - blockMarkdown: variables.data.blockMarkdown || null, - status: 'pending', - isDetached: false, - isCollapsed: false, - moderatedBy: null, - moderatedAt: null, - moderationNote: null, - createdAt: new Date(), - updatedAt: new Date(), - } - - // Optimistically add the note to all matching queries - queryClient.setQueriesData<{ - userFeedback: DocFeedback[] - detachedFeedback: any[] - isModerator: boolean - }>({ queryKey: ['docFeedback'] }, (old) => { - if (!old) return old - return { - ...old, - userFeedback: [tempNote, ...old.userFeedback], - } - }) - - return { previousData } - }, - onSuccess: () => { - onClose() - }, - onError: (error: Error, variables, context) => { - // Rollback on error - if (context?.previousData) { - context.previousData.forEach(([queryKey, data]) => { - queryClient.setQueryData(queryKey, data) - }) - } - setError(error.message) - setIsSaving(false) - }, - onSettled: () => { - queryClient.invalidateQueries({ queryKey: ['docFeedback'] }) - }, - }) + const createMutation = useMutation( + docFeedbackMutations.create({ + onSuccess: () => { + onClose() + }, + onError: (error) => { + setError(error.message) + setIsSaving(false) + }, + }), + ) const handleSave = () => { // Validate based on type diff --git a/src/components/FeedbackLeaderboard.tsx b/src/components/FeedbackLeaderboard.tsx index c079809cb..7620c41d9 100644 --- a/src/components/FeedbackLeaderboard.tsx +++ b/src/components/FeedbackLeaderboard.tsx @@ -1,7 +1,7 @@ import * as React from 'react' import { useQuery } from '@tanstack/react-query' import { useNavigate, useSearch } from '@tanstack/react-router' -import { getDocFeedbackLeaderboardQueryOptions } from '~/queries/docFeedback' +import { docFeedbackQueries } from '~/queries/docFeedback' import { Spinner } from './Spinner' import { Table, @@ -22,7 +22,7 @@ export function FeedbackLeaderboard() { const { page, pageSize } = search const { data, isLoading, error } = useQuery( - getDocFeedbackLeaderboardQueryOptions({ + docFeedbackQueries.leaderboard({ pagination: { page, pageSize }, }), ) diff --git a/src/components/FeedbackModerationPage.tsx b/src/components/FeedbackModerationPage.tsx index d22514821..208851470 100644 --- a/src/components/FeedbackModerationPage.tsx +++ b/src/components/FeedbackModerationPage.tsx @@ -1,8 +1,7 @@ import * as React from 'react' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { useNavigate, useSearch } from '@tanstack/react-router' -import { listDocFeedbackForModerationQueryOptions } from '~/queries/docFeedback' -import { moderateDocFeedback } from '~/utils/docFeedback.functions' +import { docFeedbackMutations, docFeedbackQueries } from '~/queries/docFeedback' import { FeedbackModerationTopBar } from './FeedbackModerationTopBar' import { FeedbackModerationList } from './FeedbackModerationList' import { useToast } from '~/components/ToastProvider' @@ -15,7 +14,7 @@ export function FeedbackModerationPage() { const { notify } = useToast() const { data, isLoading, error } = useQuery( - listDocFeedbackForModerationQueryOptions({ + docFeedbackQueries.moderation({ pagination: { page: search.page, pageSize: search.pageSize, @@ -32,7 +31,7 @@ export function FeedbackModerationPage() { ) const moderateMutation = useMutation({ - mutationFn: moderateDocFeedback, + ...docFeedbackMutations.moderate(), onSuccess: (_, variables) => { notify(
@@ -44,7 +43,9 @@ export function FeedbackModerationPage() {
, ) - queryClient.invalidateQueries({ queryKey: ['docFeedback', 'moderation'] }) + queryClient.invalidateQueries({ + queryKey: docFeedbackQueries.moderations(), + }) }, onError: (error: Error) => { notify( diff --git a/src/components/NotesModerationPage.tsx b/src/components/NotesModerationPage.tsx index 0182cad93..ce35fc72c 100644 --- a/src/components/NotesModerationPage.tsx +++ b/src/components/NotesModerationPage.tsx @@ -1,7 +1,7 @@ import * as React from 'react' import { useQuery } from '@tanstack/react-query' import { useNavigate, useSearch } from '@tanstack/react-router' -import { listDocFeedbackForModerationQueryOptions } from '~/queries/docFeedback' +import { docFeedbackQueries } from '~/queries/docFeedback' import { NotesModerationTopBar } from './NotesModerationTopBar' import { NotesModerationList } from './NotesModerationList' import { Spinner } from '~/components/Spinner' @@ -11,7 +11,7 @@ export function NotesModerationPage() { const search = useSearch({ from: '/admin/notes/' }) const { data, isLoading, error } = useQuery( - listDocFeedbackForModerationQueryOptions({ + docFeedbackQueries.moderation({ pagination: { page: search.page, pageSize: search.pageSize, diff --git a/src/components/OpenSourceStats.tsx b/src/components/OpenSourceStats.tsx index ae0bed1c1..071cb9385 100644 --- a/src/components/OpenSourceStats.tsx +++ b/src/components/OpenSourceStats.tsx @@ -5,11 +5,7 @@ import { StarIcon, } from '@phosphor-icons/react' import { type Library } from '~/libraries' -import { - homepageNpmStatsSummaryQuery, - ossStatsQuery, - recentDownloadsQuery, -} from '~/queries/stats' +import { statsQueries } from '~/queries/stats' import { HomeStatNumber } from '~/components/home/HomeStatNumber' import { LiveDownloadCount } from '~/components/home/LiveDownloadCount' import { useNpmDownloadCounter } from '~/hooks/useNpmDownloadCounter' @@ -60,18 +56,20 @@ export default function OssStats({ page?: StatsPage initialStats?: HomepageStatsSnapshot }) { - const { data: stats, isLoading } = useQuery(ossStatsQuery({ library })) + const { data: stats, isLoading } = useQuery( + statsQueries.ossSummary({ library }), + ) const { data: homepageNpmSummary, dataUpdatedAt, isLoading: isLoadingHomepageNpmSummary, } = useQuery({ - ...homepageNpmStatsSummaryQuery(), + ...statsQueries.homepageNpmSummary(), enabled: !library, }) const { data: recentDownloads, isLoading: isLoadingRecentDownloads } = useQuery({ - ...recentDownloadsQuery({ + ...statsQueries.recentDownloads({ library: library ?? tanStackTotalNpmStatsLibrary, }), enabled: Boolean(library), diff --git a/src/components/ShowcaseDetail.tsx b/src/components/ShowcaseDetail.tsx index a369d4d14..db31d0bee 100644 --- a/src/components/ShowcaseDetail.tsx +++ b/src/components/ShowcaseDetail.tsx @@ -1,7 +1,7 @@ import { showcaseLinkRel, isPublicShowcase } from '~/utils/showcase.shared' import * as React from 'react' import { Link } from '@tanstack/react-router' -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useMutation, useQuery } from '@tanstack/react-query' import { ArrowLeftIcon, ArrowSquareOutIcon, @@ -14,12 +14,7 @@ import { Button } from '~/ui' import { twMerge } from 'tailwind-merge' import { libraries, type LibraryId } from '~/libraries' import { USE_CASE_LABELS } from '~/utils/showcase.shared' -import { voteShowcase } from '~/utils/showcase.functions' -import { - getShowcaseQueryOptions, - getRelatedShowcasesQueryOptions, - getMyShowcaseVotesQueryOptions, -} from '~/queries/showcases' +import { showcasesMutations, showcasesQueries } from '~/queries/showcases' import { useCurrentUser } from '~/hooks/useCurrentUser' import { useLoginModal } from '~/contexts/LoginModalContext' import { ShowcaseCard } from './ShowcaseCard' @@ -32,14 +27,13 @@ interface ShowcaseDetailProps { } export function ShowcaseDetail({ showcaseId }: ShowcaseDetailProps) { - const queryClient = useQueryClient() const currentUser = useCurrentUser() const { openLoginModal } = useLoginModal() - const { data, isLoading } = useQuery(getShowcaseQueryOptions(showcaseId)) + const { data, isLoading } = useQuery(showcasesQueries.detail(showcaseId)) const { data: relatedData } = useQuery({ - ...getRelatedShowcasesQueryOptions({ + ...showcasesQueries.related({ showcaseId, libraries: data?.showcase.libraries ?? [], limit: 4, @@ -48,7 +42,7 @@ export function ShowcaseDetail({ showcaseId }: ShowcaseDetailProps) { }) const { data: votesData } = useQuery({ - ...getMyShowcaseVotesQueryOptions([showcaseId]), + ...showcasesQueries.myVotes([showcaseId]), enabled: !!currentUser, }) @@ -66,7 +60,7 @@ export function ShowcaseDetail({ showcaseId }: ShowcaseDetailProps) { ) const { data: relatedVotesData } = useQuery({ - ...getMyShowcaseVotesQueryOptions(relatedShowcaseIds), + ...showcasesQueries.myVotes(relatedShowcaseIds), enabled: !!currentUser && relatedShowcaseIds.length > 0, }) @@ -80,88 +74,9 @@ export function ShowcaseDetail({ showcaseId }: ShowcaseDetailProps) { return map }, [relatedVotesData]) - const voteMutation = useMutation({ - mutationFn: (params: { showcaseId: string; value: 1 | -1 }) => - voteShowcase({ data: params }), - onMutate: async ({ showcaseId: voteShowcaseId, value }) => { - await queryClient.cancelQueries({ queryKey: ['showcases'] }) - - const previousShowcase = queryClient.getQueryData( - getShowcaseQueryOptions(showcaseId).queryKey, - ) - const previousVotes = queryClient.getQueryData( - getMyShowcaseVotesQueryOptions([showcaseId]).queryKey, - ) - - // Optimistically update the vote - queryClient.setQueryData( - getMyShowcaseVotesQueryOptions([showcaseId]).queryKey, - (old: typeof votesData) => { - if (!old) return { votes: [{ showcaseId: voteShowcaseId, value }] } - const existingVote = old.votes.find( - (v) => v.showcaseId === voteShowcaseId, - ) - if (existingVote) { - if (existingVote.value === value) { - return { - votes: old.votes.filter((v) => v.showcaseId !== voteShowcaseId), - } - } - return { - votes: old.votes.map((v) => - v.showcaseId === voteShowcaseId ? { ...v, value } : v, - ), - } - } - return { - votes: [...old.votes, { showcaseId: voteShowcaseId, value }], - } - }, - ) - - // Optimistically update the showcase score - if (voteShowcaseId === showcaseId) { - queryClient.setQueryData( - getShowcaseQueryOptions(showcaseId).queryKey, - (old: typeof data) => { - if (!old) return old - let scoreDelta: number = value - if (currentUserVote === value) { - scoreDelta = -value - } else if (currentUserVote) { - scoreDelta = value * 2 - } - return { - ...old, - showcase: { - ...old.showcase, - voteScore: old.showcase.voteScore + scoreDelta, - }, - } - }, - ) - } - - return { previousShowcase, previousVotes } - }, - onError: (_err, _vars, context) => { - if (context?.previousShowcase) { - queryClient.setQueryData( - getShowcaseQueryOptions(showcaseId).queryKey, - context.previousShowcase, - ) - } - if (context?.previousVotes) { - queryClient.setQueryData( - getMyShowcaseVotesQueryOptions([showcaseId]).queryKey, - context.previousVotes, - ) - } - }, - onSettled: () => { - queryClient.invalidateQueries({ queryKey: ['showcases'] }) - }, - }) + const voteMutation = useMutation( + showcasesMutations.detailVote({ showcaseId, currentUserVote }), + ) const handleVote = (targetShowcaseId: string, value: 1 | -1) => { if (!currentUser) { diff --git a/src/components/ShowcaseGallery.tsx b/src/components/ShowcaseGallery.tsx index c6d588b29..bf885231c 100644 --- a/src/components/ShowcaseGallery.tsx +++ b/src/components/ShowcaseGallery.tsx @@ -1,11 +1,7 @@ import * as React from 'react' -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useMutation, useQuery } from '@tanstack/react-query' import { Link, useNavigate, useSearch } from '@tanstack/react-router' -import { - getApprovedShowcasesQueryOptions, - getMyShowcaseVotesQueryOptions, -} from '~/queries/showcases' -import { voteShowcase } from '~/utils/showcase.functions' +import { showcasesMutations, showcasesQueries } from '~/queries/showcases' import { ShowcaseCard, ShowcaseCardSkeleton } from './ShowcaseCard' import { CommunityProjectCard } from './CommunityProjectCard' import { SubmitShowcasePlaceholder } from './ShowcaseSection' @@ -31,27 +27,25 @@ export function ShowcaseGallery({ const placement = community ? 'community' : 'showcase' const navigate = useNavigate({ from }) const search = useSearch({ from }) - const queryClient = useQueryClient() const currentUser = useCurrentUser() const { openLoginModal } = useLoginModal() const pageSize = search.pageSize ?? 24 - const { data, isLoading } = useQuery( - getApprovedShowcasesQueryOptions({ - pagination: { - page: search.page, - pageSize, - }, - filters: { - placement, - libraryIds: search.libraryIds, - useCases: search.useCases, - hasSourceCode: search.hasSourceCode, - q: search.q, - }, - }), - ) + const approvedQuery = showcasesQueries.approved({ + pagination: { + page: search.page, + pageSize, + }, + filters: { + placement, + libraryIds: search.libraryIds, + useCases: search.useCases, + hasSourceCode: search.hasSourceCode, + q: search.q, + }, + }) + const { data, isLoading } = useQuery(approvedQuery) const showcaseIds = React.useMemo( () => data?.showcases.map((s) => s.showcase.id) ?? [], @@ -59,7 +53,7 @@ export function ShowcaseGallery({ ) const { data: votesData } = useQuery({ - ...getMyShowcaseVotesQueryOptions(showcaseIds), + ...showcasesQueries.myVotes(showcaseIds), enabled: !community && !!currentUser && showcaseIds.length > 0, }) @@ -73,129 +67,9 @@ export function ShowcaseGallery({ return map }, [votesData]) - const voteMutation = useMutation({ - mutationFn: (params: { showcaseId: string; value: 1 | -1 }) => - voteShowcase({ data: params }), - onMutate: async ({ showcaseId, value }) => { - // Cancel outgoing refetches - await queryClient.cancelQueries({ queryKey: ['showcases'] }) - - // Snapshot previous values - const previousShowcases = queryClient.getQueryData( - getApprovedShowcasesQueryOptions({ - pagination: { page: search.page, pageSize }, - filters: { - placement, - libraryIds: search.libraryIds, - useCases: search.useCases, - hasSourceCode: search.hasSourceCode, - q: search.q, - }, - }).queryKey, - ) - const previousVotes = queryClient.getQueryData( - getMyShowcaseVotesQueryOptions(showcaseIds).queryKey, - ) - - // Optimistically update votes - queryClient.setQueryData( - getMyShowcaseVotesQueryOptions(showcaseIds).queryKey, - (old: typeof votesData) => { - if (!old) return { votes: [{ showcaseId, value }] } - const existingVote = old.votes.find( - (v) => v.showcaseId === showcaseId, - ) - if (existingVote) { - if (existingVote.value === value) { - // Toggle off - return { - votes: old.votes.filter((v) => v.showcaseId !== showcaseId), - } - } else { - // Change vote - return { - votes: old.votes.map((v) => - v.showcaseId === showcaseId ? { ...v, value } : v, - ), - } - } - } else { - // New vote - return { votes: [...old.votes, { showcaseId, value }] } - } - }, - ) - - // Optimistically update showcase score - queryClient.setQueryData( - getApprovedShowcasesQueryOptions({ - pagination: { page: search.page, pageSize }, - filters: { - placement, - libraryIds: search.libraryIds, - useCases: search.useCases, - hasSourceCode: search.hasSourceCode, - q: search.q, - }, - }).queryKey, - (old: typeof data) => { - if (!old) return old - const currentVote = votesMap.get(showcaseId) - return { - ...old, - showcases: old.showcases.map((s) => { - if (s.showcase.id !== showcaseId) return s - let scoreDelta: number = value - if (currentVote === value) { - // Toggling off - scoreDelta = -value - } else if (currentVote) { - // Changing vote - scoreDelta = value * 2 - } - return { - ...s, - showcase: { - ...s.showcase, - voteScore: s.showcase.voteScore + scoreDelta, - }, - } - }), - } - }, - ) - - return { previousShowcases, previousVotes } - }, - onError: (_err, _vars, context) => { - // Rollback on error - if (context?.previousShowcases) { - queryClient.setQueryData( - getApprovedShowcasesQueryOptions({ - pagination: { page: search.page, pageSize }, - filters: { - placement, - libraryIds: search.libraryIds, - useCases: search.useCases, - hasSourceCode: search.hasSourceCode, - q: search.q, - }, - }).queryKey, - context.previousShowcases, - ) - } - if (context?.previousVotes) { - queryClient.setQueryData( - getMyShowcaseVotesQueryOptions(showcaseIds).queryKey, - context.previousVotes, - ) - } - }, - onSettled: () => { - // Refetch to sync with server - queryClient.invalidateQueries({ queryKey: ['showcases'] }) - }, - }) + const voteMutation = useMutation( + showcasesMutations.galleryVote({ approvedQuery, showcaseIds, votesMap }), + ) const handleVote = (showcaseId: string, value: 1 | -1) => { if (!currentUser) { diff --git a/src/components/ShowcaseModerationPage.tsx b/src/components/ShowcaseModerationPage.tsx index 68024b685..08e35e554 100644 --- a/src/components/ShowcaseModerationPage.tsx +++ b/src/components/ShowcaseModerationPage.tsx @@ -1,12 +1,7 @@ import * as React from 'react' import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' import { useNavigate, useSearch } from '@tanstack/react-router' -import { listShowcasesForModerationQueryOptions } from '~/queries/showcases' -import { - setShowcaseFeatured, - adminDeleteShowcase, - voteShowcase, -} from '~/utils/showcase.functions' +import { showcasesMutations, showcasesQueries } from '~/queries/showcases' import { ShowcaseModerationTopBar } from './ShowcaseModerationTopBar' import { ShowcaseModerationList } from './ShowcaseModerationList' import { useToast } from '~/components/ToastProvider' @@ -19,7 +14,7 @@ export function ShowcaseModerationPage() { const { notify } = useToast() const { data, isLoading, error } = useQuery( - listShowcasesForModerationQueryOptions({ + showcasesQueries.moderation({ pagination: { page: search.page, pageSize: search.pageSize, @@ -34,7 +29,7 @@ export function ShowcaseModerationPage() { ) const featuredMutation = useMutation({ - mutationFn: setShowcaseFeatured, + ...showcasesMutations.setFeatured(), onSuccess: (_, variables) => { notify(
@@ -45,7 +40,7 @@ export function ShowcaseModerationPage() {
, ) - queryClient.invalidateQueries({ queryKey: ['showcases'] }) + queryClient.invalidateQueries({ queryKey: showcasesQueries.all() }) }, onError: (error: Error) => { notify( @@ -60,14 +55,14 @@ export function ShowcaseModerationPage() { }) const deleteMutation = useMutation({ - mutationFn: adminDeleteShowcase, + ...showcasesMutations.adminDelete(), onSuccess: () => { notify(
Showcase deleted
, ) - queryClient.invalidateQueries({ queryKey: ['showcases'] }) + queryClient.invalidateQueries({ queryKey: showcasesQueries.all() }) }, onError: (error: Error) => { notify( @@ -82,9 +77,9 @@ export function ShowcaseModerationPage() { }) const voteMutation = useMutation({ - mutationFn: voteShowcase, + ...showcasesMutations.vote(), onSuccess: () => { - queryClient.invalidateQueries({ queryKey: ['showcases'] }) + queryClient.invalidateQueries({ queryKey: showcasesQueries.all() }) }, }) @@ -130,9 +125,7 @@ export function ShowcaseModerationPage() { } const handleVote = (showcaseId: string, value: 1 | -1) => { - voteMutation.mutate({ - data: { showcaseId, value }, - }) + voteMutation.mutate({ showcaseId, value }) } return ( diff --git a/src/components/ShowcaseSection.tsx b/src/components/ShowcaseSection.tsx index 6c7d6b9f4..084f9e268 100644 --- a/src/components/ShowcaseSection.tsx +++ b/src/components/ShowcaseSection.tsx @@ -1,12 +1,7 @@ import * as React from 'react' -import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' +import { useMutation, useQuery } from '@tanstack/react-query' import { Link } from '@tanstack/react-router' -import { - getFeaturedShowcasesQueryOptions, - getShowcasesByLibraryQueryOptions, - getMyShowcaseVotesQueryOptions, -} from '~/queries/showcases' -import { voteShowcase } from '~/utils/showcase.functions' +import { showcasesMutations, showcasesQueries } from '~/queries/showcases' import { ShowcaseCard, ShowcaseCardSkeleton } from './ShowcaseCard' import { Button } from '~/ui' import { ArrowRightIcon, PlusIcon } from '@phosphor-icons/react' @@ -64,13 +59,12 @@ export function ShowcaseSection({ showViewAll = true, minItems = 3, }: ShowcaseSectionProps) { - const queryClient = useQueryClient() const currentUser = useCurrentUser() const { openLoginModal } = useLoginModal() const queryOptions = libraryId - ? getShowcasesByLibraryQueryOptions({ libraryId, limit }) - : getFeaturedShowcasesQueryOptions({ limit }) + ? showcasesQueries.byLibrary({ libraryId, limit }) + : showcasesQueries.featured({ limit }) const { data, isLoading } = useQuery(queryOptions) @@ -86,7 +80,7 @@ export function ShowcaseSection({ ) const { data: votesData } = useQuery({ - ...getMyShowcaseVotesQueryOptions(showcaseIds), + ...showcasesQueries.myVotes(showcaseIds), enabled: !!currentUser && showcaseIds.length > 0, }) @@ -100,88 +94,9 @@ export function ShowcaseSection({ return map }, [votesData]) - const voteMutation = useMutation({ - mutationFn: (params: { showcaseId: string; value: 1 | -1 }) => - voteShowcase({ data: params }), - onMutate: async ({ showcaseId, value }) => { - await queryClient.cancelQueries({ queryKey: ['showcases'] }) - - const previousShowcases = queryClient.getQueryData(queryOptions.queryKey) - const previousVotes = queryClient.getQueryData( - getMyShowcaseVotesQueryOptions(showcaseIds).queryKey, - ) - - // Optimistically update votes - queryClient.setQueryData( - getMyShowcaseVotesQueryOptions(showcaseIds).queryKey, - (old: typeof votesData) => { - if (!old) return { votes: [{ showcaseId, value }] } - const existingVote = old.votes.find( - (v) => v.showcaseId === showcaseId, - ) - if (existingVote) { - if (existingVote.value === value) { - return { - votes: old.votes.filter((v) => v.showcaseId !== showcaseId), - } - } else { - return { - votes: old.votes.map((v) => - v.showcaseId === showcaseId ? { ...v, value } : v, - ), - } - } - } else { - return { votes: [...old.votes, { showcaseId, value }] } - } - }, - ) - - // Optimistically update showcase score - queryClient.setQueryData(queryOptions.queryKey, (old: typeof data) => { - if (!old) return old - const currentVote = votesMap.get(showcaseId) - return { - ...old, - showcases: old.showcases.map((s) => { - if (s.showcase.id !== showcaseId) return s - let scoreDelta: number = value - if (currentVote === value) { - scoreDelta = -value - } else if (currentVote) { - scoreDelta = value * 2 - } - return { - ...s, - showcase: { - ...s.showcase, - voteScore: s.showcase.voteScore + scoreDelta, - }, - } - }), - } - }) - - return { previousShowcases, previousVotes } - }, - onError: (_err, _vars, context) => { - if (context?.previousShowcases) { - queryClient.setQueryData( - queryOptions.queryKey, - context.previousShowcases, - ) - } - if (context?.previousVotes) { - queryClient.setQueryData( - getMyShowcaseVotesQueryOptions(showcaseIds).queryKey, - context.previousVotes, - ) - } - }, - onSettled: () => { - queryClient.invalidateQueries({ queryKey: ['showcases'] }) - }, - }) + const voteMutation = useMutation( + showcasesMutations.sectionVote({ queryOptions, showcaseIds, votesMap }), + ) const handleVote = (showcaseId: string, value: 1 | -1) => { if (!currentUser) { diff --git a/src/components/intent/SkillDiffViewer.tsx b/src/components/intent/SkillDiffViewer.tsx index e48c484cf..ca4de7c0e 100644 --- a/src/components/intent/SkillDiffViewer.tsx +++ b/src/components/intent/SkillDiffViewer.tsx @@ -1,7 +1,7 @@ import * as React from 'react' import { useQuery } from '@tanstack/react-query' import { diffLines } from 'diff' -import { intentSkillContentDiffQueryOptions } from '~/queries/intent' +import { intentQueries } from '~/queries/intent' export function SkillDiffViewer({ packageName, @@ -15,7 +15,7 @@ export function SkillDiffViewer({ readonly toVersion: string }) { const diffQuery = useQuery( - intentSkillContentDiffQueryOptions({ + intentQueries.skillContentDiff({ packageName, skillName, fromVersion, diff --git a/src/components/landing/LibraryLanding.tsx b/src/components/landing/LibraryLanding.tsx index 7b7916c94..0f77dd81f 100644 --- a/src/components/landing/LibraryLanding.tsx +++ b/src/components/landing/LibraryLanding.tsx @@ -15,7 +15,7 @@ import { getLibrary } from '~/libraries' import type { LibraryId } from '~/libraries' import { PartnersSponsorsSection } from '~/components/PartnersSponsorsSection' import { LibraryStatusBadge } from '~/components/LibraryStatusBadge' -import { ossStatsQuery, recentDownloadsQuery } from '~/queries/stats' +import { statsQueries } from '~/queries/stats' import { LandingCopyPromptButton } from './LandingCopyPromptButton' import { ChartsTextBackdrop } from './ChartsTextBackdrop' @@ -619,8 +619,10 @@ function LandingWorkbench({ function LandingStats({ libraryId }: { libraryId: LibraryLandingId }) { const library = getLibrary(libraryId) - const { data: stats } = useQuery(ossStatsQuery({ library })) - const { data: downloads } = useQuery(recentDownloadsQuery({ library })) + const { data: stats } = useQuery(statsQueries.ossSummary({ library })) + const { data: downloads } = useQuery( + statsQueries.recentDownloads({ library }), + ) const metrics = [ { href: 'https://www.npmjs.com/org/tanstack', diff --git a/src/components/npm-stats/NPMSummary.tsx b/src/components/npm-stats/NPMSummary.tsx index cbde3e3e5..f71d53fbf 100644 --- a/src/components/npm-stats/NPMSummary.tsx +++ b/src/components/npm-stats/NPMSummary.tsx @@ -2,7 +2,7 @@ import * as React from 'react' import { Suspense } from 'react' import { useSuspenseQuery } from '@tanstack/react-query' import { BlankErrorBoundary } from '~/components/BlankErrorBoundary' -import { ossStatsQuery, recentDownloadsQuery } from '~/queries/stats' +import { statsQueries } from '~/queries/stats' import { useNpmDownloadCounter } from '~/hooks/useNpmDownloadCounter' import type { Library } from '~/libraries' @@ -85,11 +85,13 @@ function StatCard({ */ function NPMSummaryContent({ library }: { library: Library }) { // Fetch all-time stats (includes ratePerDay for animation) - const { data: ossStats } = useSuspenseQuery(ossStatsQuery({ library })) + const { data: ossStats } = useSuspenseQuery( + statsQueries.ossSummary({ library }), + ) // Fetch recent download stats (daily, weekly, monthly) const { data: recentStats } = useSuspenseQuery( - recentDownloadsQuery({ library }), + statsQueries.recentDownloads({ library }), ) return ( diff --git a/src/queries/docFeedback.ts b/src/queries/docFeedback.ts index c36f9c714..961b8a633 100644 --- a/src/queries/docFeedback.ts +++ b/src/queries/docFeedback.ts @@ -1,11 +1,20 @@ -import { queryOptions } from '@tanstack/react-query' +import { mutationOptions, queryOptions } from '@tanstack/react-query' import { + createDocFeedback, + deleteDocFeedback, + getDocFeedbackForPage, + getDocFeedbackLeaderboard, getUserDocFeedback, listDocFeedbackForModeration, - getDocFeedbackLeaderboard, - getDocFeedbackForPage, + moderateDocFeedback, + updateDocFeedback, + updateDocFeedbackCollapsed, } from '~/utils/docFeedback.functions' -import type { DocFeedbackStatus, DocFeedbackType } from '~/db/types' +import type { + DocFeedback, + DocFeedbackStatus, + DocFeedbackType, +} from '~/db/types' export interface DocFeedbackFilters { status?: DocFeedbackStatus[] @@ -22,42 +31,328 @@ export interface DocFeedbackPagination { pageSize: number } -export const getUserDocFeedbackQueryOptions = (params: { - pagination: DocFeedbackPagination - filters?: { - status?: DocFeedbackStatus[] - libraryId?: string - type?: DocFeedbackType[] - } -}) => - queryOptions({ - queryKey: ['docFeedback', 'user', params], - queryFn: () => getUserDocFeedback({ data: params }), - }) - -export const listDocFeedbackForModerationQueryOptions = (params: { - pagination: DocFeedbackPagination - filters?: DocFeedbackFilters -}) => - queryOptions({ - queryKey: ['docFeedback', 'moderation', params], - queryFn: () => listDocFeedbackForModeration({ data: params }), - staleTime: 0, - }) - -export const getDocFeedbackLeaderboardQueryOptions = (params: { - pagination: DocFeedbackPagination -}) => - queryOptions({ - queryKey: ['docFeedback', 'leaderboard', params], - queryFn: () => getDocFeedbackLeaderboard({ data: params }), - }) - -export const getDocFeedbackForPageQueryOptions = (params: { - pagePath: string - libraryVersion: string -}) => - queryOptions({ - queryKey: ['docFeedback', 'page', params], - queryFn: () => getDocFeedbackForPage({ data: params }), - }) +export const docFeedbackQueries = { + all: () => ['docFeedback'], + user: (params: { + pagination: DocFeedbackPagination + filters?: { + status?: DocFeedbackStatus[] + libraryId?: string + type?: DocFeedbackType[] + } + }) => + queryOptions({ + queryKey: [...docFeedbackQueries.all(), 'user', params], + queryFn: () => getUserDocFeedback({ data: params }), + }), + moderations: () => [...docFeedbackQueries.all(), 'moderation'], + moderation: (params: { + pagination: DocFeedbackPagination + filters?: DocFeedbackFilters + }) => + queryOptions({ + queryKey: [...docFeedbackQueries.moderations(), params], + queryFn: () => listDocFeedbackForModeration({ data: params }), + staleTime: 0, + }), + leaderboard: (params: { pagination: DocFeedbackPagination }) => + queryOptions({ + queryKey: [...docFeedbackQueries.all(), 'leaderboard', params], + queryFn: () => getDocFeedbackLeaderboard({ data: params }), + }), + page: (params: { pagePath: string; libraryVersion: string }) => + queryOptions({ + queryKey: [...docFeedbackQueries.all(), 'page', params], + queryFn: () => getDocFeedbackForPage({ data: params }), + }), +} + +// Types for the query cache data structures +interface DocPageCacheData { + userFeedback: DocFeedback[] +} + +interface AccountPageCacheData { + feedback: DocFeedback[] +} + +type DocFeedbackCacheData = DocPageCacheData | AccountPageCacheData | unknown + +export const docFeedbackMutations = { + create: ({ + onSuccess, + onError, + }: { + onSuccess: () => void + onError: (error: Error) => void + }) => + mutationOptions({ + mutationFn: createDocFeedback, + + onMutate: async (variables, { client }) => { + // Cancel any outgoing refetches + await client.cancelQueries({ queryKey: docFeedbackQueries.all() }) + + // Snapshot the previous value + const previousData = client.getQueriesData({ + queryKey: docFeedbackQueries.all(), + }) + + // Create a temporary optimistic note + const tempNote: DocFeedback = { + id: `temp-${Date.now()}`, + userId: '', // Will be filled by server + type: variables.data.type, + content: variables.data.content, + characterCount: variables.data.content.length, + pagePath: variables.data.pagePath, + libraryId: variables.data.libraryId, + libraryVersion: variables.data.libraryVersion, + blockSelector: variables.data.blockSelector, + blockContentHash: variables.data.blockContentHash || null, + blockMarkdown: variables.data.blockMarkdown || null, + status: 'pending', + isDetached: false, + isCollapsed: false, + moderatedBy: null, + moderatedAt: null, + moderationNote: null, + createdAt: new Date(), + updatedAt: new Date(), + } + + // Optimistically add the note to all matching queries + client.setQueriesData<{ + userFeedback: DocFeedback[] + detachedFeedback: any[] + isModerator: boolean + }>({ queryKey: docFeedbackQueries.all() }, (old) => { + if (!old) return old + return { + ...old, + userFeedback: [tempNote, ...old.userFeedback], + } + }) + + return { previousData } + }, + onSuccess, + onError: (error: Error, variables, context, { client }) => { + // Rollback on error + if (context?.previousData) { + context.previousData.forEach(([queryKey, data]) => { + client.setQueryData(queryKey, data) + }) + } + onError(error) + }, + onSettled: (_data, _error, _variables, _context, { client }) => { + client.invalidateQueries({ queryKey: docFeedbackQueries.all() }) + }, + }), + update: ({ + noteId, + onSuccess, + onError, + }: { + noteId: string + onSuccess: () => void + onError: (error: Error) => void + }) => + mutationOptions({ + mutationFn: updateDocFeedback, + + onMutate: async (variables, { client }) => { + // Cancel any outgoing refetches + await client.cancelQueries({ queryKey: docFeedbackQueries.all() }) + + // Snapshot the previous value + const previousData = client.getQueriesData({ + queryKey: docFeedbackQueries.all(), + }) + + // Optimistically update the note content + client.setQueriesData( + { queryKey: docFeedbackQueries.all() }, + (old: DocFeedbackCacheData) => { + if (!old || typeof old !== 'object') return old + + // Handle doc page structure (userFeedback) + if ('userFeedback' in old && Array.isArray(old.userFeedback)) { + return { + ...old, + userFeedback: old.userFeedback.map((f: DocFeedback) => + f.id === noteId + ? { + ...f, + content: variables.data.content, + updatedAt: new Date(), + } + : f, + ), + } + } + + // Handle account/notes page structure (feedback) + if ('feedback' in old && Array.isArray(old.feedback)) { + return { + ...old, + feedback: old.feedback.map((f: DocFeedback) => + f.id === noteId + ? { + ...f, + content: variables.data.content, + updatedAt: new Date(), + } + : f, + ), + } + } + + return old + }, + ) + + return { previousData } + }, + onSuccess, + onError: (error: Error, variables, context, { client }) => { + // Rollback on error + if (context?.previousData) { + context.previousData.forEach(([queryKey, data]) => { + client.setQueryData(queryKey, data) + }) + } + onError(error) + }, + onSettled: (_data, _error, _variables, _context, { client }) => { + client.invalidateQueries({ queryKey: docFeedbackQueries.all() }) + }, + }), + delete: ({ + noteId, + onError, + }: { + noteId: string + onError: (error: Error) => void + }) => + mutationOptions({ + mutationFn: deleteDocFeedback, + + onMutate: async (_variables, { client }) => { + // Cancel any outgoing refetches + await client.cancelQueries({ queryKey: docFeedbackQueries.all() }) + + // Snapshot the previous value + const previousData = client.getQueriesData({ + queryKey: docFeedbackQueries.all(), + }) + + // Optimistically remove the note from all matching queries + client.setQueriesData( + { queryKey: docFeedbackQueries.all() }, + (old: DocFeedbackCacheData) => { + if (!old || typeof old !== 'object') return old + + // Handle doc page structure (userFeedback) + if ('userFeedback' in old && Array.isArray(old.userFeedback)) { + return { + ...old, + userFeedback: old.userFeedback.filter( + (f: DocFeedback) => f.id !== noteId, + ), + } + } + + // Handle account/notes page structure (feedback) + if ('feedback' in old && Array.isArray(old.feedback)) { + return { + ...old, + feedback: old.feedback.filter( + (f: DocFeedback) => f.id !== noteId, + ), + } + } + + return old + }, + ) + + return { previousData } + }, + onError: (error: Error, variables, context, { client }) => { + // Rollback on error + if (context?.previousData) { + context.previousData.forEach(([queryKey, data]) => { + client.setQueryData(queryKey, data) + }) + } + onError(error) + }, + onSettled: (_data, _error, _variables, _context, { client }) => { + client.invalidateQueries({ queryKey: docFeedbackQueries.all() }) + }, + }), + updateCollapsed: ({ noteId }: { noteId: string }) => + mutationOptions({ + mutationFn: updateDocFeedbackCollapsed, + + onMutate: async (variables, { client }) => { + // Cancel any outgoing refetches + await client.cancelQueries({ queryKey: docFeedbackQueries.all() }) + + // Snapshot the previous value + const previousData = client.getQueriesData({ + queryKey: docFeedbackQueries.all(), + }) + + // Optimistically toggle collapsed state + client.setQueriesData( + { queryKey: docFeedbackQueries.all() }, + (old: DocFeedbackCacheData) => { + if (!old || typeof old !== 'object') return old + + // Handle doc page structure (userFeedback) + if ('userFeedback' in old && Array.isArray(old.userFeedback)) { + return { + ...old, + userFeedback: old.userFeedback.map((f: DocFeedback) => + f.id === noteId + ? { ...f, isCollapsed: variables.data.isCollapsed } + : f, + ), + } + } + + // Handle account/notes page structure (feedback) + if ('feedback' in old && Array.isArray(old.feedback)) { + return { + ...old, + feedback: old.feedback.map((f: DocFeedback) => + f.id === noteId + ? { ...f, isCollapsed: variables.data.isCollapsed } + : f, + ), + } + } + + return old + }, + ) + + return { previousData } + }, + onError: (error, variables, context, { client }) => { + // Rollback on error + if (context?.previousData) { + context.previousData.forEach(([queryKey, data]) => { + client.setQueryData(queryKey, data) + }) + } + }, + onSettled: (_data, _error, _variables, _context, { client }) => { + client.invalidateQueries({ queryKey: docFeedbackQueries.all() }) + }, + }), + moderate: () => mutationOptions({ mutationFn: moderateDocFeedback }), +} diff --git a/src/queries/docsConfig.ts b/src/queries/docsConfig.ts index 3d75cf630..19c31c9f0 100644 --- a/src/queries/docsConfig.ts +++ b/src/queries/docsConfig.ts @@ -14,12 +14,14 @@ function getDocsConfigRequest(libraryId: LibraryId, version: string) { } } -export function docsConfigQueryOptions(libraryId: LibraryId, version: string) { - const request = getDocsConfigRequest(libraryId, version) +export const docsConfigQueries = { + detail: (libraryId: LibraryId, version: string) => { + const request = getDocsConfigRequest(libraryId, version) - return queryOptions({ - queryKey: ['docs-config', request.repo, request.branch, request.docsRoot], - queryFn: () => getTanstackDocsConfig({ data: request }), - staleTime: 1000 * 60 * 5, - }) + return queryOptions({ + queryKey: ['docs-config', request.repo, request.branch, request.docsRoot], + queryFn: () => getTanstackDocsConfig({ data: request }), + staleTime: 1000 * 60 * 5, + }) + }, } diff --git a/src/queries/docsManifest.ts b/src/queries/docsManifest.ts index 7d307e5db..16f2d3eba 100644 --- a/src/queries/docsManifest.ts +++ b/src/queries/docsManifest.ts @@ -1,16 +1,15 @@ import { queryOptions } from '@tanstack/react-query' import { fetchDocsPathManifest } from '~/utils/docs.functions' -export function docsPathManifestQueryOptions(request: { - repo: string - branch: string - docsRoot: string -}) { - const { repo, branch, docsRoot } = request +export const docsManifestQueries = { + paths: (request: { repo: string; branch: string; docsRoot: string }) => { + const { repo, branch, docsRoot } = request - return queryOptions({ - queryKey: ['docs-path-manifest', repo, branch, docsRoot], - queryFn: () => fetchDocsPathManifest({ data: { repo, branch, docsRoot } }), - staleTime: 1000 * 60 * 5, - }) + return queryOptions({ + queryKey: ['docs-path-manifest', repo, branch, docsRoot], + queryFn: () => + fetchDocsPathManifest({ data: { repo, branch, docsRoot } }), + staleTime: 1000 * 60 * 5, + }) + }, } diff --git a/src/queries/intent.ts b/src/queries/intent.ts index 026e51a2c..24dfb6917 100644 --- a/src/queries/intent.ts +++ b/src/queries/intent.ts @@ -12,95 +12,88 @@ import { getIntentSkillContentDiff, } from '~/utils/intent.functions' -export const intentStatsQueryOptions = () => - queryOptions({ - queryKey: ['intent', 'stats'], - queryFn: () => getIntentStats(), - staleTime: 5 * 60 * 1000, - }) - -export const intentDirectoryQueryOptions = (params: { - search?: string - framework?: string - sort?: 'downloads' | 'name' | 'skills' | 'newest' - page?: number - pageSize?: number -}) => - queryOptions({ - queryKey: ['intent', 'directory', params], - queryFn: () => getIntentDirectory({ data: params }), - staleTime: 5 * 60 * 1000, - }) - -export const intentPackageDetailQueryOptions = (name: string) => - queryOptions({ - queryKey: ['intent', 'package', name], - queryFn: () => getIntentPackageDetail({ data: { name } }), - staleTime: 10 * 60 * 1000, - }) - -export const intentVersionSkillsQueryOptions = (params: { - packageName: string - version: string -}) => - queryOptions({ - queryKey: ['intent', 'skills', params.packageName, params.version], - queryFn: () => getIntentVersionSkills({ data: params }), - staleTime: 30 * 60 * 1000, - }) - -export const intentSkillSearchQueryOptions = (query: string) => - queryOptions({ - queryKey: ['intent', 'skill-search', query], - queryFn: () => searchIntentSkills({ data: { query } }), - staleTime: 2 * 60 * 1000, - enabled: query.trim().length > 0, - }) - -export const intentVersionDiffQueryOptions = (params: { - packageName: string - fromVersion: string - toVersion: string -}) => - queryOptions({ - queryKey: ['intent', 'diff', params], - queryFn: () => diffIntentVersions({ data: params }), - staleTime: 30 * 60 * 1000, - }) - -export const intentSkillHistoryQueryOptions = (packageNames: Array) => - queryOptions({ - queryKey: ['intent', 'skill-history', packageNames], - queryFn: () => getIntentSkillHistory({ data: { packageNames } }), - staleTime: 10 * 60 * 1000, - enabled: packageNames.length > 0, - }) - -export const intentPackageChangelogQueryOptions = (packageName: string) => - queryOptions({ - queryKey: ['intent', 'changelog', packageName], - queryFn: () => getIntentPackageChangelog({ data: { packageName } }), - staleTime: 10 * 60 * 1000, - }) - -export const intentSingleSkillHistoryQueryOptions = (params: { - packageName: string - skillName: string -}) => - queryOptions({ - queryKey: ['intent', 'single-skill-history', params], - queryFn: () => getIntentSingleSkillHistory({ data: params }), - staleTime: 10 * 60 * 1000, - }) - -export const intentSkillContentDiffQueryOptions = (params: { - packageName: string - skillName: string - fromVersion: string - toVersion: string -}) => - queryOptions({ - queryKey: ['intent', 'skill-content-diff', params], - queryFn: () => getIntentSkillContentDiff({ data: params }), - staleTime: 30 * 60 * 1000, - }) +export const intentQueries = { + all: () => ['intent'], + stats: () => + queryOptions({ + queryKey: [...intentQueries.all(), 'stats'], + queryFn: () => getIntentStats(), + staleTime: 5 * 60 * 1000, + }), + directory: (params: { + search?: string + framework?: string + sort?: 'downloads' | 'name' | 'skills' | 'newest' + page?: number + pageSize?: number + }) => + queryOptions({ + queryKey: [...intentQueries.all(), 'directory', params], + queryFn: () => getIntentDirectory({ data: params }), + staleTime: 5 * 60 * 1000, + }), + packageDetail: (name: string) => + queryOptions({ + queryKey: [...intentQueries.all(), 'package', name], + queryFn: () => getIntentPackageDetail({ data: { name } }), + staleTime: 10 * 60 * 1000, + }), + versionSkills: (params: { packageName: string; version: string }) => + queryOptions({ + queryKey: [ + ...intentQueries.all(), + 'skills', + params.packageName, + params.version, + ], + queryFn: () => getIntentVersionSkills({ data: params }), + staleTime: 30 * 60 * 1000, + }), + skillSearch: (query: string) => + queryOptions({ + queryKey: [...intentQueries.all(), 'skill-search', query], + queryFn: () => searchIntentSkills({ data: { query } }), + staleTime: 2 * 60 * 1000, + enabled: query.trim().length > 0, + }), + versionDiff: (params: { + packageName: string + fromVersion: string + toVersion: string + }) => + queryOptions({ + queryKey: [...intentQueries.all(), 'diff', params], + queryFn: () => diffIntentVersions({ data: params }), + staleTime: 30 * 60 * 1000, + }), + skillHistory: (packageNames: Array) => + queryOptions({ + queryKey: [...intentQueries.all(), 'skill-history', packageNames], + queryFn: () => getIntentSkillHistory({ data: { packageNames } }), + staleTime: 10 * 60 * 1000, + enabled: packageNames.length > 0, + }), + packageChangelog: (packageName: string) => + queryOptions({ + queryKey: [...intentQueries.all(), 'changelog', packageName], + queryFn: () => getIntentPackageChangelog({ data: { packageName } }), + staleTime: 10 * 60 * 1000, + }), + singleSkillHistory: (params: { packageName: string; skillName: string }) => + queryOptions({ + queryKey: [...intentQueries.all(), 'single-skill-history', params], + queryFn: () => getIntentSingleSkillHistory({ data: params }), + staleTime: 10 * 60 * 1000, + }), + skillContentDiff: (params: { + packageName: string + skillName: string + fromVersion: string + toVersion: string + }) => + queryOptions({ + queryKey: [...intentQueries.all(), 'skill-content-diff', params], + queryFn: () => getIntentSkillContentDiff({ data: params }), + staleTime: 30 * 60 * 1000, + }), +} diff --git a/src/queries/roles.ts b/src/queries/roles.ts index 266da7c06..f5eeec0d4 100644 --- a/src/queries/roles.ts +++ b/src/queries/roles.ts @@ -11,22 +11,22 @@ export interface ListRolesFilters { capabilityFilter?: Capability[] } -export const listRolesQueryOptions = (filters?: ListRolesFilters) => - queryOptions({ - queryKey: ['admin', 'roles', filters], - queryFn: () => listRoles({ data: filters || {} }), - }) - -export const getBulkUserRolesQueryOptions = (userIds: string[]) => - queryOptions({ - queryKey: ['admin', 'bulkUserRoles', userIds], - queryFn: () => getBulkUserRoles({ data: { userIds } }), - enabled: userIds.length > 0, - }) - -export const getBulkEffectiveCapabilitiesQueryOptions = (userIds: string[]) => - queryOptions({ - queryKey: ['admin', 'bulkEffectiveCapabilities', userIds], - queryFn: () => getBulkEffectiveCapabilities({ data: { userIds } }), - enabled: userIds.length > 0, - }) +export const rolesQueries = { + list: (filters?: ListRolesFilters) => + queryOptions({ + queryKey: ['admin', 'roles', filters], + queryFn: () => listRoles({ data: filters || {} }), + }), + bulkUserRoles: (userIds: string[]) => + queryOptions({ + queryKey: ['admin', 'bulkUserRoles', userIds], + queryFn: () => getBulkUserRoles({ data: { userIds } }), + enabled: userIds.length > 0, + }), + bulkEffectiveCapabilities: (userIds: string[]) => + queryOptions({ + queryKey: ['admin', 'bulkEffectiveCapabilities', userIds], + queryFn: () => getBulkEffectiveCapabilities({ data: { userIds } }), + enabled: userIds.length > 0, + }), +} diff --git a/src/queries/showcases.ts b/src/queries/showcases.ts index 2542984ca..c6be61c85 100644 --- a/src/queries/showcases.ts +++ b/src/queries/showcases.ts @@ -1,13 +1,17 @@ -import { queryOptions } from '@tanstack/react-query' +import { mutationOptions, queryOptions } from '@tanstack/react-query' import { - getMyShowcases, + adminDeleteShowcase, + deleteShowcase, getApprovedShowcases, - getShowcasesByLibrary, getFeaturedShowcases, - listShowcasesForModeration, - getShowcase, + getMyShowcases, getMyShowcaseVotes, getRelatedShowcases, + getShowcase, + getShowcasesByLibrary, + listShowcasesForModeration, + setShowcaseFeatured, + voteShowcase, } from '~/utils/showcase.functions' import type { ShowcaseStatus, ShowcaseUseCase } from '~/db/types' @@ -26,85 +30,386 @@ export interface ShowcaseFilters { featured?: boolean } -export const getMyShowcasesQueryOptions = (params: { - pagination: ShowcasePagination -}) => - queryOptions({ - queryKey: ['showcases', 'mine', params], - queryFn: () => getMyShowcases({ data: params }), - }) - -export const getApprovedShowcasesQueryOptions = (params: { - pagination: ShowcasePagination - filters?: { - placement?: 'showcase' | 'community' - libraryIds?: string[] - useCases?: ShowcaseUseCase[] - featured?: boolean - hasSourceCode?: boolean - q?: string - } -}) => - queryOptions({ - queryKey: ['showcases', 'approved', params], - queryFn: () => getApprovedShowcases({ data: params }), - }) - -export const getShowcasesByLibraryQueryOptions = (params: { - libraryId: string - limit?: number -}) => - queryOptions({ - queryKey: ['showcases', 'library', params.libraryId, params.limit], - queryFn: () => - getShowcasesByLibrary({ - data: { libraryId: params.libraryId, limit: params.limit ?? 6 }, - }), - }) - -export const getFeaturedShowcasesQueryOptions = (params: { limit?: number }) => - queryOptions({ - queryKey: ['showcases', 'featured', params.limit], - queryFn: () => getFeaturedShowcases({ data: { limit: params.limit ?? 6 } }), - }) - -export const listShowcasesForModerationQueryOptions = (params: { - pagination: ShowcasePagination - filters?: ShowcaseFilters -}) => - queryOptions({ - queryKey: ['showcases', 'moderation', params], - queryFn: () => listShowcasesForModeration({ data: params }), - staleTime: 0, - }) - -export const getShowcaseQueryOptions = (showcaseId: string) => - queryOptions({ - queryKey: ['showcases', 'detail', showcaseId], - queryFn: () => getShowcase({ data: { showcaseId } }), - }) - -export const getMyShowcaseVotesQueryOptions = (showcaseIds: string[]) => - queryOptions({ - queryKey: ['showcases', 'votes', 'mine', showcaseIds], - queryFn: () => getMyShowcaseVotes({ data: { showcaseIds } }), - enabled: showcaseIds.length > 0, - }) - -export const getRelatedShowcasesQueryOptions = (params: { - showcaseId: string - libraries: string[] - limit?: number -}) => - queryOptions({ - queryKey: ['showcases', 'related', params.showcaseId], - queryFn: () => - getRelatedShowcases({ - data: { - showcaseId: params.showcaseId, - libraries: params.libraries, - limit: params.limit ?? 4, - }, - }), - enabled: params.libraries.length > 0, - }) +export const showcasesQueries = { + all: () => ['showcases'], + mine: () => [...showcasesQueries.all(), 'mine'], + mineList: (params: { pagination: ShowcasePagination }) => + queryOptions({ + queryKey: [...showcasesQueries.mine(), params], + queryFn: () => getMyShowcases({ data: params }), + }), + approved: (params: { + pagination: ShowcasePagination + filters?: { + placement?: 'showcase' | 'community' + libraryIds?: string[] + useCases?: ShowcaseUseCase[] + featured?: boolean + hasSourceCode?: boolean + q?: string + } + }) => + queryOptions({ + queryKey: [...showcasesQueries.all(), 'approved', params], + queryFn: () => getApprovedShowcases({ data: params }), + }), + byLibrary: (params: { libraryId: string; limit?: number }) => + queryOptions({ + queryKey: [ + ...showcasesQueries.all(), + 'library', + params.libraryId, + params.limit, + ], + queryFn: () => + getShowcasesByLibrary({ + data: { libraryId: params.libraryId, limit: params.limit ?? 6 }, + }), + }), + featured: (params: { limit?: number }) => + queryOptions({ + queryKey: [...showcasesQueries.all(), 'featured', params.limit], + queryFn: () => + getFeaturedShowcases({ data: { limit: params.limit ?? 6 } }), + }), + moderation: (params: { + pagination: ShowcasePagination + filters?: ShowcaseFilters + }) => + queryOptions({ + queryKey: [...showcasesQueries.all(), 'moderation', params], + queryFn: () => listShowcasesForModeration({ data: params }), + staleTime: 0, + }), + detail: (showcaseId: string) => + queryOptions({ + queryKey: [...showcasesQueries.all(), 'detail', showcaseId], + queryFn: () => getShowcase({ data: { showcaseId } }), + }), + myVotes: (showcaseIds: string[]) => + queryOptions({ + queryKey: [...showcasesQueries.all(), 'votes', 'mine', showcaseIds], + queryFn: () => getMyShowcaseVotes({ data: { showcaseIds } }), + enabled: showcaseIds.length > 0, + }), + related: (params: { + showcaseId: string + libraries: string[] + limit?: number + }) => + queryOptions({ + queryKey: [...showcasesQueries.all(), 'related', params.showcaseId], + queryFn: () => + getRelatedShowcases({ + data: { + showcaseId: params.showcaseId, + libraries: params.libraries, + limit: params.limit ?? 4, + }, + }), + enabled: params.libraries.length > 0, + }), +} + +export const showcasesMutations = { + vote: () => + mutationOptions({ + mutationFn: (params: { showcaseId: string; value: 1 | -1 }) => + voteShowcase({ data: params }), + }), + galleryVote: ({ + approvedQuery, + showcaseIds, + votesMap, + }: { + approvedQuery: ReturnType + showcaseIds: string[] + votesMap: Map + }) => + mutationOptions({ + mutationFn: (params: { showcaseId: string; value: 1 | -1 }) => + voteShowcase({ data: params }), + onMutate: async ({ showcaseId, value }, { client }) => { + // Cancel outgoing refetches + await client.cancelQueries({ queryKey: showcasesQueries.all() }) + + // Snapshot previous values + const previousShowcases = client.getQueryData(approvedQuery.queryKey) + const previousVotes = client.getQueryData( + showcasesQueries.myVotes(showcaseIds).queryKey, + ) + + // Optimistically update votes + client.setQueryData( + showcasesQueries.myVotes(showcaseIds).queryKey, + (old) => { + if (!old) return { votes: [{ showcaseId, value }] } + const existingVote = old.votes.find( + (v) => v.showcaseId === showcaseId, + ) + if (existingVote) { + if (existingVote.value === value) { + // Toggle off + return { + votes: old.votes.filter((v) => v.showcaseId !== showcaseId), + } + } else { + // Change vote + return { + votes: old.votes.map((v) => + v.showcaseId === showcaseId ? { ...v, value } : v, + ), + } + } + } else { + // New vote + return { votes: [...old.votes, { showcaseId, value }] } + } + }, + ) + + // Optimistically update showcase score + client.setQueryData(approvedQuery.queryKey, (old) => { + if (!old) return old + const currentVote = votesMap.get(showcaseId) + return { + ...old, + showcases: old.showcases.map((s) => { + if (s.showcase.id !== showcaseId) return s + let scoreDelta: number = value + if (currentVote === value) { + // Toggling off + scoreDelta = -value + } else if (currentVote) { + // Changing vote + scoreDelta = value * 2 + } + return { + ...s, + showcase: { + ...s.showcase, + voteScore: s.showcase.voteScore + scoreDelta, + }, + } + }), + } + }) + + return { previousShowcases, previousVotes } + }, + onError: (_err, _vars, context, { client }) => { + // Rollback on error + if (context?.previousShowcases) { + client.setQueryData(approvedQuery.queryKey, context.previousShowcases) + } + if (context?.previousVotes) { + client.setQueryData( + showcasesQueries.myVotes(showcaseIds).queryKey, + context.previousVotes, + ) + } + }, + onSettled: (_data, _error, _variables, _context, { client }) => { + // Refetch to sync with server + client.invalidateQueries({ queryKey: showcasesQueries.all() }) + }, + }), + sectionVote: ({ + queryOptions, + showcaseIds, + votesMap, + }: { + queryOptions: + | ReturnType + | ReturnType + showcaseIds: string[] + votesMap: Map + }) => + mutationOptions({ + mutationFn: (params: { showcaseId: string; value: 1 | -1 }) => + voteShowcase({ data: params }), + onMutate: async ({ showcaseId, value }, { client }) => { + await client.cancelQueries({ queryKey: showcasesQueries.all() }) + + const previousShowcases = client.getQueryData(queryOptions.queryKey) + const previousVotes = client.getQueryData( + showcasesQueries.myVotes(showcaseIds).queryKey, + ) + + // Optimistically update votes + client.setQueryData( + showcasesQueries.myVotes(showcaseIds).queryKey, + (old) => { + if (!old) return { votes: [{ showcaseId, value }] } + const existingVote = old.votes.find( + (v) => v.showcaseId === showcaseId, + ) + if (existingVote) { + if (existingVote.value === value) { + return { + votes: old.votes.filter((v) => v.showcaseId !== showcaseId), + } + } else { + return { + votes: old.votes.map((v) => + v.showcaseId === showcaseId ? { ...v, value } : v, + ), + } + } + } else { + return { votes: [...old.votes, { showcaseId, value }] } + } + }, + ) + + // Optimistically update showcase score + client.setQueryData(queryOptions.queryKey, (old) => { + if (!old) return old + const currentVote = votesMap.get(showcaseId) + return { + ...old, + showcases: old.showcases.map((s) => { + if (s.showcase.id !== showcaseId) return s + let scoreDelta: number = value + if (currentVote === value) { + scoreDelta = -value + } else if (currentVote) { + scoreDelta = value * 2 + } + return { + ...s, + showcase: { + ...s.showcase, + voteScore: s.showcase.voteScore + scoreDelta, + }, + } + }), + } + }) + + return { previousShowcases, previousVotes } + }, + onError: (_err, _vars, context, { client }) => { + if (context?.previousShowcases) { + client.setQueryData(queryOptions.queryKey, context.previousShowcases) + } + if (context?.previousVotes) { + client.setQueryData( + showcasesQueries.myVotes(showcaseIds).queryKey, + context.previousVotes, + ) + } + }, + onSettled: (_data, _error, _variables, _context, { client }) => { + client.invalidateQueries({ queryKey: showcasesQueries.all() }) + }, + }), + detailVote: ({ + showcaseId, + currentUserVote, + }: { + showcaseId: string + currentUserVote: 1 | -1 | null + }) => + mutationOptions({ + mutationFn: (params: { showcaseId: string; value: 1 | -1 }) => + voteShowcase({ data: params }), + onMutate: async ({ showcaseId: voteShowcaseId, value }, { client }) => { + await client.cancelQueries({ queryKey: showcasesQueries.all() }) + + const previousShowcase = client.getQueryData( + showcasesQueries.detail(showcaseId).queryKey, + ) + const previousVotes = client.getQueryData( + showcasesQueries.myVotes([showcaseId]).queryKey, + ) + + // Optimistically update the vote + client.setQueryData( + showcasesQueries.myVotes([showcaseId]).queryKey, + (old) => { + if (!old) return { votes: [{ showcaseId: voteShowcaseId, value }] } + const existingVote = old.votes.find( + (v) => v.showcaseId === voteShowcaseId, + ) + if (existingVote) { + if (existingVote.value === value) { + return { + votes: old.votes.filter( + (v) => v.showcaseId !== voteShowcaseId, + ), + } + } + return { + votes: old.votes.map((v) => + v.showcaseId === voteShowcaseId ? { ...v, value } : v, + ), + } + } + return { + votes: [...old.votes, { showcaseId: voteShowcaseId, value }], + } + }, + ) + + // Optimistically update the showcase score + if (voteShowcaseId === showcaseId) { + client.setQueryData( + showcasesQueries.detail(showcaseId).queryKey, + (old) => { + if (!old) return old + let scoreDelta: number = value + if (currentUserVote === value) { + scoreDelta = -value + } else if (currentUserVote) { + scoreDelta = value * 2 + } + return { + ...old, + showcase: { + ...old.showcase, + voteScore: old.showcase.voteScore + scoreDelta, + }, + } + }, + ) + } + + return { previousShowcase, previousVotes } + }, + onError: (_err, _vars, context, { client }) => { + if (context?.previousShowcase) { + client.setQueryData( + showcasesQueries.detail(showcaseId).queryKey, + context.previousShowcase, + ) + } + if (context?.previousVotes) { + client.setQueryData( + showcasesQueries.myVotes([showcaseId]).queryKey, + context.previousVotes, + ) + } + }, + onSettled: (_data, _error, _variables, _context, { client }) => { + client.invalidateQueries({ queryKey: showcasesQueries.all() }) + }, + }), + setFeatured: () => mutationOptions({ mutationFn: setShowcaseFeatured }), + delete: ({ + onSuccess, + onError, + }: { + onSuccess: () => void + onError: (error: Error) => void + }) => + mutationOptions({ + mutationFn: deleteShowcase, + onSuccess: (_data, _variables, _context, { client }) => { + onSuccess() + client.invalidateQueries({ queryKey: showcasesQueries.mine() }) + }, + onError, + }), + adminDelete: () => mutationOptions({ mutationFn: adminDeleteShowcase }), +} diff --git a/src/queries/stats.ts b/src/queries/stats.ts index f0261a81a..37ff02f61 100644 --- a/src/queries/stats.ts +++ b/src/queries/stats.ts @@ -12,51 +12,46 @@ export type { StatsQueryParams } from '~/utils/stats-queries.functions' type StatsQueryLibrary = NonNullable type RecentDownloadsLibrary = StatsQueryLibrary -export const ossStatsQueryOptions = (params?: StatsQueryParams) => - queryOptions({ - queryKey: ['stats', 'oss', params], - queryFn: () => getOSSStats({ data: { library: params?.library } }), - staleTime: 1000 * 60 * 15, // Cache for 15 minutes - }) +export const statsQueries = { + all: () => ['stats'], + oss: () => [...statsQueries.all(), 'oss'], + ossSummary: ({ library }: { library?: StatsQueryLibrary } = {}) => { + const params: StatsQueryParams = { + library: library + ? { + id: library.id, + npmPackageNames: library.npmPackageNames, + repo: library.repo, + frameworks: library.frameworks, + } + : undefined, + } -export const homepageNpmStatsSummaryQuery = () => - queryOptions({ - queryKey: ['stats', 'homepage-npm-summary'], - queryFn: () => getHomepageNpmStatsSummary(), - staleTime: 1000 * 60 * 15, - }) + return queryOptions({ + queryKey: [...statsQueries.oss(), params], + queryFn: () => getOSSStats({ data: { library: params.library } }), + staleTime: 1000 * 60 * 15, // Cache for 15 minutes + }) + }, + homepageNpmSummary: () => + queryOptions({ + queryKey: [...statsQueries.all(), 'homepage-npm-summary'], + queryFn: () => getHomepageNpmStatsSummary(), + staleTime: 1000 * 60 * 15, + }), + recentDownloads: ({ library }: { library: RecentDownloadsLibrary }) => { + const queryLibrary = { + id: library.id, + npmPackageNames: library.npmPackageNames, + repo: library.repo, + frameworks: library.frameworks, + } -export function ossStatsQuery({ - library, -}: { library?: StatsQueryLibrary } = {}) { - return ossStatsQueryOptions({ - library: library - ? { - id: library.id, - npmPackageNames: library.npmPackageNames, - repo: library.repo, - frameworks: library.frameworks, - } - : undefined, - }) -} - -export function recentDownloadsQuery({ - library, -}: { - library: RecentDownloadsLibrary -}) { - const queryLibrary = { - id: library.id, - npmPackageNames: library.npmPackageNames, - repo: library.repo, - frameworks: library.frameworks, - } - - return queryOptions({ - queryKey: ['npm-recent-downloads', queryLibrary], - queryFn: (): Promise => - fetchRecentDownloadStats({ data: { library: queryLibrary } }), - staleTime: 5 * 60 * 1000, - }) + return queryOptions({ + queryKey: ['npm-recent-downloads', queryLibrary], + queryFn: (): Promise => + fetchRecentDownloadStats({ data: { library: queryLibrary } }), + staleTime: 5 * 60 * 1000, + }) + }, } diff --git a/src/queries/users.ts b/src/queries/users.ts index 9eaa44867..67975b7e7 100644 --- a/src/queries/users.ts +++ b/src/queries/users.ts @@ -18,9 +18,11 @@ export interface ListUsersFilters { sortDir?: 'asc' | 'desc' } -export const listUsersQueryOptions = (filters: ListUsersFilters) => - queryOptions({ - queryKey: ['admin', 'users', filters], - queryFn: () => listUsers({ data: filters }), - staleTime: 0, - }) +export const usersQueries = { + list: (filters: ListUsersFilters) => + queryOptions({ + queryKey: ['admin', 'users', filters], + queryFn: () => listUsers({ data: filters }), + staleTime: 0, + }), +} diff --git a/src/routes/-library-landing-route.tsx b/src/routes/-library-landing-route.tsx index e85111c74..7a5231fbb 100644 --- a/src/routes/-library-landing-route.tsx +++ b/src/routes/-library-landing-route.tsx @@ -3,8 +3,8 @@ import { redirect } from '@tanstack/react-router' import type { QueryClient } from '@tanstack/react-query' import { getLibrary } from '~/libraries' import type { LibraryId } from '~/libraries' -import { docsConfigQueryOptions } from '~/queries/docsConfig' -import { ossStatsQuery, recentDownloadsQuery } from '~/queries/stats' +import { docsConfigQueries } from '~/queries/docsConfig' +import { statsQueries } from '~/queries/stats' import { ogImageUrl } from '~/utils/og' import { seo } from '~/utils/seo' import { stackBlitzEmbedHeaders } from '~/utils/stackblitz-embed' @@ -44,14 +44,16 @@ export async function loadLibraryLandingRouteData( }> { const library = getLibrary(libraryId) const configPromise = queryClient.ensureQueryData( - docsConfigQueryOptions(libraryId, version), + docsConfigQueries.detail(libraryId, version), ) const statsPromise = library.statsAvailable === false ? Promise.resolve() : Promise.all([ - queryClient.ensureQueryData(ossStatsQuery({ library })), - queryClient.ensureQueryData(recentDownloadsQuery({ library })), + queryClient.ensureQueryData(statsQueries.ossSummary({ library })), + queryClient.ensureQueryData( + statsQueries.recentDownloads({ library }), + ), ]).then(() => undefined) const [config] = await Promise.all([configPromise, statsPromise]) diff --git a/src/routes/_library/$libraryId/$version.tsx b/src/routes/_library/$libraryId/$version.tsx index 661f89e0e..5b2bd4a60 100644 --- a/src/routes/_library/$libraryId/$version.tsx +++ b/src/routes/_library/$libraryId/$version.tsx @@ -6,7 +6,7 @@ import { } from '@tanstack/react-router' import { RedirectVersionBanner } from '~/components/RedirectVersionBanner' import { findLibrary } from '~/libraries' -import { docsConfigQueryOptions } from '~/queries/docsConfig' +import { docsConfigQueries } from '~/queries/docsConfig' import { validateLibraryVersion } from '../../-library-landing' export const Route = createFileRoute('/_library/$libraryId/$version')({ @@ -49,7 +49,7 @@ export const Route = createFileRoute('/_library/$libraryId/$version')({ return { config: await ctx.context.queryClient.ensureQueryData( - docsConfigQueryOptions(library.id, version!), + docsConfigQueries.detail(library.id, version!), ), } }, diff --git a/src/routes/_library/charts.catalog.tsx b/src/routes/_library/charts.catalog.tsx index 040b4e305..5e3b05626 100644 --- a/src/routes/_library/charts.catalog.tsx +++ b/src/routes/_library/charts.catalog.tsx @@ -1,11 +1,11 @@ import { Outlet, createFileRoute } from '@tanstack/react-router' -import { docsConfigQueryOptions } from '~/queries/docsConfig' +import { docsConfigQueries } from '~/queries/docsConfig' export const Route = createFileRoute('/_library/charts/catalog')({ staleTime: 1000 * 60 * 5, loader: async ({ context: { queryClient } }) => ({ config: await queryClient.ensureQueryData( - docsConfigQueryOptions('charts', 'latest'), + docsConfigQueries.detail('charts', 'latest'), ), version: 'latest', }), diff --git a/src/routes/_library/highlight.$version.theme-editor.tsx b/src/routes/_library/highlight.$version.theme-editor.tsx index dad771ba7..32d6aac89 100644 --- a/src/routes/_library/highlight.$version.theme-editor.tsx +++ b/src/routes/_library/highlight.$version.theme-editor.tsx @@ -1,5 +1,5 @@ import { createFileRoute, redirect } from '@tanstack/react-router' -import { docsConfigQueryOptions } from '~/queries/docsConfig' +import { docsConfigQueries } from '~/queries/docsConfig' import { ThemeEditorPage } from '~/components/highlight-theme-editor/ThemeEditorPage' import { validateLibraryVersion } from '../-library-landing' @@ -20,7 +20,7 @@ export const Route = createFileRoute( loader: async ({ params, context: { queryClient } }) => { return { config: await queryClient.ensureQueryData( - docsConfigQueryOptions('highlight', params.version), + docsConfigQueries.detail('highlight', params.version), ), } }, diff --git a/src/routes/account/feedback.tsx b/src/routes/account/feedback.tsx index ffc3b7737..ac81a8133 100644 --- a/src/routes/account/feedback.tsx +++ b/src/routes/account/feedback.tsx @@ -1,7 +1,7 @@ import * as React from 'react' import { Link, createFileRoute } from '@tanstack/react-router' import { useQuery } from '@tanstack/react-query' -import { getUserDocFeedbackQueryOptions } from '~/queries/docFeedback' +import { docFeedbackQueries } from '~/queries/docFeedback' import { PaginationControls } from '~/components/PaginationControls' import { useCurrentUserQuery } from '~/hooks/useCurrentUser' import { DocFeedbackNote } from '~/components/DocFeedbackNote' @@ -22,7 +22,7 @@ function AccountFeedbackPage() { user && typeof user === 'object' && 'userId' in user ? user.userId : null const { data, isLoading } = useQuery( - getUserDocFeedbackQueryOptions({ + docFeedbackQueries.user({ pagination: { page, pageSize }, filters: { type: ['improvement'] }, }), diff --git a/src/routes/account/notes.tsx b/src/routes/account/notes.tsx index e3ce540ca..bb8331b1d 100644 --- a/src/routes/account/notes.tsx +++ b/src/routes/account/notes.tsx @@ -1,7 +1,7 @@ import * as React from 'react' import { Link, createFileRoute } from '@tanstack/react-router' import { useQuery } from '@tanstack/react-query' -import { getUserDocFeedbackQueryOptions } from '~/queries/docFeedback' +import { docFeedbackQueries } from '~/queries/docFeedback' import { PaginationControls } from '~/components/PaginationControls' import { useCurrentUserQuery } from '~/hooks/useCurrentUser' import { DocFeedbackNote } from '~/components/DocFeedbackNote' @@ -22,7 +22,7 @@ function AccountNotesPage() { user && typeof user === 'object' && 'userId' in user ? user.userId : null const { data, isLoading } = useQuery( - getUserDocFeedbackQueryOptions({ + docFeedbackQueries.user({ pagination: { page, pageSize }, filters: { type: ['note'] }, }), diff --git a/src/routes/account/submissions.tsx b/src/routes/account/submissions.tsx index 368080135..19c62d38a 100644 --- a/src/routes/account/submissions.tsx +++ b/src/routes/account/submissions.tsx @@ -1,9 +1,8 @@ import { PLACEMENT_LABELS } from '~/utils/showcase.shared' import * as React from 'react' import { Link, createFileRoute } from '@tanstack/react-router' -import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query' -import { getMyShowcasesQueryOptions } from '~/queries/showcases' -import { deleteShowcase } from '~/utils/showcase.functions' +import { useQuery, useMutation } from '@tanstack/react-query' +import { showcasesMutations, showcasesQueries } from '~/queries/showcases' import { libraries } from '~/libraries' import { useToast } from '~/components/ToastProvider' import { seo } from '~/utils/seo' @@ -22,7 +21,7 @@ import { Badge, Button } from '~/ui' export const Route = createFileRoute('/account/submissions')({ loader: async ({ context: { queryClient } }) => { await queryClient.ensureQueryData( - getMyShowcasesQueryOptions({ + showcasesQueries.mineList({ pagination: { page: 1, pageSize: 20 }, }), ) @@ -39,36 +38,35 @@ export const Route = createFileRoute('/account/submissions')({ const libraryMap = new Map(libraries.map((lib) => [lib.id as string, lib])) function AccountSubmissionsPage() { - const queryClient = useQueryClient() const { notify } = useToast() const { data, isLoading } = useQuery( - getMyShowcasesQueryOptions({ + showcasesQueries.mineList({ pagination: { page: 1, pageSize: 20 }, }), ) - const deleteMutation = useMutation({ - mutationFn: deleteShowcase, - onSuccess: () => { - notify( -
-
Showcase deleted
-
, - ) - queryClient.invalidateQueries({ queryKey: ['showcases', 'mine'] }) - }, - onError: (error: Error) => { - notify( -
-
Delete failed
-
- {error.message} -
-
, - ) - }, - }) + const deleteMutation = useMutation( + showcasesMutations.delete({ + onSuccess: () => { + notify( +
+
Showcase deleted
+
, + ) + }, + onError: (error) => { + notify( +
+
Delete failed
+
+ {error.message} +
+
, + ) + }, + }), + ) const handleDelete = (showcaseId: string) => { if (confirm('Are you sure you want to delete this showcase?')) { diff --git a/src/routes/admin/feedback.index.tsx b/src/routes/admin/feedback.index.tsx index f14256b3f..312930bbb 100644 --- a/src/routes/admin/feedback.index.tsx +++ b/src/routes/admin/feedback.index.tsx @@ -2,7 +2,7 @@ import { redirect, createFileRoute } from '@tanstack/react-router' import * as v from 'valibot' import { seo } from '~/utils/seo' import { FeedbackModerationPage } from '~/components/FeedbackModerationPage' -import { listDocFeedbackForModerationQueryOptions } from '~/queries/docFeedback' +import { docFeedbackQueries } from '~/queries/docFeedback' import { requireCapability } from '~/utils/auth.functions' import { libraryIdSchema, @@ -46,7 +46,7 @@ export const Route = createFileRoute('/admin/feedback/')({ }), loader: async ({ deps, context: { queryClient } }) => { await queryClient.ensureQueryData( - listDocFeedbackForModerationQueryOptions({ + docFeedbackQueries.moderation({ pagination: { page: deps.page, pageSize: deps.pageSize, diff --git a/src/routes/admin/feedback_.$id.tsx b/src/routes/admin/feedback_.$id.tsx index ae87b458e..18449f2d9 100644 --- a/src/routes/admin/feedback_.$id.tsx +++ b/src/routes/admin/feedback_.$id.tsx @@ -5,6 +5,7 @@ import { moderateDocFeedback, } from '~/utils/docFeedback.functions' import { libraries } from '~/libraries' +import { docFeedbackQueries } from '~/queries/docFeedback' import { ArrowLeftIcon, ChatCenteredIcon, @@ -47,7 +48,9 @@ function FeedbackDetailPage() { }), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['admin', 'feedback', id] }) - queryClient.invalidateQueries({ queryKey: ['docFeedback', 'moderation'] }) + queryClient.invalidateQueries({ + queryKey: docFeedbackQueries.moderations(), + }) }, }) diff --git a/src/routes/admin/notes.index.tsx b/src/routes/admin/notes.index.tsx index d5681537c..2641d394b 100644 --- a/src/routes/admin/notes.index.tsx +++ b/src/routes/admin/notes.index.tsx @@ -2,7 +2,7 @@ import { redirect, createFileRoute } from '@tanstack/react-router' import * as v from 'valibot' import { seo } from '~/utils/seo' import { NotesModerationPage } from '~/components/NotesModerationPage' -import { listDocFeedbackForModerationQueryOptions } from '~/queries/docFeedback' +import { docFeedbackQueries } from '~/queries/docFeedback' import { requireCapability } from '~/utils/auth.functions' import { isoDateSchema, @@ -48,7 +48,7 @@ export const Route = createFileRoute('/admin/notes/')({ }), loader: async ({ deps, context: { queryClient } }) => { await queryClient.ensureQueryData( - listDocFeedbackForModerationQueryOptions({ + docFeedbackQueries.moderation({ pagination: { page: deps.page, pageSize: deps.pageSize, diff --git a/src/routes/admin/npm-stats.tsx b/src/routes/admin/npm-stats.tsx index f81787f96..492cd07f3 100644 --- a/src/routes/admin/npm-stats.tsx +++ b/src/routes/admin/npm-stats.tsx @@ -3,7 +3,7 @@ import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { DownloadIcon, ArrowsClockwiseIcon } from '@phosphor-icons/react' import { Card } from '~/components/Card' import { NpmIcon } from '~/components/icons/NpmIcon' -import { homepageNpmStatsSummaryQuery } from '~/queries/stats' +import { statsQueries } from '~/queries/stats' import { Button } from '~/ui' import { refreshAllNpmStats } from '~/utils/stats-admin.functions' import { formatDistanceToNow } from '~/utils/dates' @@ -15,16 +15,16 @@ export const Route = createFileRoute('/admin/npm-stats')({ function NpmStatsAdmin() { const queryClient = useQueryClient() const { data: homepageSummary, isLoading: homepageSummaryLoading } = useQuery( - homepageNpmStatsSummaryQuery(), + statsQueries.homepageNpmSummary(), ) const refreshSummaryMutation = useMutation({ mutationFn: () => refreshAllNpmStats({ data: { org: 'tanstack' } }), onSuccess: () => { queryClient.invalidateQueries({ - queryKey: ['stats', 'homepage-npm-summary'], + queryKey: statsQueries.homepageNpmSummary().queryKey, }) - queryClient.invalidateQueries({ queryKey: ['stats', 'oss'] }) + queryClient.invalidateQueries({ queryKey: statsQueries.oss() }) }, }) diff --git a/src/routes/admin/showcases.index.tsx b/src/routes/admin/showcases.index.tsx index 884d9e9a4..7eed68459 100644 --- a/src/routes/admin/showcases.index.tsx +++ b/src/routes/admin/showcases.index.tsx @@ -2,7 +2,7 @@ import { redirect, createFileRoute } from '@tanstack/react-router' import * as v from 'valibot' import { seo } from '~/utils/seo' import { ShowcaseModerationPage } from '~/components/ShowcaseModerationPage' -import { listShowcasesForModerationQueryOptions } from '~/queries/showcases' +import { showcasesQueries } from '~/queries/showcases' import { requireCapability } from '~/utils/auth.functions' import { libraryIdSchema, @@ -44,7 +44,7 @@ export const Route = createFileRoute('/admin/showcases/')({ }), loader: async ({ deps, context: { queryClient } }) => { await queryClient.ensureQueryData( - listShowcasesForModerationQueryOptions({ + showcasesQueries.moderation({ pagination: { page: deps.page, pageSize: deps.pageSize, diff --git a/src/routes/admin/showcases_.$id.tsx b/src/routes/admin/showcases_.$id.tsx index 3f4862acb..0d55a8ed6 100644 --- a/src/routes/admin/showcases_.$id.tsx +++ b/src/routes/admin/showcases_.$id.tsx @@ -10,6 +10,7 @@ import { voteShowcase, } from '~/utils/showcase.functions' import { libraries } from '~/libraries' +import { showcasesQueries } from '~/queries/showcases' import { USE_CASE_LABELS, PLACEMENT_LABELS } from '~/utils/showcase.shared' import { ArrowLeftIcon, @@ -77,7 +78,7 @@ function ShowcaseDetailPage() { adminUpdateShowcase({ data }), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['admin', 'showcase', id] }) - queryClient.invalidateQueries({ queryKey: ['showcases'] }) + queryClient.invalidateQueries({ queryKey: showcasesQueries.all() }) setIsEditing(false) setFormData(null) }, @@ -86,7 +87,7 @@ function ShowcaseDetailPage() { const deleteMutation = useMutation({ mutationFn: () => adminDeleteShowcase({ data: { showcaseId: id } }), onSuccess: () => { - queryClient.invalidateQueries({ queryKey: ['showcases'] }) + queryClient.invalidateQueries({ queryKey: showcasesQueries.all() }) navigate({ to: '/admin/showcases' }) }, }) @@ -96,7 +97,7 @@ function ShowcaseDetailPage() { voteShowcase({ data: { showcaseId: id, value: params.value } }), onSuccess: () => { queryClient.invalidateQueries({ queryKey: ['admin', 'showcase', id] }) - queryClient.invalidateQueries({ queryKey: ['showcases'] }) + queryClient.invalidateQueries({ queryKey: showcasesQueries.all() }) }, }) diff --git a/src/routes/admin/users.tsx b/src/routes/admin/users.tsx index 7bd83558c..e8fed71f7 100644 --- a/src/routes/admin/users.tsx +++ b/src/routes/admin/users.tsx @@ -34,12 +34,8 @@ import { type SignupSource, } from '~/db/types' import * as v from 'valibot' -import { listUsersQueryOptions } from '~/queries/users' -import { - listRolesQueryOptions, - getBulkUserRolesQueryOptions, - getBulkEffectiveCapabilitiesQueryOptions, -} from '~/queries/roles' +import { usersQueries } from '~/queries/users' +import { rolesQueries } from '~/queries/roles' import { getUserRoles } from '~/utils/roles.functions' import { FloppyDiskIcon, @@ -287,7 +283,7 @@ function UsersPage() { const pageSize = search.pageSize ?? 10 const usersQuery = useQuery({ - ...listUsersQueryOptions({ + ...usersQueries.list({ pagination: { limit: pageSize, page: currentPageIndex, @@ -316,7 +312,7 @@ function UsersPage() { const bulkAssignRolesToUsers = useBulkAssignRolesToUsers() const bulkUpdateUserCapabilities = useBulkUpdateUserCapabilities() const allRolesQuery = useQuery({ - ...listRolesQueryOptions({}), + ...rolesQueries.list({}), placeholderData: keepPreviousData, }) const allRoles = useMemo(() => allRolesQuery.data || [], [allRolesQuery.data]) @@ -327,12 +323,12 @@ function UsersPage() { [usersQuery?.data?.page], ) const bulkUserRolesQuery = useQuery({ - ...getBulkUserRolesQueryOptions(userIds), + ...rolesQueries.bulkUserRoles(userIds), placeholderData: keepPreviousData, }) const bulkUserRoles = bulkUserRolesQuery.data const bulkEffectiveCapabilitiesQuery = useQuery({ - ...getBulkEffectiveCapabilitiesQueryOptions(userIds), + ...rolesQueries.bulkEffectiveCapabilities(userIds), placeholderData: keepPreviousData, }) const bulkEffectiveCapabilities = bulkEffectiveCapabilitiesQuery.data diff --git a/src/routes/community-projects.tsx b/src/routes/community-projects.tsx index fda322e03..807c78b01 100644 --- a/src/routes/community-projects.tsx +++ b/src/routes/community-projects.tsx @@ -2,7 +2,7 @@ import { createFileRoute } from '@tanstack/react-router' import * as v from 'valibot' import { seo } from '~/utils/seo' import { ShowcaseGallery } from '~/components/ShowcaseGallery' -import { getApprovedShowcasesQueryOptions } from '~/queries/showcases' +import { showcasesQueries } from '~/queries/showcases' import { libraryIdSchema, showcaseUseCaseSchema, @@ -44,7 +44,7 @@ export const Route = createFileRoute('/community-projects')({ }), loader: async ({ deps, context: { queryClient } }) => { await queryClient.ensureQueryData( - getApprovedShowcasesQueryOptions({ + showcasesQueries.approved({ pagination: { page: deps.page, pageSize: deps.pageSize, diff --git a/src/routes/feedback-leaderboard.tsx b/src/routes/feedback-leaderboard.tsx index 767ca12b9..b0031e844 100644 --- a/src/routes/feedback-leaderboard.tsx +++ b/src/routes/feedback-leaderboard.tsx @@ -2,7 +2,7 @@ import { createFileRoute } from '@tanstack/react-router' import * as v from 'valibot' import { seo } from '~/utils/seo' import { FeedbackLeaderboard } from '~/components/FeedbackLeaderboard' -import { getDocFeedbackLeaderboardQueryOptions } from '~/queries/docFeedback' +import { docFeedbackQueries } from '~/queries/docFeedback' const searchSchema = v.object({ page: v.fallback(v.optional(v.number(), 1), 1), @@ -21,7 +21,7 @@ export const Route = createFileRoute('/feedback-leaderboard')({ }), loader: async ({ deps, context: { queryClient } }) => { await queryClient.ensureQueryData( - getDocFeedbackLeaderboardQueryOptions({ + docFeedbackQueries.leaderboard({ pagination: { page: deps.page, pageSize: deps.pageSize, diff --git a/src/routes/index.tsx b/src/routes/index.tsx index c515252e5..941ca5d4f 100644 --- a/src/routes/index.tsx +++ b/src/routes/index.tsx @@ -24,7 +24,7 @@ import { useQuery } from '@tanstack/react-query' import { Button } from '~/components/ds/ui' import { Scarf } from '~/components/Scarf' import { useInView } from '~/hooks/useInView' -import { homepageNpmStatsSummaryQuery, ossStatsQuery } from '~/queries/stats' +import { statsQueries } from '~/queries/stats' import { useLibrariesOverlay } from '~/contexts/LibrariesOverlayContext' import { fetchRecentPosts } from '~/utils/blog.functions' import { usePrefersReducedMotion } from '~/utils/usePrefersReducedMotion' @@ -33,9 +33,9 @@ import { getTanStackHomepageJsonLd } from '~/utils/organization-structured-data' export const Route = createFileRoute('/')({ loader: async ({ context: { queryClient } }) => { - const npmStatsQuery = homepageNpmStatsSummaryQuery() + const npmStatsQuery = statsQueries.homepageNpmSummary() const [stats, npmSummary, recentPosts] = await Promise.all([ - queryClient.ensureQueryData(ossStatsQuery()), + queryClient.ensureQueryData(statsQueries.ossSummary()), queryClient.ensureQueryData(npmStatsQuery), fetchRecentPosts(), ]) @@ -683,9 +683,9 @@ function PrincipleProof({ function AdoptionProof() { const { initialStats } = Route.useLoaderData() const { data: summary, dataUpdatedAt } = useQuery( - homepageNpmStatsSummaryQuery(), + statsQueries.homepageNpmSummary(), ) - const { data: stats } = useQuery(ossStatsQuery()) + const { data: stats } = useQuery(statsQueries.ossSummary()) const totalDownloads = summary?.totalDownloads ?? initialStats.totalDownloads ?? 0 diff --git a/src/routes/intent/registry/$packageName.$skillName.tsx b/src/routes/intent/registry/$packageName.$skillName.tsx index 8de195819..a43d80b7d 100644 --- a/src/routes/intent/registry/$packageName.$skillName.tsx +++ b/src/routes/intent/registry/$packageName.$skillName.tsx @@ -2,11 +2,7 @@ import * as React from 'react' import { createFileRoute, Link, useNavigate } from '@tanstack/react-router' import { useSuspenseQuery, useQuery } from '@tanstack/react-query' import { seo } from '~/utils/seo' -import { - intentPackageDetailQueryOptions, - intentVersionSkillsQueryOptions, - intentSingleSkillHistoryQueryOptions, -} from '~/queries/intent' +import { intentQueries } from '~/queries/intent' import { getIntentSkillPage, type SkillVersionEntry, @@ -54,13 +50,13 @@ export const Route = createFileRoute( loader: async ({ params, deps, context: { queryClient } }) => { const name = decodePkgName(params.packageName) const detail = await queryClient.ensureQueryData( - intentPackageDetailQueryOptions(name), + intentQueries.packageDetail(name), ) const latestVersion = detail?.versions[0]?.version ?? '' const activeVersion = deps.version ?? latestVersion if (activeVersion) { await queryClient.ensureQueryData( - intentVersionSkillsQueryOptions({ + intentQueries.versionSkills({ packageName: name, version: activeVersion, }), @@ -112,7 +108,7 @@ function SkillDetailPage() { ) const skillsQuery = useSuspenseQuery( - intentVersionSkillsQueryOptions({ + intentQueries.versionSkills({ packageName: pkgName, version: activeVersion, }), @@ -276,7 +272,7 @@ function SkillVersionHistory({ readonly activeVersion: string }) { const historyQuery = useQuery( - intentSingleSkillHistoryQueryOptions({ packageName, skillName }), + intentQueries.singleSkillHistory({ packageName, skillName }), ) const entries = historyQuery.data diff --git a/src/routes/intent/registry/$packageName.index.tsx b/src/routes/intent/registry/$packageName.index.tsx index c56ba0c52..584bfb537 100644 --- a/src/routes/intent/registry/$packageName.index.tsx +++ b/src/routes/intent/registry/$packageName.index.tsx @@ -1,11 +1,7 @@ import * as React from 'react' import { createFileRoute, Link, useNavigate } from '@tanstack/react-router' import { useSuspenseQuery, useQuery } from '@tanstack/react-query' -import { - intentPackageDetailQueryOptions, - intentVersionSkillsQueryOptions, - intentPackageChangelogQueryOptions, -} from '~/queries/intent' +import { intentQueries } from '~/queries/intent' import type { ChangelogEntry } from '~/utils/intent.functions' import { Panel, PanelContent } from '~/components/Panel' const LazySkillDiffViewer = React.lazy(() => @@ -26,13 +22,13 @@ export const Route = createFileRoute('/intent/registry/$packageName/')({ loader: async ({ params, deps, context: { queryClient } }) => { const name = decodePkgName(params.packageName) const detail = queryClient.getQueryData( - intentPackageDetailQueryOptions(name).queryKey, + intentQueries.packageDetail(name).queryKey, ) const latestVersion = detail?.versions[0]?.version ?? '' const activeVersion = deps.version ?? latestVersion if (activeVersion) { await queryClient.ensureQueryData( - intentVersionSkillsQueryOptions({ + intentQueries.versionSkills({ packageName: name, version: activeVersion, }), @@ -68,14 +64,14 @@ function PackageIndexPage() { ) const skillsQuery = useSuspenseQuery( - intentVersionSkillsQueryOptions({ + intentQueries.versionSkills({ packageName: pkgName, version: activeVersion, }), ) const skills = skillsQuery.data?.skills ?? [] - const changelogQuery = useQuery(intentPackageChangelogQueryOptions(pkgName)) + const changelogQuery = useQuery(intentQueries.packageChangelog(pkgName)) const expandedSkillSet = React.useMemo( () => new Set(urlExpandedSkills ?? []), diff --git a/src/routes/intent/registry/$packageName.tsx b/src/routes/intent/registry/$packageName.tsx index 1e88adcf3..ccadb0e9d 100644 --- a/src/routes/intent/registry/$packageName.tsx +++ b/src/routes/intent/registry/$packageName.tsx @@ -11,11 +11,7 @@ import * as v from 'valibot' import { CopyIcon, CheckIcon } from '@phosphor-icons/react' import { Panel, PanelContent } from '~/components/Panel' import { seo } from '~/utils/seo' -import { - intentPackageDetailQueryOptions, - intentVersionSkillsQueryOptions, - intentSkillHistoryQueryOptions, -} from '~/queries/intent' +import { intentQueries } from '~/queries/intent' import type { IntentPackageDetail } from '~/utils/intent.functions' import { useToast } from '~/components/ToastProvider' import { SkillSparklineFallback } from '~/components/intent/SkillSparklineFallback' @@ -68,7 +64,7 @@ export const Route = createFileRoute('/intent/registry/$packageName')({ validateSearch: (search) => v.parse(searchSchema, search), loader: async ({ params, context: { queryClient } }) => { const name = decodePkgName(params.packageName) - await queryClient.ensureQueryData(intentPackageDetailQueryOptions(name)) + await queryClient.ensureQueryData(intentQueries.packageDetail(name)) }, head: ({ params }) => { const name = decodePkgName(params.packageName) @@ -98,7 +94,7 @@ function PackageLayout() { function PackageLayoutContent({ name }: { readonly name: string }) { const { version: searchVersion } = Route.useSearch() const navigate = useNavigate({ from: Route.fullPath }) - const detailQuery = useSuspenseQuery(intentPackageDetailQueryOptions(name)) + const detailQuery = useSuspenseQuery(intentQueries.packageDetail(name)) const detail = detailQuery.data const latestVersion = detail?.versions[0]?.version ?? '' @@ -155,7 +151,7 @@ function PackageLayoutInner({ } const skillsQuery = useSuspenseQuery( - intentVersionSkillsQueryOptions({ + intentQueries.versionSkills({ packageName: name, version: activeVersion, }), @@ -163,9 +159,7 @@ function PackageLayoutInner({ const skills = skillsQuery.data?.skills ?? [] const packageNames = React.useMemo(() => [name], [name]) - const skillHistoryQuery = useQuery( - intentSkillHistoryQueryOptions(packageNames), - ) + const skillHistoryQuery = useQuery(intentQueries.skillHistory(packageNames)) const skillHistory = skillHistoryQuery.data?.[name] return ( diff --git a/src/routes/intent/registry/index.tsx b/src/routes/intent/registry/index.tsx index bd6c3f9c8..d1dbc207a 100644 --- a/src/routes/intent/registry/index.tsx +++ b/src/routes/intent/registry/index.tsx @@ -3,12 +3,7 @@ import { createFileRoute, Link, useNavigate } from '@tanstack/react-router' import { useSuspenseQuery, useQuery } from '@tanstack/react-query' import * as v from 'valibot' import { seo } from '~/utils/seo' -import { - intentStatsQueryOptions, - intentDirectoryQueryOptions, - intentSkillSearchQueryOptions, - intentSkillHistoryQueryOptions, -} from '~/queries/intent' +import { intentQueries } from '~/queries/intent' import type { EnrichedIntentPackage, SkillHistoryEntry, @@ -47,9 +42,9 @@ export const Route = createFileRoute('/intent/registry/')({ }), loader: ({ deps, context: { queryClient } }) => Promise.all([ - queryClient.ensureQueryData(intentStatsQueryOptions()), + queryClient.ensureQueryData(intentQueries.stats()), queryClient.ensureQueryData( - intentDirectoryQueryOptions({ + intentQueries.directory({ search: deps.q, framework: deps.framework, sort: deps.sort, @@ -74,12 +69,12 @@ function IntentRegistryPage() { const { q, tab, framework, sort, page, view } = Route.useSearch() const navigate = Route.useNavigate() - const statsQuery = useSuspenseQuery(intentStatsQueryOptions()) + const statsQuery = useSuspenseQuery(intentQueries.stats()) const directoryQuery = useSuspenseQuery( - intentDirectoryQueryOptions({ search: q, framework, sort, page }), + intentQueries.directory({ search: q, framework, sort, page }), ) const skillSearchQuery = useQuery({ - ...intentSkillSearchQueryOptions(q ?? ''), + ...intentQueries.skillSearch(q ?? ''), enabled: tab === 'skills' && (q?.trim().length ?? 0) > 0, }) @@ -95,7 +90,7 @@ function IntentRegistryPage() { [packageNames], ) const skillHistoryQuery = useQuery( - intentSkillHistoryQueryOptions(skillHistoryPackageNames), + intentQueries.skillHistory(skillHistoryPackageNames), ) const skillHistory = React.useMemo( () => skillHistoryQuery.data ?? {}, diff --git a/src/routes/showcase/$id.tsx b/src/routes/showcase/$id.tsx index df130ae9d..571a7d39d 100644 --- a/src/routes/showcase/$id.tsx +++ b/src/routes/showcase/$id.tsx @@ -3,10 +3,7 @@ import { createFileRoute } from '@tanstack/react-router' import * as v from 'valibot' import { seo } from '~/utils/seo' import { ShowcaseDetail } from '~/components/ShowcaseDetail' -import { - getShowcaseQueryOptions, - getRelatedShowcasesQueryOptions, -} from '~/queries/showcases' +import { showcasesQueries } from '~/queries/showcases' export const Route = createFileRoute('/showcase/$id')({ params: { @@ -17,12 +14,12 @@ export const Route = createFileRoute('/showcase/$id')({ }, loader: async ({ params, context: { queryClient } }) => { const showcaseData = await queryClient.ensureQueryData( - getShowcaseQueryOptions(params.id), + showcasesQueries.detail(params.id), ) if (showcaseData?.showcase.libraries.length) { await queryClient.ensureQueryData( - getRelatedShowcasesQueryOptions({ + showcasesQueries.related({ showcaseId: params.id, libraries: showcaseData.showcase.libraries, limit: 4, diff --git a/src/routes/showcase/index.tsx b/src/routes/showcase/index.tsx index 063b52f59..1c44027c1 100644 --- a/src/routes/showcase/index.tsx +++ b/src/routes/showcase/index.tsx @@ -2,7 +2,7 @@ import { createFileRoute, stripSearchParams } from '@tanstack/react-router' import * as v from 'valibot' import { seo } from '~/utils/seo' import { ShowcaseGallery } from '~/components/ShowcaseGallery' -import { getApprovedShowcasesQueryOptions } from '~/queries/showcases' +import { showcasesQueries } from '~/queries/showcases' import { showcaseSearchSchema, defaultShowcaseSearch, @@ -36,7 +36,7 @@ export const Route = createFileRoute('/showcase/')({ }), loader: async ({ deps, context: { queryClient } }) => { await queryClient.ensureQueryData( - getApprovedShowcasesQueryOptions({ + showcasesQueries.approved({ pagination: { page: deps.page, pageSize: deps.pageSize, diff --git a/src/utils/docs.ts b/src/utils/docs.ts index 9c20f4921..37cec8198 100644 --- a/src/utils/docs.ts +++ b/src/utils/docs.ts @@ -1,6 +1,6 @@ import { isNotFound, notFound } from '@tanstack/react-router' import type { QueryClient } from '@tanstack/react-query' -import { docsPathManifestQueryOptions } from '~/queries/docsManifest' +import { docsManifestQueries } from '~/queries/docsManifest' import { fetchDocs, fetchDocsManifest, @@ -104,7 +104,7 @@ export async function resolveDocsRoutePath(opts: { docsRoot: opts.docsRoot, } const manifest = opts.queryClient - ? await opts.queryClient.fetchQuery(docsPathManifestQueryOptions(request)) + ? await opts.queryClient.fetchQuery(docsManifestQueries.paths(request)) : await fetchDocsPathManifest({ data: request }) if (manifest.paths.length === 0) { @@ -256,7 +256,7 @@ async function findLatestDocsPath( docsRoot: opts.docsRoot, } const manifest = opts.queryClient - ? await opts.queryClient.fetchQuery(docsPathManifestQueryOptions(request)) + ? await opts.queryClient.fetchQuery(docsManifestQueries.paths(request)) : await fetchDocsPathManifest({ data: request }) return docsManifestHasPath(manifest, docsPath) ? docsPath : null diff --git a/tests/docs-manifest-cache.test.ts b/tests/docs-manifest-cache.test.ts index 503c6f89a..b4da38495 100644 --- a/tests/docs-manifest-cache.test.ts +++ b/tests/docs-manifest-cache.test.ts @@ -1,7 +1,7 @@ import assert from 'node:assert/strict' import test from 'node:test' import { dehydrate, hydrate, QueryClient } from '@tanstack/react-query' -import { docsPathManifestQueryOptions } from '../src/queries/docsManifest' +import { docsManifestQueries } from '../src/queries/docsManifest' import { resolveDocsRoutePath } from '../src/utils/docs' const request = { @@ -12,7 +12,7 @@ const request = { test('docs navigation reuses the manifest hydrated by the server', async () => { const serverClient = new QueryClient() - serverClient.setQueryData(docsPathManifestQueryOptions(request).queryKey, { + serverClient.setQueryData(docsManifestQueries.paths(request).queryKey, { paths: ['routing/routing-concepts', 'routing/route-trees'], redirects: {}, }) @@ -64,7 +64,7 @@ test('cached manifests stay separate for each repository, branch, and docs root' try { for (const [index, data] of requests.entries()) { - queryClient.setQueryData(docsPathManifestQueryOptions(data).queryKey, { + queryClient.setQueryData(docsManifestQueries.paths(data).queryKey, { paths: [`page-${index}`], redirects: {}, }) diff --git a/tests/mutation-cache-updates.test.ts b/tests/mutation-cache-updates.test.ts new file mode 100644 index 000000000..16e0c3221 --- /dev/null +++ b/tests/mutation-cache-updates.test.ts @@ -0,0 +1,359 @@ +import { test } from 'node:test' +import { build } from 'esbuild' +import { mkdtemp, writeFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' + +// Each factory holds the mutation of one call site. Server functions are stubbed so a +// test can hold a call open (to read the optimistic cache), then resolve or +// reject it (to read the settled or rolled-back cache). +test('mutation options update, roll back, and invalidate the query cache', async () => { + const root = resolve(import.meta.dirname, '..') + const directory = await mkdtemp(join(tmpdir(), 'mutation-cache-')) + try { + const result = await build({ + stdin: { + resolveDir: root, + contents: ` + import assert from 'node:assert/strict' + import { MutationObserver, QueryClient } from '@tanstack/react-query' + import { showcasesMutations, showcasesQueries } from './src/queries/showcases' + import { docFeedbackMutations, docFeedbackQueries } from './src/queries/docFeedback' + import { server } from 'server-functions' + + function setup() { + return new QueryClient({ defaultOptions: { queries: { retry: false }, mutations: { retry: false } } }) + } + + // Runs mutation options the way useMutation does, without rendering. + function observe(client, options) { + const observer = new MutationObserver(client, options) + return { mutateAsync: (variables) => observer.mutate(variables) } + } + + function isInvalidated(client, queryKey) { + return client.getQueryState(queryKey).isInvalidated + } + + // A query outside every prefix used below, to prove invalidation stays scoped. + const outsideKey = docFeedbackQueries.page({ pagePath: 'overview', libraryVersion: 'latest' }).queryKey + + // new vote adds the value, voting the same value again removes it, + // and switching sides moves the score by twice the value. + const voteCases = [ + { name: 'new vote', current: undefined, value: 1, delta: 1, votes: [{ showcaseId: 'a', value: 1 }] }, + { name: 'toggle off', current: 1, value: 1, delta: -1, votes: [] }, + { name: 'switch', current: -1, value: 1, delta: 2, votes: [{ showcaseId: 'a', value: 1 }] }, + ] + + // listQuery holds showcase 'a' with score 10; votesKey holds my votes. + async function checkVote({ label, listQuery, listData, scoreOf, votesKey, mutationOptionsFor }) { + for (const c of voteCases) { + for (const outcome of ['resolve', 'reject']) { + const name = label + ' ' + c.name + ' (' + outcome + ')' + const client = setup() + const previousVotes = { votes: c.current ? [{ showcaseId: 'a', value: c.current }] : [] } + client.setQueryData(listQuery.queryKey, listData) + client.setQueryData(votesKey, previousVotes) + client.setQueryData(outsideKey, { userFeedback: [] }) + const vote = observe(client, mutationOptionsFor(c.current)) + + const call = server.hold('voteShowcase') + const pending = vote.mutateAsync({ showcaseId: 'a', value: c.value }) + assert.deepEqual(await call.input, { data: { showcaseId: 'a', value: c.value } }) + assert.equal(scoreOf(client.getQueryData(listQuery.queryKey)), 10 + c.delta, name + ': optimistic score') + assert.deepEqual(client.getQueryData(votesKey).votes, c.votes, name + ': optimistic votes') + + if (outcome === 'resolve') { + call.resolve({ success: true }) + await pending + } else { + call.reject(new Error('vote failed')) + await assert.rejects(pending, /vote failed/) + assert.equal(scoreOf(client.getQueryData(listQuery.queryKey)), 10, name + ': score rolled back') + assert.deepEqual(client.getQueryData(votesKey), previousVotes, name + ': votes rolled back') + } + assert.equal(isInvalidated(client, listQuery.queryKey), true, name + ': showcase query invalidated') + assert.equal(isInvalidated(client, votesKey), true, name + ': votes invalidated') + assert.equal(isInvalidated(client, outsideKey), false, name + ': other queries untouched') + client.clear() + } + } + } + + const showcaseIds = ['a', 'b'] + const list = { showcases: [{ showcase: { id: 'a', voteScore: 10 } }, { showcase: { id: 'b', voteScore: 3 } }] } + const listScore = (data) => data.showcases[0].showcase.voteScore + const toVotesMap = (current) => new Map(current ? [['a', current]] : []) + + async function galleryVote() { + const approvedQuery = showcasesQueries.approved({ pagination: { page: 1, pageSize: 24 }, filters: { placement: 'showcase' } }) + await checkVote({ + label: 'ShowcaseGallery', + listQuery: approvedQuery, + listData: list, + scoreOf: listScore, + votesKey: showcasesQueries.myVotes(showcaseIds).queryKey, + mutationOptionsFor: (current) => showcasesMutations.galleryVote({ approvedQuery, showcaseIds, votesMap: toVotesMap(current) }), + }) + } + + async function sectionVote() { + for (const queryOptions of [showcasesQueries.featured({ limit: 6 }), showcasesQueries.byLibrary({ libraryId: 'query', limit: 6 })]) { + await checkVote({ + label: 'ShowcaseSection ' + queryOptions.queryKey[1], + listQuery: queryOptions, + listData: list, + scoreOf: listScore, + votesKey: showcasesQueries.myVotes(showcaseIds).queryKey, + mutationOptionsFor: (current) => showcasesMutations.sectionVote({ queryOptions, showcaseIds, votesMap: toVotesMap(current) }), + }) + } + } + + async function detailVote() { + await checkVote({ + label: 'ShowcaseDetail', + listQuery: showcasesQueries.detail('a'), + listData: { showcase: { id: 'a', voteScore: 10 } }, + scoreOf: (data) => data.showcase.voteScore, + votesKey: showcasesQueries.myVotes(['a']).queryKey, + mutationOptionsFor: (current) => showcasesMutations.detailVote({ showcaseId: 'a', currentUserVote: current ?? null }), + }) + } + + + // Notes are cached by the docs page (userFeedback) and by /account/notes (feedback). + const pageKey = docFeedbackQueries.page({ pagePath: 'overview', libraryVersion: 'latest' }).queryKey + const userKey = docFeedbackQueries.user({ pagination: { page: 1, pageSize: 20 } }).queryKey + const showcaseKey = showcasesQueries.featured({ limit: 6 }).queryKey + const note = { id: 'n1', type: 'note', content: 'before', isCollapsed: false } + const other = { id: 'n2', type: 'note', content: 'other', isCollapsed: false } + + // update stamps updatedAt with the current time, so it is left out of comparisons. + const withoutUpdatedAt = (notes) => notes.map(({ updatedAt, ...rest }) => rest) + + // Runs one note mutation against both caches and checks every outcome. + async function checkNoteMutation({ label, serverFunction, input, mutationOptionsFor, expectNotes, onSuccessCalls, onErrorCalls }) { + for (const outcome of ['resolve', 'reject']) { + const name = label + ' (' + outcome + ')' + const client = setup() + const page = { userFeedback: [note, other], detachedFeedback: [], isModerator: false } + const user = { feedback: [note, other] } + client.setQueryData(pageKey, page) + client.setQueryData(userKey, user) + client.setQueryData(showcaseKey, { showcases: [] }) + const events = [] + const mutation = observe(client, mutationOptionsFor(events)) + + const call = server.hold(serverFunction) + const pending = mutation.mutateAsync(input) + assert.deepEqual(await call.input, input, name + ': server input') + assert.deepEqual(withoutUpdatedAt(client.getQueryData(pageKey).userFeedback), expectNotes, name + ': optimistic docs page') + assert.deepEqual(withoutUpdatedAt(client.getQueryData(userKey).feedback), expectNotes, name + ': optimistic account notes') + + if (outcome === 'resolve') { + call.resolve({ success: true }) + await pending + assert.deepEqual(events, onSuccessCalls, name + ': success callback') + } else { + call.reject(new Error('save failed')) + await assert.rejects(pending, /save failed/) + assert.deepEqual(client.getQueryData(pageKey), page, name + ': docs page rolled back') + assert.deepEqual(client.getQueryData(userKey), user, name + ': account notes rolled back') + assert.deepEqual(events, onErrorCalls, name + ': error callback') + } + assert.equal(isInvalidated(client, pageKey), true, name + ': docs page invalidated') + assert.equal(isInvalidated(client, userKey), true, name + ': account notes invalidated') + assert.equal(isInvalidated(client, showcaseKey), false, name + ': other queries untouched') + client.clear() + } + } + + async function docFeedbackNote() { + const onError = (events) => (error) => events.push('error: ' + error.message) + await checkNoteMutation({ + label: 'DocFeedbackNote delete', + serverFunction: 'deleteDocFeedback', + input: { data: { feedbackId: 'n1' } }, + mutationOptionsFor: (events) => docFeedbackMutations.delete({ noteId: 'n1', onError: onError(events) }), + expectNotes: [other], + onSuccessCalls: [], + onErrorCalls: ['error: save failed'], + }) + await checkNoteMutation({ + label: 'DocFeedbackNote update', + serverFunction: 'updateDocFeedback', + input: { data: { feedbackId: 'n1', content: 'after' } }, + mutationOptionsFor: (events) => docFeedbackMutations.update({ noteId: 'n1', onSuccess: () => events.push('success'), onError: onError(events) }), + expectNotes: [{ ...note, content: 'after' }, other], + onSuccessCalls: ['success'], + onErrorCalls: ['error: save failed'], + }) + await checkNoteMutation({ + label: 'DocFeedbackNote collapse', + serverFunction: 'updateDocFeedbackCollapsed', + input: { data: { feedbackId: 'n1', isCollapsed: true } }, + mutationOptionsFor: () => docFeedbackMutations.updateCollapsed({ noteId: 'n1' }), + expectNotes: [{ ...note, isCollapsed: true }, other], + onSuccessCalls: [], + onErrorCalls: [], + }) + } + + async function docFeedbackCreate() { + const input = { data: { type: 'note', content: 'new note', pagePath: 'overview', libraryId: 'query', libraryVersion: 'latest', blockSelector: 'p:nth-of-type(1)' } } + for (const outcome of ['resolve', 'reject']) { + const name = 'DocFeedbackProvider create (' + outcome + ')' + const client = setup() + const page = { userFeedback: [other], detachedFeedback: [], isModerator: false } + client.setQueryData(pageKey, page) + client.setQueryData(showcaseKey, { showcases: [] }) + const events = [] + const create = observe(client, docFeedbackMutations.create({ + onSuccess: () => events.push('success'), + onError: (error) => events.push('error: ' + error.message), + })) + + const call = server.hold('createDocFeedback') + const pending = create.mutateAsync(input) + assert.deepEqual(await call.input, input, name + ': server input') + const [optimistic, ...rest] = client.getQueryData(pageKey).userFeedback + assert.match(optimistic.id, /^temp-/, name + ': optimistic note id') + assert.equal(optimistic.content, 'new note', name + ': optimistic note content') + assert.deepEqual(rest, [other], name + ': existing notes kept') + + if (outcome === 'resolve') { + call.resolve({ id: 'n3' }) + await pending + assert.deepEqual(events, ['success'], name + ': success callback') + } else { + call.reject(new Error('save failed')) + await assert.rejects(pending, /save failed/) + assert.deepEqual(client.getQueryData(pageKey), page, name + ': docs page rolled back') + assert.deepEqual(events, ['error: save failed'], name + ': error callback') + } + assert.equal(isInvalidated(client, pageKey), true, name + ': docs page invalidated') + assert.equal(isInvalidated(client, showcaseKey), false, name + ': other queries untouched') + client.clear() + } + } + + async function deleteMyShowcase() { + const mineKey = showcasesQueries.mineList({ pagination: { page: 1, pageSize: 20 } }).queryKey + const approvedKey = showcasesQueries.approved({ pagination: { page: 1, pageSize: 24 } }).queryKey + for (const outcome of ['resolve', 'reject']) { + const name = 'account/submissions delete (' + outcome + ')' + const client = setup() + client.setQueryData(mineKey, { showcases: [] }) + client.setQueryData(approvedKey, { showcases: [] }) + const events = [] + const remove = observe(client, showcasesMutations.delete({ + onSuccess: () => events.push('success'), + onError: (error) => events.push('error: ' + error.message), + })) + + const call = server.hold('deleteShowcase') + const pending = remove.mutateAsync({ data: { showcaseId: 'a' } }) + assert.deepEqual(await call.input, { data: { showcaseId: 'a' } }, name + ': server input') + if (outcome === 'resolve') { + call.resolve({ success: true }) + await pending + assert.deepEqual(events, ['success'], name + ': success callback') + assert.equal(isInvalidated(client, mineKey), true, name + ': my submissions invalidated') + } else { + call.reject(new Error('delete failed')) + await assert.rejects(pending, /delete failed/) + assert.deepEqual(events, ['error: delete failed'], name + ': error callback') + assert.equal(isInvalidated(client, mineKey), false, name + ': nothing invalidated on failure') + } + assert.equal(isInvalidated(client, approvedKey), false, name + ': public showcases untouched') + client.clear() + } + } + + export async function verify() { + await galleryVote() + await sectionVote() + await detailVote() + await docFeedbackNote() + await docFeedbackCreate() + await deleteMyShowcase() + } + `, + }, + bundle: true, + platform: 'node', + format: 'esm', + banner: { + js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);", + }, + write: false, + alias: { '~': join(root, 'src') }, + plugins: [ + { + name: 'server-function-boundary', + setup(builder) { + builder.onResolve( + { + filter: /(showcase|docFeedback)\.functions$|^server-functions$/, + }, + () => ({ path: 'server-functions', namespace: 'fixture' }), + ) + builder.onLoad({ filter: /.*/, namespace: 'fixture' }, () => ({ + contents: ` + const held = new Map() + export const server = { + // Holds the next call of a server function until the test settles it. + hold(name) { + const input = Promise.withResolvers() + const output = Promise.withResolvers() + held.set(name, { input, output }) + return { input: input.promise, resolve: output.resolve, reject: output.reject } + }, + } + function stub(name) { + return (input) => { + const call = held.get(name) + if (!call) throw new Error(name + ' was called without server.hold') + held.delete(name) + call.input.resolve(input) + return call.output.promise + } + } + export const voteShowcase = stub('voteShowcase') + export const adminDeleteShowcase = stub('adminDeleteShowcase') + export const deleteShowcase = stub('deleteShowcase') + export const setShowcaseFeatured = stub('setShowcaseFeatured') + export const getApprovedShowcases = stub('getApprovedShowcases') + export const getFeaturedShowcases = stub('getFeaturedShowcases') + export const getMyShowcases = stub('getMyShowcases') + export const getMyShowcaseVotes = stub('getMyShowcaseVotes') + export const getRelatedShowcases = stub('getRelatedShowcases') + export const getShowcase = stub('getShowcase') + export const getShowcasesByLibrary = stub('getShowcasesByLibrary') + export const listShowcasesForModeration = stub('listShowcasesForModeration') + export const createDocFeedback = stub('createDocFeedback') + export const deleteDocFeedback = stub('deleteDocFeedback') + export const updateDocFeedback = stub('updateDocFeedback') + export const updateDocFeedbackCollapsed = stub('updateDocFeedbackCollapsed') + export const moderateDocFeedback = stub('moderateDocFeedback') + export const getDocFeedbackForPage = stub('getDocFeedbackForPage') + export const getDocFeedbackLeaderboard = stub('getDocFeedbackLeaderboard') + export const getUserDocFeedback = stub('getUserDocFeedback') + export const listDocFeedbackForModeration = stub('listDocFeedbackForModeration') + `, + })) + }, + }, + ], + }) + const file = join(directory, 'fixture.mjs') + await writeFile(file, result.outputFiles[0].text) + const fixture = await import(pathToFileURL(file).href) + await fixture.verify() + } finally { + await rm(directory, { recursive: true, force: true }) + } +}) diff --git a/tests/query-factories.test.ts b/tests/query-factories.test.ts new file mode 100644 index 000000000..238a39ad7 --- /dev/null +++ b/tests/query-factories.test.ts @@ -0,0 +1,148 @@ +import { test } from 'node:test' +import { build } from 'esbuild' +import { mkdtemp, writeFile, rm } from 'node:fs/promises' +import { tmpdir } from 'node:os' +import { join, resolve } from 'node:path' +import { pathToFileURL } from 'node:url' + +// Mutation call sites cancel, roll back, and invalidate by key prefix +// (e.g. `showcasesQueries.all()`), so every query they touch must stay under +// the prefix they pass. Server functions are stubbed so only the factories run. +test('query factories keep keys under the prefixes mutation call sites invalidate', async () => { + const root = resolve(import.meta.dirname, '..') + const directory = await mkdtemp(join(tmpdir(), 'query-factories-')) + try { + const result = await build({ + stdin: { + resolveDir: root, + contents: ` + import assert from 'node:assert/strict' + import { QueryClient } from '@tanstack/react-query' + import { showcasesQueries } from './src/queries/showcases' + import { docFeedbackQueries } from './src/queries/docFeedback' + import { statsQueries } from './src/queries/stats' + + const pagination = { page: 1, pageSize: 20 } + const library = { id: 'query', npmPackageNames: ['@tanstack/query-core'], repo: 'tanstack/query', frameworks: ['react'] } + + function invalidated(prefix, keys) { + const client = new QueryClient() + for (const key of keys) client.setQueryData(key, {}) + client.invalidateQueries({ queryKey: prefix, refetchType: 'none' }) + const states = keys.map((key) => client.getQueryState(key).isInvalidated) + client.clear() + return states + } + + export async function verify() { + const showcaseKeys = { + mineList: showcasesQueries.mineList({ pagination }).queryKey, + approved: showcasesQueries.approved({ pagination }).queryKey, + byLibrary: showcasesQueries.byLibrary({ libraryId: 'query' }).queryKey, + featured: showcasesQueries.featured({}).queryKey, + moderation: showcasesQueries.moderation({ pagination }).queryKey, + detail: showcasesQueries.detail('showcase-1').queryKey, + myVotes: showcasesQueries.myVotes(['showcase-1']).queryKey, + related: showcasesQueries.related({ showcaseId: 'showcase-1', libraries: ['query'] }).queryKey, + } + assert.deepEqual( + invalidated(showcasesQueries.all(), Object.values(showcaseKeys)), + Object.values(showcaseKeys).map(() => true), + 'showcasesQueries.all() must cover every showcase query', + ) + assert.deepEqual( + invalidated(showcasesQueries.mine(), [showcaseKeys.mineList, showcaseKeys.approved]), + [true, false], + 'showcasesQueries.mine() must cover only the signed-in user submissions', + ) + + const feedbackKeys = { + user: docFeedbackQueries.user({ pagination }).queryKey, + moderation: docFeedbackQueries.moderation({ pagination }).queryKey, + leaderboard: docFeedbackQueries.leaderboard({ pagination }).queryKey, + page: docFeedbackQueries.page({ pagePath: 'framework/react/overview', libraryVersion: 'latest' }).queryKey, + } + assert.deepEqual( + invalidated(docFeedbackQueries.all(), Object.values(feedbackKeys)), + Object.values(feedbackKeys).map(() => true), + 'docFeedbackQueries.all() must cover every feedback query', + ) + assert.deepEqual( + invalidated(docFeedbackQueries.moderations(), [feedbackKeys.moderation, feedbackKeys.page]), + [true, false], + 'docFeedbackQueries.moderations() must cover only moderation lists', + ) + + const homepage = statsQueries.homepageNpmSummary().queryKey + assert.deepEqual( + invalidated(statsQueries.oss(), [ + statsQueries.ossSummary().queryKey, + statsQueries.ossSummary({ library }).queryKey, + homepage, + ]), + [true, true, false], + 'statsQueries.oss() must cover every OSS summary', + ) + assert.deepEqual(invalidated(homepage, [homepage]), [true]) + } + `, + }, + bundle: true, + platform: 'node', + format: 'esm', + banner: { + js: "import { createRequire } from 'node:module'; const require = createRequire(import.meta.url);", + }, + write: false, + alias: { '~': join(root, 'src') }, + plugins: [ + { + name: 'server-function-boundary', + setup(builder) { + builder.onResolve( + { + filter: /(showcase|docFeedback|stats-queries)\.functions$/, + }, + () => ({ path: 'server-functions', namespace: 'fixture' }), + ) + builder.onLoad({ filter: /.*/, namespace: 'fixture' }, () => ({ + contents: ` + const unused = async () => { throw new Error('not called in this test') } + export const voteShowcase = unused + export const adminDeleteShowcase = unused + export const deleteShowcase = unused + export const getApprovedShowcases = unused + export const getFeaturedShowcases = unused + export const getMyShowcases = unused + export const getMyShowcaseVotes = unused + export const getRelatedShowcases = unused + export const getShowcase = unused + export const getShowcasesByLibrary = unused + export const listShowcasesForModeration = unused + export const setShowcaseFeatured = unused + export const createDocFeedback = unused + export const deleteDocFeedback = unused + export const getDocFeedbackForPage = unused + export const getDocFeedbackLeaderboard = unused + export const getUserDocFeedback = unused + export const listDocFeedbackForModeration = unused + export const moderateDocFeedback = unused + export const updateDocFeedback = unused + export const updateDocFeedbackCollapsed = unused + export const fetchRecentDownloadStats = unused + export const getHomepageNpmStatsSummary = unused + export const getOSSStats = unused + `, + })) + }, + }, + ], + }) + const file = join(directory, 'fixture.mjs') + await writeFile(file, result.outputFiles[0].text) + const fixture = await import(pathToFileURL(file).href) + await fixture.verify() + } finally { + await rm(directory, { recursive: true, force: true }) + } +})