Skip to content

Commit 08cefa6

Browse files
committed
improvement(kb): migrate manual fetches in kb module to use reactquery
1 parent 5f45db4 commit 08cefa6

File tree

6 files changed

+626
-516
lines changed

6 files changed

+626
-516
lines changed

apps/sim/app/workspace/[workspaceId]/knowledge/[id]/[documentId]/components/create-chunk-modal/create-chunk-modal.tsx

Lines changed: 22 additions & 50 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import { useRef, useState } from 'react'
44
import { createLogger } from '@sim/logger'
5-
import { useQueryClient } from '@tanstack/react-query'
65
import {
76
Button,
87
Label,
@@ -14,7 +13,7 @@ import {
1413
Textarea,
1514
} from '@/components/emcn'
1615
import type { DocumentData } from '@/lib/knowledge/types'
17-
import { knowledgeKeys } from '@/hooks/queries/knowledge'
16+
import { useCreateChunk } from '@/hooks/queries/knowledge'
1817

1918
const logger = createLogger('CreateChunkModal')
2019

@@ -31,73 +30,46 @@ export function CreateChunkModal({
3130
document,
3231
knowledgeBaseId,
3332
}: CreateChunkModalProps) {
34-
const queryClient = useQueryClient()
33+
const { mutate: createChunk, isPending: isCreating, error: mutationError } = useCreateChunk()
3534
const [content, setContent] = useState('')
36-
const [isCreating, setIsCreating] = useState(false)
37-
const [error, setError] = useState<string | null>(null)
3835
const [showUnsavedChangesAlert, setShowUnsavedChangesAlert] = useState(false)
3936
const isProcessingRef = useRef(false)
4037

38+
const error = mutationError?.message ?? null
4139
const hasUnsavedChanges = content.trim().length > 0
4240

43-
const handleCreateChunk = async () => {
41+
const handleCreateChunk = () => {
4442
if (!document || content.trim().length === 0 || isProcessingRef.current) {
4543
if (isProcessingRef.current) {
4644
logger.warn('Chunk creation already in progress, ignoring duplicate request')
4745
}
4846
return
4947
}
5048

51-
try {
52-
isProcessingRef.current = true
53-
setIsCreating(true)
54-
setError(null)
55-
56-
const response = await fetch(
57-
`/api/knowledge/${knowledgeBaseId}/documents/${document.id}/chunks`,
58-
{
59-
method: 'POST',
60-
headers: {
61-
'Content-Type': 'application/json',
62-
},
63-
body: JSON.stringify({
64-
content: content.trim(),
65-
enabled: true,
66-
}),
67-
}
68-
)
69-
70-
if (!response.ok) {
71-
const result = await response.json()
72-
throw new Error(result.error || 'Failed to create chunk')
49+
isProcessingRef.current = true
50+
51+
createChunk(
52+
{
53+
knowledgeBaseId,
54+
documentId: document.id,
55+
content: content.trim(),
56+
enabled: true,
57+
},
58+
{
59+
onSuccess: () => {
60+
isProcessingRef.current = false
61+
onClose()
62+
},
63+
onError: () => {
64+
isProcessingRef.current = false
65+
},
7366
}
74-
75-
const result = await response.json()
76-
77-
if (result.success && result.data) {
78-
logger.info('Chunk created successfully:', result.data.id)
79-
80-
await queryClient.invalidateQueries({
81-
queryKey: knowledgeKeys.detail(knowledgeBaseId),
82-
})
83-
84-
onClose()
85-
} else {
86-
throw new Error(result.error || 'Failed to create chunk')
87-
}
88-
} catch (err) {
89-
logger.error('Error creating chunk:', err)
90-
setError(err instanceof Error ? err.message : 'An error occurred')
91-
} finally {
92-
isProcessingRef.current = false
93-
setIsCreating(false)
94-
}
67+
)
9568
}
9669

9770
const onClose = () => {
9871
onOpenChange(false)
9972
setContent('')
100-
setError(null)
10173
setShowUnsavedChangesAlert(false)
10274
}
10375

apps/sim/app/workspace/[workspaceId]/knowledge/[id]/[documentId]/components/delete-chunk-modal/delete-chunk-modal.tsx

Lines changed: 4 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -1,13 +1,8 @@
11
'use client'
22

3-
import { useState } from 'react'
4-
import { createLogger } from '@sim/logger'
5-
import { useQueryClient } from '@tanstack/react-query'
63
import { Button, Modal, ModalBody, ModalContent, ModalFooter, ModalHeader } from '@/components/emcn'
74
import type { ChunkData } from '@/lib/knowledge/types'
8-
import { knowledgeKeys } from '@/hooks/queries/knowledge'
9-
10-
const logger = createLogger('DeleteChunkModal')
5+
import { useDeleteChunk } from '@/hooks/queries/knowledge'
116

127
interface DeleteChunkModalProps {
138
chunk: ChunkData | null
@@ -24,44 +19,12 @@ export function DeleteChunkModal({
2419
isOpen,
2520
onClose,
2621
}: DeleteChunkModalProps) {
27-
const queryClient = useQueryClient()
28-
const [isDeleting, setIsDeleting] = useState(false)
22+
const { mutate: deleteChunk, isPending: isDeleting } = useDeleteChunk()
2923

30-
const handleDeleteChunk = async () => {
24+
const handleDeleteChunk = () => {
3125
if (!chunk || isDeleting) return
3226

33-
try {
34-
setIsDeleting(true)
35-
36-
const response = await fetch(
37-
`/api/knowledge/${knowledgeBaseId}/documents/${documentId}/chunks/${chunk.id}`,
38-
{
39-
method: 'DELETE',
40-
}
41-
)
42-
43-
if (!response.ok) {
44-
throw new Error('Failed to delete chunk')
45-
}
46-
47-
const result = await response.json()
48-
49-
if (result.success) {
50-
logger.info('Chunk deleted successfully:', chunk.id)
51-
52-
await queryClient.invalidateQueries({
53-
queryKey: knowledgeKeys.detail(knowledgeBaseId),
54-
})
55-
56-
onClose()
57-
} else {
58-
throw new Error(result.error || 'Failed to delete chunk')
59-
}
60-
} catch (err) {
61-
logger.error('Error deleting chunk:', err)
62-
} finally {
63-
setIsDeleting(false)
64-
}
27+
deleteChunk({ knowledgeBaseId, documentId, chunkId: chunk.id }, { onSuccess: onClose })
6528
}
6629

6730
if (!chunk) return null

apps/sim/app/workspace/[workspaceId]/knowledge/[id]/[documentId]/components/edit-chunk-modal/edit-chunk-modal.tsx

Lines changed: 11 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,6 @@
22

33
import { useEffect, useMemo, useRef, useState } from 'react'
44
import { createLogger } from '@sim/logger'
5-
import { useQueryClient } from '@tanstack/react-query'
65
import { ChevronDown, ChevronUp } from 'lucide-react'
76
import {
87
Button,
@@ -19,7 +18,7 @@ import {
1918
import type { ChunkData, DocumentData } from '@/lib/knowledge/types'
2019
import { getAccurateTokenCount, getTokenStrings } from '@/lib/tokenization/estimators'
2120
import { useUserPermissionsContext } from '@/app/workspace/[workspaceId]/providers/workspace-permissions-provider'
22-
import { knowledgeKeys } from '@/hooks/queries/knowledge'
21+
import { useUpdateChunk } from '@/hooks/queries/knowledge'
2322

2423
const logger = createLogger('EditChunkModal')
2524

@@ -50,17 +49,17 @@ export function EditChunkModal({
5049
onNavigateToPage,
5150
maxChunkSize,
5251
}: EditChunkModalProps) {
53-
const queryClient = useQueryClient()
5452
const userPermissions = useUserPermissionsContext()
53+
const { mutate: updateChunk, isPending: isSaving, error: mutationError } = useUpdateChunk()
5554
const [editedContent, setEditedContent] = useState(chunk?.content || '')
56-
const [isSaving, setIsSaving] = useState(false)
5755
const [isNavigating, setIsNavigating] = useState(false)
58-
const [error, setError] = useState<string | null>(null)
5956
const [showUnsavedChangesAlert, setShowUnsavedChangesAlert] = useState(false)
6057
const [pendingNavigation, setPendingNavigation] = useState<(() => void) | null>(null)
6158
const [tokenizerOn, setTokenizerOn] = useState(false)
6259
const textareaRef = useRef<HTMLTextAreaElement>(null)
6360

61+
const error = mutationError?.message ?? null
62+
6463
const hasUnsavedChanges = editedContent !== (chunk?.content || '')
6564

6665
const tokenStrings = useMemo(() => {
@@ -102,44 +101,15 @@ export function EditChunkModal({
102101
const canNavigatePrev = currentChunkIndex > 0 || currentPage > 1
103102
const canNavigateNext = currentChunkIndex < allChunks.length - 1 || currentPage < totalPages
104103

105-
const handleSaveContent = async () => {
104+
const handleSaveContent = () => {
106105
if (!chunk || !document) return
107106

108-
try {
109-
setIsSaving(true)
110-
setError(null)
111-
112-
const response = await fetch(
113-
`/api/knowledge/${knowledgeBaseId}/documents/${document.id}/chunks/${chunk.id}`,
114-
{
115-
method: 'PUT',
116-
headers: {
117-
'Content-Type': 'application/json',
118-
},
119-
body: JSON.stringify({
120-
content: editedContent,
121-
}),
122-
}
123-
)
124-
125-
if (!response.ok) {
126-
const result = await response.json()
127-
throw new Error(result.error || 'Failed to update chunk')
128-
}
129-
130-
const result = await response.json()
131-
132-
if (result.success) {
133-
await queryClient.invalidateQueries({
134-
queryKey: knowledgeKeys.detail(knowledgeBaseId),
135-
})
136-
}
137-
} catch (err) {
138-
logger.error('Error updating chunk:', err)
139-
setError(err instanceof Error ? err.message : 'An error occurred')
140-
} finally {
141-
setIsSaving(false)
142-
}
107+
updateChunk({
108+
knowledgeBaseId,
109+
documentId: document.id,
110+
chunkId: chunk.id,
111+
content: editedContent,
112+
})
143113
}
144114

145115
const navigateToChunk = async (direction: 'prev' | 'next') => {
@@ -165,7 +135,6 @@ export function EditChunkModal({
165135
}
166136
} catch (err) {
167137
logger.error(`Error navigating ${direction}:`, err)
168-
setError(`Failed to navigate to ${direction === 'prev' ? 'previous' : 'next'} chunk`)
169138
} finally {
170139
setIsNavigating(false)
171140
}

0 commit comments

Comments
 (0)