ChronicStone
ChronicStone
TtRPC
Created by ChronicStone on 8/28/2023 in #❓-help
tRPC subscription : Access to socket ID from subscription
I'm trying to implement user online status in a reliable way on my app, on the "live" part of my app. It's done & working well, but on some cases where the connexion is cut & not restored, I can't trigger the mutation marking the user offline. Right now I'm handling this through the client only right now but in some instances, it's not reliable. What I'd like to do would be something like this : (For subscription I need to pass my authToken as an input since wsLink does not support dynamic header resolver yet to my knowledge).
userOnlineStatusChanged: publicProcedure
.input(z.object({ authToken: z.string() }))
.subscription(async ({ input, ctx, socket }) => {
const user = await getUserFromJwt()
if(!user) throw new TRPCError({ code: 'UNAUTHORIZED', message: '...' })

// SOMEHOW GET SOCKET ID & ASSOCIATE IT TO USER :
const storage = useStorage('db')
storage.set(socket.id, user._id)


return observable<{ userId: string; online: boolean }>((emit) => {
mapEvents.on(
'userOnlineStatusChanged',
(params) => params.organizationId === user.organizationId && emit.next(params),
);

return () => {
mapEvents.off(
'userOnlineStatusChanged',
(params) => params.organizationId === user.organizationId && emit.next(params),
);
};
});
})
userOnlineStatusChanged: publicProcedure
.input(z.object({ authToken: z.string() }))
.subscription(async ({ input, ctx, socket }) => {
const user = await getUserFromJwt()
if(!user) throw new TRPCError({ code: 'UNAUTHORIZED', message: '...' })

// SOMEHOW GET SOCKET ID & ASSOCIATE IT TO USER :
const storage = useStorage('db')
storage.set(socket.id, user._id)


return observable<{ userId: string; online: boolean }>((emit) => {
mapEvents.on(
'userOnlineStatusChanged',
(params) => params.organizationId === user.organizationId && emit.next(params),
);

return () => {
mapEvents.off(
'userOnlineStatusChanged',
(params) => params.organizationId === user.organizationId && emit.next(params),
);
};
});
})
The goal being that on disconnexion of the socket, I mark the user as disconnected from the server to make the whole thing more reliable :
5 replies