Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions .changeset/topic-query-get-topic.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'fetchium': patch
---

Add `getTopic()` to `TopicQuery` for parity with `getPath()` on `RESTQuery`. The static `topic` template only supports fixed-shape topics, so consumers with variable-segment-count or conditionally-shaped topics had to hand-author one query class per shape. Subclasses can now override `getTopic()` to compute the topic dynamically at execution time over the resolved params (e.g. `'layout:' + this.params.segments.map(encodeURIComponent).join(':')`); when defined it takes precedence over the `topic` field. The `topic` field is now optional, matching `path?` on `RESTQuery`. Existing queries that define `topic` as a static template continue to work unchanged.
93 changes: 91 additions & 2 deletions packages/fetchium/src/__tests__/topic-query.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,9 @@ class MockTopicQueryAdapter extends TopicQueryAdapter {

override hasNext(ctx: Query): boolean {
const topicCtx = ctx as TopicQuery;
const meta = this._topicMeta.get(topicCtx.topic);
const topic = topicCtx.getTopic ? topicCtx.getTopic() : topicCtx.topic;
if (topic === undefined) return false;
const meta = this._topicMeta.get(topic);
if (!meta?.fetchNextUrl) return false;

const resolved = this.resolveFetchNext(topicCtx);
Expand All @@ -161,7 +163,11 @@ class MockTopicQueryAdapter extends TopicQueryAdapter {

override async sendNext(ctx: Query, signal: AbortSignal): Promise<unknown> {
const topicCtx = ctx as TopicQuery;
const meta = this._topicMeta.get(topicCtx.topic);
const topic = topicCtx.getTopic ? topicCtx.getTopic() : topicCtx.topic;
if (topic === undefined) {
throw new Error('TopicQuery requires a topic for sendNext');
}
const meta = this._topicMeta.get(topic);

if (!meta?.fetchNextUrl) {
throw new Error('No fetchNextUrl available for topic');
Expand Down Expand Up @@ -2140,4 +2146,87 @@ describe('TopicQuery', () => {
}
});
});

// ============================================================
// Section 7: Dynamic topics via getTopic()
// ============================================================

describe('getTopic() override', () => {
it('should resolve the topic via getTopic() when defined', async () => {
class GetLayout extends MockTopicQuery {
params = { segments: t.array(t.string) };
result = { items: t.array(t.entity(TopicPrice)) };

getTopic() {
return 'layout:' + (this.params.segments as string[]).map(encodeURIComponent).join(':');
}
}

mockStream.pushTopicData('layout:a:b:c', {
items: [{ __typename: 'TopicPrice', id: '1', token: 'BTC', value: 50000, change24h: 2.5 }],
});

await testWithClient(client, async () => {
const relay = fetchQuery(GetLayout, { segments: ['a', 'b', 'c'] });
await relay;

expect(relay.isResolved).toBe(true);
expect(relay.value!.items).toHaveLength(1);
expect(relay.value!.items[0].token).toBe('BTC');
});
});

it('should support variable-segment-count topics with one query class', async () => {
class GetLayout extends MockTopicQuery {
params = { segments: t.array(t.string) };
result = { items: t.array(t.entity(TopicPrice)) };

getTopic() {
return 'layout:' + (this.params.segments as string[]).map(encodeURIComponent).join(':');
}
}

mockStream.pushTopicData('layout:a:b', {
items: [{ __typename: 'TopicPrice', id: '1', token: 'BTC', value: 50000, change24h: 2.5 }],
});
mockStream.pushTopicData('layout:a:b:c:d', {
items: [{ __typename: 'TopicPrice', id: '2', token: 'ETH', value: 3000, change24h: -1.2 }],
});

await testWithClient(client, async () => {
const shortRelay = fetchQuery(GetLayout, { segments: ['a', 'b'] });
const longRelay = fetchQuery(GetLayout, { segments: ['a', 'b', 'c', 'd'] });

await shortRelay;
await longRelay;

expect(shortRelay.value!.items[0].token).toBe('BTC');
expect(longRelay.value!.items[0].token).toBe('ETH');
});
});

it('should take precedence over a static topic field when both are defined', async () => {
class GetLayout extends MockTopicQuery {
params = { id: t.string };
topic = 'fallback:topic';
result = { items: t.array(t.entity(TopicPrice)) };

getTopic() {
return `dynamic:${this.params.id}`;
}
}

mockStream.pushTopicData('dynamic:abc', {
items: [{ __typename: 'TopicPrice', id: '1', token: 'BTC', value: 50000, change24h: 2.5 }],
});

await testWithClient(client, async () => {
const relay = fetchQuery(GetLayout, { id: 'abc' });
await relay;

expect(relay.isResolved).toBe(true);
expect(relay.value!.items[0].token).toBe('BTC');
});
});
});
});
12 changes: 9 additions & 3 deletions packages/fetchium/src/topic/TopicQuery.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,10 +11,13 @@ export abstract class TopicQuery extends Query {
// Explicit type lets subclasses override with adapters that take constructor args.
static override adapter: QueryAdapterClass<TopicQueryAdapter> = TopicQueryAdapter;

abstract topic: string;
topic?: string;

// User-overridable getter — the adapter reads this from the execution context.
getTopic?(): string;

getIdentityKey(): string {
return `topic:${this.topic}`;
return `topic:${this.topic ?? ''}`;
}

getConfig(): QueryConfigOptions {
Expand All @@ -23,7 +26,10 @@ export abstract class TopicQuery extends Query {
subscribe: () => {
return () => {
const adapter = (this as Record<string, any>)._topicAdapter as TopicQueryAdapter | undefined;
adapter?.unsubscribe(this.topic);
const topic = this.getTopic ? this.getTopic() : this.topic;
if (topic !== undefined) {
adapter?.unsubscribe(topic);
}
};
},
};
Expand Down
9 changes: 7 additions & 2 deletions packages/fetchium/src/topic/TopicQueryAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,8 @@ import type { MutationEvent } from '../types.js';
// ================================

interface TopicCtx extends Query {
topic: string;
topic?: string;
getTopic?(): string;
_topicAdapter?: TopicQueryAdapter;
}

Expand Down Expand Up @@ -92,7 +93,11 @@ export abstract class TopicQueryAdapter extends QueryAdapter {
override async send(ctx: Query, _signal: AbortSignal): Promise<unknown> {
const topicCtx = ctx as TopicCtx;
topicCtx._topicAdapter = this;
const topic = topicCtx.topic;
const topic = topicCtx.getTopic ? topicCtx.getTopic() : topicCtx.topic;

if (topic === undefined) {
throw new Error('TopicQuery requires a topic. Define `topic` as a field or override `getTopic()`.');
}

const existing = this._topics.get(topic);

Expand Down
Loading