molochM
tRPC3y ago
7 replies
moloch

Cannot get subscription event to fire

Ripping my hair out here trying to get Websockets working with tRPC and Next. Everything seems to be working and the frontend client is connecting to my websocket server, however triggering the addFact mutation does not not successfully emit the new catFact despite there not being any errors. I've looked at various repos that achieve similar functionality and haven't been able to spot the problem, does anyone have any guidance?

export const catFactsRouter = createTRPCRouter({
  fact: publicProcedure.query(({ ctx }) => {

    const fact = ctx.prisma.catFact.findFirst({
      orderBy: {
        createdAt: "desc",
      },
    });

    return fact;
  }),
  addFact: protectedProcedure
    .input(
      z.object({
        token: z.string().min(1),
        fact: z.string().min(1)
      })
    )
    .mutation(async ({ input, ctx }) => {
      console.log(`protectedProcedure.mutation()`);
      const fact = await ctx.prisma.catFact.create({
        data: {
          fact: input.fact,
        }
      });
      console.log(`ctx.ee.emit(Events.NEW_CAT_FACT, fact)`);
      ctx.ee.emit(Events.NEW_CAT_FACT, fact);
      console.log(`ee.emit(Events.NEW_CAT_FACT, fact);`);
      return fact;
    }),
  onFact: publicProcedure.subscription(({ ctx }) => {
    console.log("publicProcedure.subscription")

    // `resolve()` is triggered for each client when they start subscribing `onFact`
    // return an `observable` with a callback which is triggered immediately
    return observable<CatFact>((emit) => {
      const onCatFact = (data: CatFact) => {
        console.log(`Emitting fact to client:`, data);
        // emit data to client
        emit.next(data);
      };
      console.log("ctx.ee.on(Events.NEW_CAT_FACT, onCatFact);")

      ctx.ee.on(Events.NEW_CAT_FACT, onCatFact);

      return () => {
        ctx.ee.off(Events.NEW_CAT_FACT, onCatFact);
      };
    });
  }),
});
Was this page helpful?