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

signal-proxy.ts

61 lines2.2 KB

1import { computed, untracked } from '@angular/core'
2import type { Signal } from '@angular/core'
3​
4export type MethodKeys<T> = {
5 [K in keyof T]: T[K] extends (...args: Array<any>) => any ? K : never
6}[keyof T]
7​
8export type MapToSignals<T, TExcludeFields extends MethodKeys<T> = never> = {
9 [K in keyof T]: K extends TExcludeFields ? T[K] : Signal<T[K]>
11​
12/**
13 * Exposes fields of an object passed via an Angular `Signal` as `Computed` signals.
14 * Functions on the object are passed through as-is.
15 * @param inputSignal - `Signal` that must return an object.
16 * @param excludeFields - Array of function property names that should NOT be converted to signals.
17 * @returns A proxy object with the same fields as the input object, but with each field wrapped in a `Computed` signal.
18 */
19export function signalProxy<
20 TInput extends Record<string | symbol, any>,
21 const TExcludeFields extends ReadonlyArray<MethodKeys<TInput>> = [],
22>(inputSignal: Signal<TInput>, excludeFields: TExcludeFields) {
23 const internalState = {} as MapToSignals<TInput, TExcludeFields[number]>
24 const excludeFieldsArray = excludeFields as ReadonlyArray<string>
25​
26 return new Proxy<MapToSignals<TInput, TExcludeFields[number]>>(
27 internalState,
28 {
29 get(target, prop) {
30 // first check if we have it in our internal state and return it
31 const computedField = target[prop]
32 if (computedField) return computedField
33​
34 // if it is an excluded function, return it without tracking
35 if (excludeFieldsArray.includes(prop as string)) {
36 const fn = (...args: Parameters<TInput[typeof prop]>) =>
37 untracked(inputSignal)[prop](...args)
38 // @ts-expect-error
39 target[prop] = fn
40 return fn
41 }
42​
43 // otherwise, make a computed field
44 // @ts-expect-error
45 return (target[prop] = computed(() => inputSignal()[prop]))
46 },
47 has(_, prop) {
48 return !!untracked(inputSignal)[prop]
49 },
50 ownKeys() {
51 return Reflect.ownKeys(untracked(inputSignal))
52 },
53 getOwnPropertyDescriptor() {
54 return {
55 enumerable: true,
56 configurable: true,
57 }
58 },
59 },
60 )