Last active
April 25, 2021 15:10
-
-
Save jmaicaaan/0536f6a2ad3c98aaf0e4cb00c65986df to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| import { | |
| format, | |
| isAfter, | |
| isSameDay, | |
| } from 'date-fns'; | |
| import * as Yup from 'yup'; | |
| import { tryCatch } from '../../utils/tryCatch'; | |
| const validationSchema = Yup.object().shape({ | |
| date: Yup.date().required(), | |
| startTime: Yup.date().required(), | |
| endTime: Yup.date().required() | |
| .when('startTime', (startTime: Date, schema: Yup.DateSchema) => { | |
| return schema.test( | |
| 'start-time-past', | |
| 'End Time should be ahead of Start Time', | |
| (endTime) => { | |
| return !isSameDay(endTime, startTime) && isAfter(endTime, startTime); | |
| }); | |
| }) | |
| }); | |
| export const post = async (req, res) => { | |
| const [validatedData, validationError] = await tryCatch(() => ( | |
| validationSchema.validate(req.body) | |
| )); | |
| if (validationError) { | |
| console.log('validationError', validationError); | |
| return res.status(400).send(validationError); | |
| } | |
| const { | |
| date: unformattedDate, | |
| startTime: unformattedStartTime, | |
| endTime: unformattedEndTime, | |
| } = validatedData; | |
| // TODO - Since this came from the request body, this needs to be cast to Date | |
| const date = format(new Date(unformattedDate), 'EEEE, MMMM dd, yyyy'); | |
| const startTime = format(new Date(unformattedStartTime), 'hh:mm aa'); | |
| const endTime = format(new Date(unformattedEndTime), 'hh:mm aa'); | |
| // This is a demo that the data will be saved | |
| // save({ | |
| // date, | |
| // startTime, | |
| // endTime, | |
| // }); | |
| return res.status(200).send('Successfully saved'); | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment