Skip to content

Commit

Permalink
Moved validations insdie controller. Created util to format errors
Browse files Browse the repository at this point in the history
  • Loading branch information
Disura-Randunu committed Sep 16, 2024
1 parent 0b8299a commit 60bcc8d
Show file tree
Hide file tree
Showing 3 changed files with 33 additions and 8 deletions.
24 changes: 23 additions & 1 deletion src/controllers/admin/mentor.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ import {
} from '../../services/mentor.service'
import type { ApiResponse, PaginatedApiResponse } from '../../types'
import { IMG_HOST } from '../../configs/envConfig'
import { formatValidationErrors, upload } from '../../utils'
import { mentorUpdateSchema } from '../../schemas/admin/admin.mentor-routes.schema'

export const updateMentorHandler = async (
req: Request,
Expand All @@ -27,15 +29,35 @@ export const updateMentorHandler = async (
}

try {
const { mentorId } = req.params
await new Promise<void>((resolve, reject) => {
upload(req, res, (err) => {
if (err) {
reject(err)
} else {
resolve()
}
})
})

const data = req.body.data ? JSON.parse(req.body.data) : req.body

const result = mentorUpdateSchema.safeParse(data)
if (!result.success) {
return res.status(400).json({
error: 'Invalid data',
details: formatValidationErrors(result.error)
})
}

const mentorUpdateData: Partial<Mentor> = { ...data }
const profileUpdateData: Partial<Profile> = { ...data.profile }

if (req.file) {
profileUpdateData.image_url = `${IMG_HOST}/${req.file.filename}`
}

const { mentorId } = req.params

const { mentor, statusCode, message } = await updateMentorDetails(
mentorId,
mentorUpdateData,
Expand Down
8 changes: 1 addition & 7 deletions src/routes/admin/mentor/mentor.route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,20 +17,14 @@ import {
getAllMentorEmailsSchema,
getAllMentorsByStatusSchema,
mentorStatusSchema,
mentorUpdateSchema,
searchMentorsSchema,
updateMentorAvailabilitySchema
} from '../../../schemas/admin/admin.mentor-routes.schema'
import { paginationSchema } from '../../../schemas/common/pagination-request.schema'
import { upload } from '../../../utils'

const mentorRouter = express.Router()

mentorRouter.put(
'/:mentorId',
[requireAuth, upload, requestBodyValidator(mentorUpdateSchema)],
updateMentorHandler
)
mentorRouter.put('/:mentorId', requireAuth, updateMentorHandler)
mentorRouter.put(
'/:mentorId/state',
[requireAuth, requestBodyValidator(mentorStatusSchema)],
Expand Down
9 changes: 9 additions & 0 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@ import { generateCertificate } from './services/admin/generateCertificate'
import { randomUUID } from 'crypto'
import { certificatesDir } from './app'
import type Mentee from './entities/mentee.entity'
import { type ZodError } from 'zod'

export const signAndSetCookie = (res: Response, uuid: string): void => {
const token = jwt.sign({ userId: uuid }, JWT_SECRET ?? '')
Expand Down Expand Up @@ -290,3 +291,11 @@ export const getPasswordChangedEmailContent = (
export const capitalizeFirstLetter = (word: string): string => {
return word.charAt(0).toUpperCase() + word.slice(1).toLowerCase()
}

export const formatValidationErrors = (
err: ZodError
): Array<{ message: string }> => {
return err.errors.map((issue) => ({
message: `${issue.path.join('.')} is ${issue.message}`
}))
}

0 comments on commit 60bcc8d

Please sign in to comment.