Skip to content

Commit 9487671

Browse files
committed
feat: create schedule validation middleware
1 parent dea4214 commit 9487671

File tree

3 files changed

+32
-3
lines changed

3 files changed

+32
-3
lines changed

apps/server/src/controllers/v1/schedules.ts

+1-2
Original file line numberDiff line numberDiff line change
@@ -5,8 +5,7 @@ import middlewares from '@/middlewares'
55

66
const router: Router = asyncify(express.Router())
77

8-
// TODO: add validator(eventId, authorId)
9-
router.post('/', async (req: Request, res: Response) => {
8+
router.post('/', middlewares.schedules.addScheduleMiddleware, async (req: Request, res: Response) => {
109
const { name, eventId, authorId, startDate, endDate, address, location, description, images } = req.body
1110
const schedule = await ScheduleModel.create({
1211
name: name,

apps/server/src/middlewares/schedules.ts

+23-1
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { NextFunction, Request, Response } from 'express'
22
import { ScheduleModel } from '@/models/schedule'
3-
import { UnauthorizedSchedule } from '@/types/errors/schedule'
3+
import { InvalidRequestFormat, UnauthorizedSchedule } from '@/types/errors/schedule'
4+
import { EventsModel } from '@/models/event'
5+
import { UserModel } from '@/models/user'
46

57
export const verifyAuthorMiddleware = async (req: Request, res: Response, next: NextFunction) => {
68
const authorId = (await ScheduleModel.findOne({ _id: req.params.id }).exec())?.authorId
@@ -12,3 +14,23 @@ export const verifyAuthorMiddleware = async (req: Request, res: Response, next:
1214
}
1315
next()
1416
}
17+
18+
const verifyEventId = async (req: Request, res: Response, next: NextFunction) => {
19+
const { eventId } = req.body
20+
const target = await EventsModel.findOne({ _id: eventId }).exec()
21+
if (!target) {
22+
throw new InvalidRequestFormat(new Error(`not found event => id: ${eventId}`))
23+
}
24+
next()
25+
}
26+
27+
const verifyAuthorId = async (req: Request, res: Response, next: NextFunction) => {
28+
const { authorId } = req.body
29+
const target = await UserModel.findOne({ _id: authorId }).exec()
30+
if (!target) {
31+
throw new InvalidRequestFormat(new Error(`not found author => id: ${authorId}`))
32+
}
33+
next()
34+
}
35+
36+
export const addScheduleMiddleware = [verifyAuthorId, verifyEventId]

apps/server/src/types/errors/schedule.ts

+8
Original file line numberDiff line numberDiff line change
@@ -7,3 +7,11 @@ export class UnauthorizedSchedule extends APIError {
77
Error.captureStackTrace(this, UnauthorizedSchedule)
88
}
99
}
10+
11+
export class InvalidRequestFormat extends APIError {
12+
constructor(cause: Error | string = null) {
13+
super(400, 40000, 'invalid request format', cause)
14+
Object.setPrototypeOf(this, InvalidRequestFormat.prototype)
15+
Error.captureStackTrace(this, InvalidRequestFormat)
16+
}
17+
}

0 commit comments

Comments
 (0)