Skip to content

Commit

Permalink
feat(server + client): streaming mutations and queries over HTTP (#5700)
Browse files Browse the repository at this point in the history
  • Loading branch information
KATT committed May 19, 2024
1 parent 8cc33e2 commit 188e6a8
Show file tree
Hide file tree
Showing 3 changed files with 21 additions and 3 deletions.
10 changes: 8 additions & 2 deletions src/client/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/**
* This is the client-side code that uses the inferred types from the server
*/
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import { createTRPCClient, unstable_httpBatchStreamLink } from '@trpc/client';
/**
* We only import the `AppRouter` type from the server - this is not available at runtime
*/
Expand All @@ -10,7 +10,7 @@ import type { AppRouter } from '../server/index.js';
// Initialize the tRPC client
const trpc = createTRPCClient<AppRouter>({
links: [
httpBatchLink({
unstable_httpBatchStreamLink({
url: 'http://localhost:3000',
}),
],
Expand All @@ -34,3 +34,9 @@ console.log('Created user:', createdUser);
const user = await trpc.user.byId.query('1');
// ^?
console.log('User 1:', user);

const iterable = await trpc.examples.iterable.query();

for await (const i of iterable) {
console.log('Iterable:', i);
}
8 changes: 8 additions & 0 deletions src/server/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -32,6 +32,14 @@ const appRouter = router({
return user;
}),
},
examples: {
iterable: publicProcedure.query(async function* () {
for (let i = 0; i < 3; i++) {
await new Promise((resolve) => setTimeout(resolve, 500));
yield i;
}
}),
},
});

// Export type router type signature, this is used by the client.
Expand Down
6 changes: 5 additions & 1 deletion src/server/trpc.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,11 @@ import { initTRPC } from '@trpc/server';
* Initialization of tRPC backend
* Should be done only once per backend!
*/
const t = initTRPC.create();
const t = initTRPC.create({
experimental: {
iterablesAndDeferreds: true,
},
});

/**
* Export reusable router and procedure helpers
Expand Down

0 comments on commit 188e6a8

Please sign in to comment.