Open History to see the last commit
1import { type Signal, computed, untracked } from '@angular/core'
2import type { DefaultError, QueryObserverResult } from '@tanstack/query-core'
3import type { CreateBaseQueryResult } from './types'
4β
5export function createResultStateSignalProxy<
6 TData = unknown,
7 TError = DefaultError,
8 State = QueryObserverResult<TData, TError>,
9>(resultState: Signal<State>) {
10 const internalState = {} as CreateBaseQueryResult<TData, TError, State>
11β
12 return new Proxy(internalState, {
13 get<Key extends keyof State>(
14 target: CreateBaseQueryResult<TData, TError, State>,
15 prop: Key | string | symbol,
16 ) {
17 // first check if we have it in our internal state and return it
18 const computedField = target[prop as Key]
19β
20 // TODO: check if this if statement is necessary
21 // eslint-disable-next-line @typescript-eslint/no-unnecessary-condition
22 if (computedField) return computedField
23β
24 // then, check if it's a function on the resultState and return it
25 const targetField = untracked(resultState)[prop as Key]
26 if (typeof targetField === 'function') return targetField
27β
28 // finally, create a computed field, store it and return it
29 // @ts-ignore
30 return (target[prop] = computed(() => resultState()[prop as Key]))
31 },
32 has<K extends keyof State>(
33 target: CreateBaseQueryResult<TData, TError, State>,
34 prop: K | string | symbol,
35 ) {
36 return !!target[prop as K]
37 },
38 ownKeys(target) {
39 return [...Reflect.ownKeys(target)]
40 },
41 getOwnPropertyDescriptor() {
42 return {
43 enumerable: true,
44 configurable: true,
45 }
46 },
47 set(): boolean {
48 return true
49 },
50 })
51}