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

signal-proxy.ts

48 lines1.4 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 *
11 * Functions on the object are passed through as-is.
12 *
13 * @param inputSignal - `Signal` that must return an object.
14 *
15 */
16export function signalProxy<TInput extends Record<string | symbol, any>>(
17 inputSignal: Signal<TInput>,
18) {
19 const internalState = {} as MapToSignals<TInput>
20​
21 return new Proxy<MapToSignals<TInput>>(internalState, {
22 get(target, prop) {
23 // first check if we have it in our internal state and return it
24 const computedField = target[prop]
25 if (computedField) return computedField
26​
27 // then, check if it's a function on the resultState and return it
28 const targetField = untracked(inputSignal)[prop]
29 if (typeof targetField === 'function') return targetField
30​
31 // finally, create a computed field, store it and return it
32 // @ts-ignore
33 return (target[prop] = computed(() => inputSignal()[prop]))
34 },
35 has(_, prop) {
36 return !!untracked(inputSignal)[prop]
37 },
38 ownKeys() {
39 return Reflect.ownKeys(untracked(inputSignal))
40 },
41 getOwnPropertyDescriptor() {
42 return {
43 enumerable: true,
44 configurable: true,
45 }
46 },
47 })