Skip to content

Commit

Permalink
feat(validation): validate user interests to match subject list
Browse files Browse the repository at this point in the history
  • Loading branch information
Veirt committed Nov 13, 2024
1 parent 9ddcfb0 commit 08d5966
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 5 deletions.
2 changes: 1 addition & 1 deletion src/middleware/validation.middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ export const validator =
(schema: AnyZodObject): RequestHandler =>
async (req, res, next) => {
try {
const result = schema.parse({
const result = await schema.parseAsync({
body: req.body,
params: req.params,
query: req.query,
Expand Down
33 changes: 29 additions & 4 deletions src/schemas/user.schema.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import { firestore } from "@/config";
import { z } from "zod";

export const userSchema = z.object({
Expand All @@ -16,9 +17,35 @@ export const userSchema = z.object({
createdAt: z.date(),
updatedAt: z.date(),
lastSeen: z.date().optional(),
interests: z.array(z.string()).optional(),
interests: z
.array(z.string())
.superRefine(async (interests, ctx) => {
try {
const subjectsSnapshot = await firestore.collection("subjects").get();
const validSubjects = subjectsSnapshot.docs.map((doc) => doc.id);

const invalidInterests = interests.filter(
(interest) => !validSubjects.includes(interest),
);
if (invalidInterests.length > 0) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: `Invalid interests found: ${invalidInterests.join(", ")}`,
});
}
} catch (error) {
ctx.addIssue({
code: z.ZodIssueCode.custom,
message: "Failed to validate interests due to an internal error",
});
}
})
.optional(),
learningStyle: z
.enum(["visual", "auditory", "reading/writing", "kinesthetic"])
.enum(["visual", "auditory", "reading/writing", "kinesthetic"], {
message:
"Learning style must be one of 'visual', 'auditory', 'reading/writing', or 'kinesthetic'",
})
.optional(),
});

Expand All @@ -28,7 +55,5 @@ export const updateProfileSchema = z.object({
createdAt: true,
updatedAt: true,
lastSeen: true,
interests: true,
learningStyle: true,
}),
});

0 comments on commit 08d5966

Please sign in to comment.