import { inferAsyncReturnType, initTRPC } from "@trpc/server";
import {
CreateHTTPContextOptions,
createHTTPServer,
} from "@trpc/server/adapters/standalone";
import {
CreateWSSContextFnOptions,
applyWSSHandler,
} from "@trpc/server/adapters/ws";
import { observable } from "@trpc/server/observable";
import ws from "ws";
// import { z } from "zod";
// This is how you initialize a context for the server
function createContext(
opts: CreateHTTPContextOptions | CreateWSSContextFnOptions
) {
return {};
}
type Context = inferAsyncReturnType<typeof createContext>;
const t = initTRPC.context<Context>().create();
const publicProcedure = t.procedure;
const router = t.router;
const postRouter = router({
randomNumber: publicProcedure.subscription(() => {
return observable<{ randomNumber: number }>((emit) => {
const timer = setInterval(() => {
emit.next({ randomNumber: Math.random() });
console.log({ randomNumber: Math.random() });
}, 200);
return () => {
clearInterval(timer);
};
});
}),
});
// Merge routers together
export const appRouter = router({
post: postRouter,
});
export type AppRouter = typeof appRouter;
// http server
const { server, listen } = createHTTPServer({
router: appRouter,
createContext,
});
// ws server
const wss = new ws.Server({ server });
applyWSSHandler<AppRouter>({
wss,
router: appRouter,
createContext,
});
setInterval(() => {
console.log("Connected clients", wss.clients.size);
}, 1000);
listen(2022);
console.log("Server running");