W
Wasp4mo ago
Dada

API Context Problem

in my main.wasp:
// ....

query getConversations {
fn: import { getConversations } from "@src/chat/queries",
entities: [User, Conversation, Participant, Message],
auth: true
}

api mobileGetConversations {
fn: import { mobileGetConversations } from "@src/chat/mobileApi.ts",
entities: [User, Conversation, Participant, Message],
auth: true,
httpRoute: (GET, "/api/auth/mobile/conversations")
}
// ....

query getConversations {
fn: import { getConversations } from "@src/chat/queries",
entities: [User, Conversation, Participant, Message],
auth: true
}

api mobileGetConversations {
fn: import { mobileGetConversations } from "@src/chat/mobileApi.ts",
entities: [User, Conversation, Participant, Message],
auth: true,
httpRoute: (GET, "/api/auth/mobile/conversations")
}
@src/chat/mobileApi.ts
// ...
interface ApiContext {
user?: User;
entities: {
User: PrismaClient['user'];
Conversation: PrismaClient['conversation'];
Participant: PrismaClient['participant'];
Message: PrismaClient['message'];
MessageStatus: PrismaClient['messageStatus'];
}
}
// GET /api/auth/mobile/conversations
export const mobileGetConversations = async (req: any, context: ApiContext): Promise<MobileConversation[]> => {
try {
const conversations = await getConversationsQuery({}, context);
/// ....
} catch (error: any) {
console.error('Failed to get conversations:', error);
throw new HttpError(500, error.message || 'Failed to get conversations');
}
};

// ...
// ...
interface ApiContext {
user?: User;
entities: {
User: PrismaClient['user'];
Conversation: PrismaClient['conversation'];
Participant: PrismaClient['participant'];
Message: PrismaClient['message'];
MessageStatus: PrismaClient['messageStatus'];
}
}
// GET /api/auth/mobile/conversations
export const mobileGetConversations = async (req: any, context: ApiContext): Promise<MobileConversation[]> => {
try {
const conversations = await getConversationsQuery({}, context);
/// ....
} catch (error: any) {
console.error('Failed to get conversations:', error);
throw new HttpError(500, error.message || 'Failed to get conversations');
}
};

// ...
in @src/chat/queries , when the query is called from within wasp frontend using useQuery Hook , it works fine and the context contains the user and the entities , but when its called from the api handler function , the user is found in context.req.user instead of context.user and the entities no where to be found:
export const getConversations = async (args: GetConversationsArgs, context: any): Promise<AugmentedConversation[]> => {

if (!context.user && !context.req.user) {
throw new HttpError(401, 'User not authenticated. Please login.');
}
const currentUserId = context?.user?.id || context?.req?.user?.id;

// ....
export const getConversations = async (args: GetConversationsArgs, context: any): Promise<AugmentedConversation[]> => {

if (!context.user && !context.req.user) {
throw new HttpError(401, 'User not authenticated. Please login.');
}
const currentUserId = context?.user?.id || context?.req?.user?.id;

// ....
what am i doing wrong ?
3 Replies
kapa.ai
kapa.ai4mo ago
Hi @Dada. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- You're encountering a common issue when reusing Wasp operations (like queries) inside custom API endpoints: the context object provided by Wasp to queries/actions is not the same as the one you get in a custom API handler. What's happening: - When Wasp calls your query (e.g., via useQuery on the frontend), it injects a context object that contains both user and entities, as expected for Wasp operationsImplementing Queries. - When you define a custom API endpoint (with api in main.wasp), the handler function receives three arguments: req, res, and context. The context here is also injected by Wasp, but its structure is specific to APIs. If you don't see entities in context, it's likely due to how you're calling or passing context between your API and your queryDefining the API's NodeJS Implementation. Key points from the docs: - In a custom API, your handler signature should be:
export const mobileGetConversations = (req, res, context) => { ... }

export const mobileGetConversations = (req, res, context) => { ... }

The context object should contain user and entities if you declare them in main.waspUsing Entities in APIs. - If you call a query from your API handler, you must ensure you pass the correct context structure. The context you get in the API handler is not automatically the same as the one Wasp injects into queries/actions. What you might be doing wrong: - In your API handler, you are calling getConversationsQuery({}, context), passing the API's context directly to the query. However, the query expects a context shaped as Wasp would inject it (with entities and user at the top level), but the API context may differ, or you may be missing some fields. - You mention that user is found in context.req.user instead of context.user. This suggests that your API context is not matching what the query expects. How to fix: You need to adapt the context from your API handler to match what your query expects. For example:
export const mobileGetConversations = async (req, res, context) => {
// Adapt context for the query
const queryContext = {
user: context.user || context.req?.user,
entities: context.entities,
};

try {
const conversations = await getConversationsQuery({}, queryContext);
// ...
} catch (error) {
// ...
}
};
export const mobileGetConversations = async (req, res, context) => {
// Adapt context for the query
const queryContext = {
user: context.user || context.req?.user,
entities: context.entities,
};

try {
const conversations = await getConversationsQuery({}, queryContext);
// ...
} catch (error) {
// ...
}
};
Make sure that: - You are using the correct handler signature for your API: (req, res, context). - You adapt the context before passing it to the query, so it matches what the query expects (user and entities at the top level). References: - Defining the API's NodeJS Implementation - Using Entities in APIs - Implementing Queries If you still don't see entities in context, double-check your main.wasp api declaration includes the entities field, and that you're using the correct handler signature. If the problem persists, there may be a bug or a deeper integration issue. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ---------------------- Sorry @Dada, I seem to be having a bit of trouble. Don't worry though, I've pinged my support and they will try to fix me up! :technologist: Perhaps try again in 15mins?
Filip
Filip4mo ago
Hey @Dada, sorry for the delay. We were out for a couple of days. Still need help here?
Dada
DadaOP4mo ago
@Filip no its all good , thank you bro.

Did you find this page helpful?