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

signal-proxy.ts

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