kotyan
kotyan
TTCTheo's Typesafe Cult
Created by janglad on 9/4/2023 in #questions
Prisma + Zod, where to validate uniqueness
frontend:
useEffect(() => {
if (error && error.message === CommunityErrorMessages.NAME_ALREADY_EXISTS) {
form.setError("name", {
type: "manual",
message: CommunityErrorMessages.NAME_ALREADY_EXISTS,
});
}
}, [error, form]);
useEffect(() => {
if (error && error.message === CommunityErrorMessages.NAME_ALREADY_EXISTS) {
form.setError("name", {
type: "manual",
message: CommunityErrorMessages.NAME_ALREADY_EXISTS,
});
}
}, [error, form]);
10 replies
TTCTheo's Typesafe Cult
Created by janglad on 9/4/2023 in #questions
Prisma + Zod, where to validate uniqueness
const validateUniqueConstraint = async ({
fieldName,
errorMessage,
func,
}: {
fieldName: string;
errorMessage: string;
func: Function;
}) => {
try {
return await func();
} catch (e) {
if (
e instanceof PrismaClientKnownRequestError &&
e.code === "P2002" &&
(e.meta?.target as string[])?.includes(fieldName)
) {
throw new TRPCError({
code: "CONFLICT",
message: errorMessage,
});
}
}
};

enum ErrorMessages {
FIELD_ALREADY_EXISTS = "Field already exists",
}

const result = await validateUniqueConstraint({
fieldName: "name",
errorMessage: ErrorMessages.FIELD_ALREADY_EXISTS,
func: () =>
prisma.entity.create({
data: {
field: "value",
},
}),
});
const validateUniqueConstraint = async ({
fieldName,
errorMessage,
func,
}: {
fieldName: string;
errorMessage: string;
func: Function;
}) => {
try {
return await func();
} catch (e) {
if (
e instanceof PrismaClientKnownRequestError &&
e.code === "P2002" &&
(e.meta?.target as string[])?.includes(fieldName)
) {
throw new TRPCError({
code: "CONFLICT",
message: errorMessage,
});
}
}
};

enum ErrorMessages {
FIELD_ALREADY_EXISTS = "Field already exists",
}

const result = await validateUniqueConstraint({
fieldName: "name",
errorMessage: ErrorMessages.FIELD_ALREADY_EXISTS,
func: () =>
prisma.entity.create({
data: {
field: "value",
},
}),
});
10 replies
TTCTheo's Typesafe Cult
Created by janglad on 9/4/2023 in #questions
Prisma + Zod, where to validate uniqueness
I've created a utility function validateUniqueConstraint to handle unique constraint errors from Prisma. It takes in a field name, error message, and a function that triggers a Prisma operation. If a unique constraint error occurs on the specified field, it throws a user-friendly TRPCError with the provided error message. Then I handle this error using enum on the frontend.
10 replies