Skip to content
Source
Sign inSign up
TanStack/query
Open History to see the last commit

signal-proxy.ts

49 lines1.6 KB

1import { computed, untracked } from '@angular/core'
2import type { Signal } from '@angular/core'
3​
4/**
5 * Maps each field of `T` to a `Signal` of its value. Functions are kept as they are.
6 */
7export type MapToSignals<T> = {
8 [K in keyof T]: T[K] extends Function ? T[K] : Signal<T[K]>
9}
10​
11/**
12 * Exposes fields of an object passed via an Angular `Signal` as `Computed` signals.
13 * Functions on the object are passed through as-is.
14 * @param inputSignal - `Signal` that must return an object.
15 * @returns A proxy object with the same fields as the input object, but with each field wrapped in a `Computed` signal.
16 */
17export function signalProxy<TInput extends Record<string | symbol, any>>(
18 inputSignal: Signal<TInput>,
19) {
20 const internalState = {} as MapToSignals<TInput>
21​
22 return new Proxy<MapToSignals<TInput>>(internalState, {
23 get(target, prop) {
24 // first check if we have it in our internal state and return it
25 const computedField = target[prop]
26 if (computedField) return computedField
27​
28 // then, check if it's a function on the resultState and return it
29 const targetField = untracked(inputSignal)[prop]
30 if (typeof targetField === 'function') return targetField
31​
32 // finally, create a computed field, store it and return it
33 // @ts-expect-error
34 return (target[prop] = computed(() => inputSignal()[prop]))
35 },
36 has(_, prop) {
37 return !!untracked(inputSignal)[prop]
38 },
39 ownKeys() {
40 return Reflect.ownKeys(untracked(inputSignal))
41 },
42 getOwnPropertyDescriptor() {
43 return {
44 enumerable: true,
45 configurable: true,
46 }
47 },
48 })