Error function trpc

Okay, so im kinda new to trpc stuff and not that familiar with that. I want to throw error on backend when Email is not unique. So when i write it like this in my router it works great, it throws that error:
registerUser: publicProcedure
.input(z.object({ email: z.string(), password: z.string() }))
.mutation(async ({ input, ctx }) => {
const user = await ctx.prisma.user.findUnique({
where: {
email: input.email,
},
});
if (user) {
throw new TRPCError({
code: "CONFLICT",
message: "Email is already used.",
});
}
const newlyCreatedUser = await ctx.prisma.user.create({
data: input,
});
return newlyCreatedUser;
}),
});
registerUser: publicProcedure
.input(z.object({ email: z.string(), password: z.string() }))
.mutation(async ({ input, ctx }) => {
const user = await ctx.prisma.user.findUnique({
where: {
email: input.email,
},
});
if (user) {
throw new TRPCError({
code: "CONFLICT",
message: "Email is already used.",
});
}
const newlyCreatedUser = await ctx.prisma.user.create({
data: input,
});
return newlyCreatedUser;
}),
});
but wanted to do it in more elegant way, and use util function like this
import { TRPCError } from "@trpc/server";

export const isUniqueEmail = async (ctx: any, passedEmail: string) => {
const email = await ctx.prisma.user.findUnique({
where: {
email: passedEmail,
},
});
if (email) {
throw new TRPCError({ code: "CONFLICT" });
}
};
import { TRPCError } from "@trpc/server";

export const isUniqueEmail = async (ctx: any, passedEmail: string) => {
const email = await ctx.prisma.user.findUnique({
where: {
email: passedEmail,
},
});
if (email) {
throw new TRPCError({ code: "CONFLICT" });
}
};
and
export const userRouter = createTRPCRouter({
registerUser: publicProcedure
.input(z.object({ email: z.string(), password: z.string() }))
.mutation(async ({ input, ctx }) => {
isUniqueEmail(ctx, input.email)
const newlyCreatedUser = await ctx.prisma.user.create({
data: input,
});
return newlyCreatedUser;
}),
});
export const userRouter = createTRPCRouter({
registerUser: publicProcedure
.input(z.object({ email: z.string(), password: z.string() }))
.mutation(async ({ input, ctx }) => {
isUniqueEmail(ctx, input.email)
const newlyCreatedUser = await ctx.prisma.user.create({
data: input,
});
return newlyCreatedUser;
}),
});
, but then i just got error i assume from that unique field in db and got 500, not my desired error which i throw in util function. What is wrong? also, dont really know how to type ctx in util function. Thanks
1 Reply
Unknown User
Unknown User3y ago
Message Not Public
Sign In & Join Server To View

Did you find this page helpful?