Reputation: 55
When a try to send a simple json including the id of a provider and a date I get the following error
UnhandledPromiseRejectionWarning: TypeError: Cannot
convert undefined or null to object
at Function.keys (<anonymous>)
at Function.findAll (C:\Users\Usuario\Desktop\Studies\Go_Stack\modulo2\goBarber\node_modules\sequelize\lib\model.js:1692:47)
at Function.findOne (C:\Users\Usuario\Desktop\Studies\Go_Stack\modulo2\goBarber\node_modules\sequelize\lib\model.js:1924:17)
at store (C:\Users\Usuario\Desktop\Studies\Go_Stack\modulo2\goBarber\src\app\controllers\AppointmentController.js:28:63)
at processTicksAndRejections (internal/process/task_queues.js:85:5)
(node:19212) UnhandledPromiseRejectionWarning: Unhandled promise
rejection. This error originated either by throwing inside of an
async function without a catch block, or by rejecting a promise which was not handled with .catch(). (rejection id: 1)
(node:19212) [DEP0018] DeprecationWarning: Unhandled promise rejections are deprecated. In the future, promise rejections that are not handled will terminate the Node.js process with a non-zero exit code.
import * as Yup from 'yup';
import { startOfHour, parseISO, isBefore } from 'date-fns';
import User from '../models/user';
import Appointment from '../models/Appointment';
class AppointmentController {
async store(req, res) {
const schema = Yup.object().shape({
provider_id: Yup.number().required(),
date: Yup.date().required(),
});
if (!(await schema.isValid(req.body))) {
return res.status(400).json({ error: 'Validations Fails' });
}
const { provider_id, date } = req.body;
const checkIsProvider = await User.findOne({
where: { id: provider_id, provider: true },
});
if (!checkIsProvider) {
return res.status(400).json({ error:'You can only create appointments with providers' });
}
const hourStart = startOfHour(parseISO(date));
if (isBefore(hourStart, new Date())) {
return res.status(400).json({ error: 'Past dates are not permitted' });
}
const checkAvailability = await Appointment.findOne({
where: {
provider_id,
canceled_at: null,
date: hourStart,
},
});
if (checkAvailability) {
return res.status(400).json({ error: 'Appointment date is not available' });
}
const appointment = await Appointment.create({
user_id: req.userId,
provider_id,
date,
});
return res.json(appointment);
}
}
export default new AppointmentController();
Upvotes: 0
Views: 1804
Reputation: 383
findOne method in Appointment class raises exception and you do not catch it anywhere. You need to do something like that:
let checkAvailability;
try {
checkAvailability = await Appointment.findOne({
where: {
provider_id,
canceled_at: null,
date: hourStart,
},
});
} catch (err) {
checkAvailability = false
}
use try/catch
to handle exceptions.
Check out await reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/await
Upvotes: 2