Skip to content

Commit

Permalink
Match: Replace Joi with Zod
Browse files Browse the repository at this point in the history
  • Loading branch information
samuelim01 committed Oct 24, 2024
1 parent 966a859 commit a0a35bd
Show file tree
Hide file tree
Showing 4 changed files with 27 additions and 75 deletions.
76 changes: 14 additions & 62 deletions services/match/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

5 changes: 2 additions & 3 deletions services/match/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,19 +17,18 @@
"body-parser": "^1.20.3",
"cors": "^2.8.5",
"express": "^4.21.0",
"joi": "^17.13.3",
"jsonwebtoken": "^9.0.2",
"mongoose": "^8.7.0",
"morgan": "^1.10.0",
"zod": "^3.23.8"
"zod": "^3.23.8",
"zod-validation-error": "^3.4.0"
},
"devDependencies": {
"@eslint/js": "^9.10.0",
"@types/amqplib": "^0.10.5",
"@types/cors": "^2.8.17",
"@types/eslint__js": "^8.42.3",
"@types/express": "^4.17.21",
"@types/joi": "^17.2.2",
"@types/jsonwebtoken": "^9.0.7",
"@types/mongoose": "^5.11.96",
"@types/morgan": "^1.9.9",
Expand Down
11 changes: 7 additions & 4 deletions services/match/src/controllers/matchRequestController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,20 +10,23 @@ import {
} from '../models/repository';
import { produceMatchUpdatedRequest } from '../events/producer';
import { getStatus } from '../models/matchRequestModel';
import { fromError } from 'zod-validation-error';

/**
* Creates a match request.
* @param req
* @param res
*/
export const createMatchRequest = async (req: Request, res: Response) => {
const { error, value } = createMatchRequestSchema.validate(req.body);
if (error) {
return handleBadRequest(res, error.message);
const result = createMatchRequestSchema.safeParse(req.body);

if (!result.success) {
const formattedError = fromError(result.error).toString();
return handleBadRequest(res, formattedError);
}

const { id: userId, username } = req.user;
const { topics, difficulty } = value;
const { topics, difficulty } = result.data;
try {
const matchRequest = await _createMatchRequest(userId, username, topics, difficulty);
await produceMatchUpdatedRequest(matchRequest.id, userId, username, topics, difficulty);
Expand Down
10 changes: 4 additions & 6 deletions services/match/src/validation/matchRequestValidation.ts
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import Joi from 'joi';
import { z } from 'zod';
import { Difficulty } from '../models/matchRequestModel';

export const createMatchRequestSchema = Joi.object({
topics: Joi.array().items(Joi.string()).min(1).required(),
difficulty: Joi.string()
.valid(...Object.values(Difficulty))
.required(),
export const createMatchRequestSchema = z.object({
topics: z.array(z.string().min(1)).min(1),
difficulty: z.nativeEnum(Difficulty),
});

0 comments on commit a0a35bd

Please sign in to comment.