Skip to content

Commit c024d0a

Browse files
fix(fetchium): resolve TopicQuery adapter via subclass-aware lookup (#13)
* fix(fetchium): resolve TopicQuery adapter via subclass-aware lookup TopicQuery declared `static adapter` as a type-only annotation with no runtime value, so subclasses had to set it explicitly. That breaks two patterns: 1. Generated TopicQuery classes that don't know which concrete adapter a consumer will use — they can only target the abstract base. 2. Hand-authored subclasses had to write `static adapter = MyAdapter as unknown as typeof TopicQueryAdapter` to satisfy the override. This change makes TopicQuery assign `static adapter = TopicQueryAdapter` (mirroring the RESTQuery pattern) and teaches `QueryClient.getAdapter()` to fall back to a subclass `instanceof` scan before auto-instantiating. Why both changes are needed: RESTQueryAdapter is concrete, so the registered instance's `.constructor` equals the static-adapter key on the query and exact-match lookup hits. TopicQueryAdapter is abstract, so consumers must register a subclass — the registered constructor is the subclass, not the base, and exact-match misses. The new instanceof fallback also makes the REST path correct in the (previously undefined) case where a consumer registers a subclass of RESTQueryAdapter. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * test(fetchium): clarify how the generated-TopicQuery test resolves its adapter The new test in `topic-query.test.ts` relies on the outer `beforeEach` (~1800 lines above) registering a `MockTopicQueryAdapter` instance on the QueryClient. Without that context the test reads as magic. Replace the comment with one that names the inheritance + instanceof-scan path explicitly and points at the outer registration. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(fetchium): add changeset for TopicQuery adapter resolution Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(streaming): update TopicQuery examples to drop unneeded adapter overrides After the subclass-aware adapter resolution change, individual TopicQuery subclasses no longer need to declare `static override adapter` for the common case of one registered streaming adapter. Update the streaming page so: - Inline examples extend `TopicQuery` directly instead of an intermediate `MyTopicQuery` base. - The "Registering the adapter" section explains that the resolution happens via inheritance + the QueryClient's instanceof lookup, with an opt-in note for disambiguating between multiple registered subclasses. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(streaming): drop clunky em-dashed phrasing in adapter resolution note Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(streaming): trim hypothetical multi-adapter disambiguation guidance In practice, apps register one streaming adapter per QueryClient — the multi-adapter override pattern was over-engineering. Replace with a one-liner pointing at "use a separate QueryClient" if you ever hit the case. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(streaming): drop the dangling separate-QueryClient hint The only justification for "use a separate QueryClient" is the adapter resolution ambiguity case we already trimmed as hypothetical. Without that reasoning, the sentence dangles. Remove it; the common-case explanation stands on its own. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * feat(fetchium): throw in dev when adapter lookup is ambiguous `QueryClient.getAdapter()`'s subclass-aware lookup picks the first `instanceof` match in registration order. If a consumer registers two adapters that both satisfy the same lookup base (e.g. two `TopicQueryAdapter` subclasses on one client), the resolution is silent and brittle. In dev builds, scan all registered adapters and throw on more than one match, naming the conflicting classes. In production, keep the original fast path: first match wins, exit early. The dev-only branch is gated behind `if (IS_DEV)` so it tree-shakes out of production bundles. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(fetchium): trim changeset to user-visible behavior Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * refactor(fetchium): simplify getAdapter loop and trim TopicQuery comment - `getAdapter()`: collapse the four-case branch in the instanceof scan to a single dev-mode ambiguity check plus `match ??= registered` for first-match-wins. Also drop a now-redundant inline comment on the auto-instantiate fallback (the JSDoc enumerates step 3 and the catch's error message covers the failure mode). - `TopicQuery.ts`: trim the five-line comment on `static override adapter` to a single-line note about why the explicit type annotation is load-bearing. No behavior change. All topic-query tests still pass. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(streaming): add callout warning about multi-adapter registration Captures the "one TopicQueryAdapter subclass per QueryClient" design intent and pre-warns about the dev-mode ambiguity error so users structure their setup correctly the first time. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * docs(streaming): trim multi-adapter callout to the load-bearing facts Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> * chore(fetchium): apply prettier formatting Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com> --------- Co-authored-by: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
1 parent ee291d6 commit c024d0a

5 files changed

Lines changed: 130 additions & 27 deletions

File tree

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
"fetchium": patch
3+
---
4+
5+
`TopicQuery` subclasses now inherit their adapter from the base, and `QueryClient.getAdapter()` resolves an abstract adapter class on a query to a consumer-registered concrete subclass. Generated and hand-authored `TopicQuery` classes no longer need a per-class `static adapter` override. In dev, ambiguous registrations (more than one adapter that matches the same lookup) throw with a clear error.

‎docs/src/app/core/streaming/page.md‎

Lines changed: 7 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -139,7 +139,7 @@ A topic query extends `TopicQuery` and provides a `topic` field and a `result` s
139139
import { t } from 'fetchium';
140140
import { TopicQuery } from 'fetchium/topic';
141141

142-
class GetPrices extends MyTopicQuery {
142+
class GetPrices extends TopicQuery {
143143
topic = 'prices:live';
144144

145145
result = {
@@ -151,7 +151,7 @@ class GetPrices extends MyTopicQuery {
151151
Topics can be parameterized using `this.params`, just like paths in `RESTQuery`:
152152

153153
```tsx
154-
class GetBalances extends MyTopicQuery {
154+
class GetBalances extends TopicQuery {
155155
params = { walletId: t.string };
156156

157157
topic = `balances:${this.params.walletId}`;
@@ -231,13 +231,11 @@ const queryClient = new QueryClient({
231231
});
232232
```
233233

234-
Then make your topic query classes reference the adapter:
234+
Topic query classes that extend `TopicQuery` directly resolve to the registered `MyStreamAdapter` automatically. Internally, `TopicQuery` declares `static adapter = TopicQueryAdapter` (the abstract base), and `QueryClient` looks up registered adapters by `instanceof` match, so any subclass of `TopicQueryAdapter` you register fulfills the lookup.
235235

236-
```tsx
237-
abstract class MyTopicQuery extends TopicQuery {
238-
static override adapter = MyStreamAdapter;
239-
}
240-
```
236+
{% callout title="One streaming adapter per QueryClient" %}
237+
Register at most one `TopicQueryAdapter` subclass on a given `QueryClient`. If your app needs multiple streaming protocols, create a separate `QueryClient` for each. Dev builds throw if more than one registered adapter satisfies the same lookup.
238+
{% /callout %}
241239

242240
### Pre-fulfillment
243241

@@ -515,7 +513,7 @@ In practice, most applications combine multiple real-time strategies:
515513

516514
```tsx
517515
// Topic-based streaming for live market data
518-
class GetPrices extends MyTopicQuery {
516+
class GetPrices extends TopicQuery {
519517
topic = 'prices:live';
520518
result = { prices: t.liveArray(Price) };
521519
}

‎packages/fetchium/src/QueryClient.ts‎

Lines changed: 46 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -124,26 +124,56 @@ export class QueryClient {
124124

125125
/**
126126
* Returns the registered adapter instance for the given adapter class.
127-
* Throws if no adapter of that class has been registered.
127+
*
128+
* Resolution order:
129+
* 1. Exact class match in the registered adapters.
130+
* 2. Subclass match — if any registered adapter is an `instanceof adapterClass`,
131+
* return it. This lets queries declare an abstract base adapter (e.g.
132+
* `TopicQueryAdapter`) and have the consumer-supplied concrete subclass
133+
* (e.g. a `WebSocket`-backed adapter) resolve to it.
134+
* 3. Auto-instantiate via the no-arg constructor (for adapters like
135+
* `RESTQueryAdapter` that default to `globalThis.fetch`).
136+
*
137+
* In dev builds, step 2 verifies that at most one registered adapter
138+
* matches the lookup and throws otherwise. The dev-only check is stripped
139+
* from production builds.
140+
*
141+
* Throws if none of those succeed.
128142
*/
129143
getAdapter(adapterClass: QueryAdapterClass): QueryAdapter {
130-
let adapter = this.adapters.get(adapterClass);
131-
if (!adapter) {
132-
// Auto-instantiate with no-arg constructor as fallback.
133-
// Works for adapters like RESTQueryAdapter that default to globalThis.fetch.
134-
// Adapters that require explicit configuration will throw here, prompting
135-
// the user to register an instance explicitly.
136-
try {
137-
adapter = new (adapterClass as new () => QueryAdapter)();
138-
} catch {
139-
throw new Error(
140-
`No adapter registered for ${adapterClass.name} and auto-instantiation failed. ` +
141-
`Pass an instance via QueryClient config: new QueryClient({ store, adapters: [new ${adapterClass.name}(...)] })`,
142-
);
144+
const exact = this.adapters.get(adapterClass);
145+
if (exact) return exact;
146+
147+
let match: QueryAdapter | undefined;
148+
for (const registered of this.adapters.values()) {
149+
if (registered instanceof adapterClass) {
150+
if (IS_DEV && match !== undefined) {
151+
throw new Error(
152+
`Adapter lookup for ${adapterClass.name} matches multiple registered adapters: ` +
153+
`${match.constructor.name} and ${registered.constructor.name}. ` +
154+
`Register only one adapter per lookup base on a single QueryClient, ` +
155+
`or split into separate QueryClients.`,
156+
);
157+
}
158+
match ??= registered;
143159
}
144-
this.adapters.set(adapterClass, adapter);
145-
adapter.register(this);
146160
}
161+
if (match !== undefined) {
162+
this.adapters.set(adapterClass, match);
163+
return match;
164+
}
165+
166+
let adapter: QueryAdapter;
167+
try {
168+
adapter = new (adapterClass as new () => QueryAdapter)();
169+
} catch {
170+
throw new Error(
171+
`No adapter registered for ${adapterClass.name} and auto-instantiation failed. ` +
172+
`Pass an instance via QueryClient config: new QueryClient({ store, adapters: [new ${adapterClass.name}(...)] })`,
173+
);
174+
}
175+
this.adapters.set(adapterClass, adapter);
176+
adapter.register(this);
147177
return adapter;
148178
}
149179

‎packages/fetchium/src/__tests__/topic-query.test.ts‎

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2071,4 +2071,73 @@ describe('TopicQuery', () => {
20712071
});
20722072
});
20732073
});
2074+
2075+
// ============================================================
2076+
// Section 6: Generated TopicQuery (no static adapter override)
2077+
// ============================================================
2078+
2079+
describe('Generated TopicQuery without static adapter override', () => {
2080+
it('should resolve via subclass-aware adapter lookup when subclass inherits TopicQueryAdapter from base', async () => {
2081+
// GetPricesGenerated extends TopicQuery directly and does NOT set
2082+
// `static adapter`, so it inherits `adapter = TopicQueryAdapter` (the
2083+
// abstract base) from TopicQuery. The outer beforeEach above registers
2084+
// a MockTopicQueryAdapter instance on the QueryClient — which extends
2085+
// TopicQueryAdapter — and QueryClient.getAdapter() resolves the lookup
2086+
// for TopicQueryAdapter to that instance via its `instanceof` scan.
2087+
class GetPricesGenerated extends TopicQuery {
2088+
topic = 'prices:generated';
2089+
result = {
2090+
items: t.array(t.entity(TopicPrice)),
2091+
};
2092+
}
2093+
2094+
mockStream.pushTopicData('prices:generated', {
2095+
items: [{ __typename: 'TopicPrice', id: '1', token: 'BTC', value: 50000, change24h: 2.5 }],
2096+
});
2097+
2098+
await testWithClient(client, async () => {
2099+
const relay = fetchQuery(GetPricesGenerated);
2100+
await relay;
2101+
2102+
expect(relay.isResolved).toBe(true);
2103+
expect(relay.value!.items).toHaveLength(1);
2104+
expect(relay.value!.items[0].token).toBe('BTC');
2105+
});
2106+
});
2107+
2108+
it('should expose TopicQueryAdapter as the inherited static adapter on the base class', () => {
2109+
expect(TopicQuery.adapter).toBe(TopicQueryAdapter);
2110+
2111+
class GetPricesGenerated extends TopicQuery {
2112+
topic = 'prices:generated';
2113+
result = {
2114+
items: t.array(t.entity(TopicPrice)),
2115+
};
2116+
}
2117+
2118+
expect(GetPricesGenerated.adapter).toBe(TopicQueryAdapter);
2119+
});
2120+
2121+
it('should throw in dev when multiple registered adapters match the same lookup', () => {
2122+
// Two distinct TopicQueryAdapter subclasses registered on one QueryClient
2123+
// creates an ambiguous lookup for `getAdapter(TopicQueryAdapter)` — the
2124+
// instanceof scan would pick whichever was registered first. The dev-mode
2125+
// check catches this misconfiguration up front.
2126+
class SecondTopicAdapter extends TopicQueryAdapter {
2127+
subscribe(_topic: string): void {}
2128+
unsubscribe(_topic: string): void {}
2129+
}
2130+
2131+
const ambiguousClient = new QueryClient({
2132+
store: new SyncQueryStore(new MemoryPersistentStore()),
2133+
adapters: [new MockTopicQueryAdapter(mockStream, mockFetch as any), new SecondTopicAdapter()],
2134+
} as any);
2135+
2136+
try {
2137+
expect(() => ambiguousClient.getAdapter(TopicQueryAdapter)).toThrow(/matches multiple registered adapters/);
2138+
} finally {
2139+
ambiguousClient.destroy();
2140+
}
2141+
});
2142+
});
20742143
});

‎packages/fetchium/src/topic/TopicQuery.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { Query } from '../query.js';
2-
import type { TopicQueryAdapter } from './TopicQueryAdapter.js';
2+
import { TopicQueryAdapter } from './TopicQueryAdapter.js';
33
import type { QueryAdapterClass } from '../QueryAdapter.js';
44
import type { QueryConfigOptions } from '../query-types.js';
55

@@ -8,7 +8,8 @@ import type { QueryConfigOptions } from '../query-types.js';
88
// ================================
99

1010
export abstract class TopicQuery extends Query {
11-
static override adapter: QueryAdapterClass<TopicQueryAdapter>;
11+
// Explicit type lets subclasses override with adapters that take constructor args.
12+
static override adapter: QueryAdapterClass<TopicQueryAdapter> = TopicQueryAdapter;
1213

1314
abstract topic: string;
1415

0 commit comments

Comments
 (0)