Last active
November 17, 2024 17:22
-
-
Save odiel/f4d3d09650fd1598ea29f6750e76841a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { | |
createTRPCClient, | |
httpBatchLink, | |
loggerLink, | |
splitLink, | |
unstable_httpSubscriptionLink, | |
} from '@trpc/client'; | |
import type { AppRouter } from './server.ts'; | |
async function delay(ms: number) { | |
return new Promise((resolve) => { | |
setTimeout(resolve, ms); | |
}); | |
} | |
async function main() { | |
const url = 'http://127.0.0.1:8000/trpc'; | |
const trpc = createTRPCClient<AppRouter>({ | |
links: [ | |
loggerLink({}), | |
splitLink({ | |
condition: (op) => op.type === 'subscription', | |
true: unstable_httpSubscriptionLink({ url }), | |
false: httpBatchLink({ url }), | |
}), | |
], | |
}); | |
await delay(100); | |
await trpc.example.subscribe(undefined, { | |
onData: (data: any) => { | |
console.log('received', data); | |
} | |
}); | |
console.log('👌 should be a clean exit if everything is working right'); | |
} | |
main().catch((err) => { | |
console.error(err); | |
Deno.exit(1); | |
}); | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { initTRPC } from '@trpc/server'; | |
import { fetchRequestHandler } from '@trpc/server/adapters/fetch'; | |
import EventEmitter, { on } from 'node:events'; | |
const t = initTRPC.create(); | |
const router = t.router; | |
const procedure = t.procedure; | |
const { subscription } = procedure; | |
const ee = new EventEmitter(); | |
let counter = 0; | |
setInterval(() => { | |
counter++; | |
ee.emit('count', counter); | |
console.log(`counting: ${counter}`); | |
}, 2000); | |
const iterate = async function* (opts: any) { | |
for await ( | |
const [_] of on(ee, 'count', { | |
signal: opts.signal, | |
}) | |
) { | |
console.log(`yield counter: ${counter}`); | |
yield counter; | |
} | |
}; | |
export const appRouter = router({ | |
example: subscription(iterate), | |
}); | |
export type AppRouter = typeof appRouter; | |
function handler(request: Request) { | |
if (request.method === 'HEAD') { | |
return new Response(); | |
} | |
return fetchRequestHandler({ | |
endpoint: '/trpc', | |
req: request, | |
router: appRouter, | |
createContext: () => ({}), | |
}); | |
} | |
Deno.serve(handler); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment