T
TanStack6mo ago
fascinating-indigo

I use SvelteQuery with Svelte tRPC. How to send error or success response ?

Here i create authenticate logic for logged in the user
export const authenticateUser = async (formData: z.infer<LoginSchema>) => {
const { username, password } = formData;
const [user] = await db.select().from(users).where(eq(users.username, username)).limit(1);

if (!user) {
return sendTRPCResponse({
status: 401,
message: m.login_message_user_not_exists()
});
}

const isCorrectPassword = await bcrypt.compare(password, user.password);

if (!isCorrectPassword) {
return sendTRPCResponse({
status: 401,
message: m.login_message_mismatch_credentials()
});
}

const { token, refreshToken } = await createJWT(user.id);

if (!token && !refreshToken) {
return sendTRPCResponse({
status: 401,
message: m.login_message_session_error()
});
}

return sendTRPCResponse(
{
status: 200,
message: 'ok'
},
{
token,
refreshToken
}
);
};
export const authenticateUser = async (formData: z.infer<LoginSchema>) => {
const { username, password } = formData;
const [user] = await db.select().from(users).where(eq(users.username, username)).limit(1);

if (!user) {
return sendTRPCResponse({
status: 401,
message: m.login_message_user_not_exists()
});
}

const isCorrectPassword = await bcrypt.compare(password, user.password);

if (!isCorrectPassword) {
return sendTRPCResponse({
status: 401,
message: m.login_message_mismatch_credentials()
});
}

const { token, refreshToken } = await createJWT(user.id);

if (!token && !refreshToken) {
return sendTRPCResponse({
status: 401,
message: m.login_message_session_error()
});
}

return sendTRPCResponse(
{
status: 200,
message: 'ok'
},
{
token,
refreshToken
}
);
};
I use helper sendTRPCResponse
export function sendTRPCResponse<T = void>(
baseResponse: { status: number; message: string },
data: T | undefined = undefined
) {
return {
...baseResponse,
data: data as T
};
}
export function sendTRPCResponse<T = void>(
baseResponse: { status: number; message: string },
data: T | undefined = undefined
) {
return {
...baseResponse,
data: data as T
};
}
Is response with status 200 go to onSuccess callback of mutation and status != 200 is going to onError callback ?
2 Replies
national-gold
national-gold6mo ago
how is that related to start?
unwilling-turquoise
unwilling-turquoise6mo ago
-> #svelte-query-questions

Did you find this page helpful?