WaspW
Wasp2y ago
JLegendz

useQuery server side?

I am trying to use one of my queries inside of my websocket server but when I do, the context.user doesn't exist. Even if I make sure that I'm calling this query after the user is authenticated. I'm not sure why context.user isn't populated, but it got me to thinking if maybe I should only be using the queries from the client side? Surely there's a way to do it server side though?

I have this query:

app/src/server/queries.ts
export const getSubscriptionsByUser: GetSubscriptionsByUser<void, Subscription[]> = async (args, context) => {
  if (!context.user) {
    throw new HttpError(401);
  }

  return context.entities.Subscription.findMany({
    where: {
      userId: context.user.id,
    },
    include: {
      listing: true,
    },
  });
};


and in my ws-server.ts I'm attempting to use it like this.

import { getListingSubscribers, getSubscriptionsByUser } from './queries'; // Import the getListingSubscribers function

//Skipping a bunch of unrelated code... 

socket.on('userAuthenticated', async () => {
    console.log('User authenticated:', username);

    // Check if the user is authenticated before trying to rejoin rooms
    if (socket.data.user) {
        try {
            //TODO There is an error here. context.user doesn't exist and so we can't fetch subscriptions here.
            // It's all happening before the user is fully authenticated apparently.
            const subscriptions = await getSubscriptionsByUser(undefined, context);
            subscriptions.forEach(sub => {
                const room = `listing_${sub.listingId}`;
                socket.join(room);
                console.log(`${username} rejoined room ${room}`);
            });
        } catch (error) {
            console.error('Error rejoining rooms:', error);
        }
    } else {
        console.warn('User not authenticated, skipping room rejoining.');
    }
});


The end goal of all this is to emit a signal when the user is authenticated, so that I can make sure that context.user exists, and then I can add the user back into any websocket rooms they belong to as a way to persist that connection between server restarts during development.

I always get a 401 no matter what though, and context.user just doesn't exist. Any suggestions here? I'm not sure what I'm doing wrong.
Was this page helpful?