Line data Source code
1 : import { z } from 'zod'
2 : import { fromZodError } from 'zod-validation-error'
3 :
4 : import { useComfyRegistryStore } from '@/stores/comfyRegistryStore'
5 : import type { SearchNodePacksParams } from '@/types/algoliaTypes'
6 : import type { components } from '@/types/comfyRegistryTypes'
7 : import type {
8 : NodePackSearchProvider,
9 : SearchPacksOutcome
10 : } from '@/types/searchServiceTypes'
11 :
12 : type RegistryNodePack = components['schemas']['Node']
13 :
14 2355 : const zRegistrySearchResult = z.looseObject({
15 : nodes: z.array(
16 : z.custom<RegistryNodePack>(
17 : (node) => typeof node === 'object' && node !== null,
18 : { message: 'expected a node pack object' }
19 : )
20 : )
21 : })
22 :
23 : interface CachedRegistryRequest<TParams, TResult> {
24 : call: (params: TParams) => Promise<TResult | null>
25 : evict: (params: TParams) => void
26 : }
27 :
28 2355 : export const useComfyRegistrySearchProvider = (): NodePackSearchProvider => {
29 15 : const registryStore = useComfyRegistryStore()
30 :
31 15 : const requestFailure = (): Error => {
32 1 : const cause = registryStore.error
33 1 : return new Error(
34 : cause
35 : ? `Comfy Registry request failed: ${cause}`
36 : : 'Comfy Registry request failed'
37 : )
38 : }
39 :
40 15 : const requestPage = async <TParams, TResult>(
41 : request: CachedRegistryRequest<TParams, TResult>,
42 : params: TParams
43 : ): Promise<SearchPacksOutcome> => {
44 20 : const response = await request.call(params)
45 20 : if (!response) {
46 1 : request.evict(params)
47 1 : return { ok: false, cause: requestFailure() }
48 : }
49 19 : const parsed = zRegistrySearchResult.safeParse(response)
50 20 : if (!parsed.success) {
51 0 : request.evict(params)
52 0 : return {
53 : ok: false,
54 : cause: fromZodError(parsed.error, {
55 : prefix: 'Malformed registry search response'
56 : })
57 : }
58 : }
59 19 : return {
60 : ok: true,
61 : result: { nodePacks: parsed.data.nodes, querySuggestions: [] }
62 : }
63 : }
64 :
65 15 : const searchPacks = async (
66 : query: string,
67 : params: SearchNodePacksParams
68 : ): Promise<SearchPacksOutcome> => {
69 20 : const { pageSize, pageNumber, restrictSearchableAttributes } = params
70 20 : const registryPage = pageNumber + 1
71 :
72 20 : if (!query || query.trim() === '') {
73 18 : return requestPage(registryStore.listAllPacks, {
74 : limit: pageSize,
75 : page: registryPage
76 : })
77 : }
78 :
79 20 : const isNodeSearch = restrictSearchableAttributes?.includes('comfy_nodes')
80 :
81 20 : return requestPage(registryStore.search, {
82 : search: isNodeSearch ? undefined : query,
83 : comfy_node_search: isNodeSearch ? query : undefined,
84 : limit: pageSize,
85 : page: registryPage
86 : })
87 : }
88 :
89 15 : const clearSearchCache = () => {
90 0 : registryStore.search.clear()
91 0 : registryStore.listAllPacks.clear()
92 : }
93 :
94 15 : return {
95 : searchPacks,
96 : clearSearchCache
97 : }
98 : }
|