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

signal-proxy.ts

46 lines1.5 KB

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