So what's happening is I have a Handler that has 2 types of response, an object or an error. In the routes file, the error and the object arrive normally, but when it sends the response with the object to the client, it receives an empty object.
I tried changing res.reply to return result and checking if the result is not null before it was sent to client but it didn't work.
src/Handlers/Professor.handler.js
const Professor = require('../Models/Professor.model');
const validator = require('validator');
/**
* A Class for handling professor-related routes
*/
class ProfessorHandler {
/**
* Register a professor into system
* @param {string} firstName
* @param {string} lastName
* @param {string} email
* @param {string} password
* @return {(object | Error)} Professor information
*
*/
async register({firstName, lastName, email, password}) {
if (firstName.length === 0 ||
lastName.length === 0 ||
email.length === 0 ||
password.length === 0) {
return new Error('Missing fields');
}
if (validator.isEmail(email) === false) {
return new Error('Invalid Email');
};
const emailAlreadyExists = await Professor.findOne({email});
if (emailAlreadyExists) {
return new Error('This email is already in use');
};
const professor = new Professor({firstName, lastName, email, password});
await professor.save();
await professor.generateToken();
return {
firstName: professor.firstName,
lastName: professor.lastName,
_id: professor._id,
tokens: professor.tokens,
};
}
};
module.exports = ProfessorHandler;
src/Routes/Professor.route.js
(...)
fastify.post('/professor/register',
registerProfessor,
async (req, reply) => {
const {firstName, lastName, email, password} = req.body;
const service = new ProfessorHandler();
const result = await service.register({
firstName,
lastName,
email,
password,
});
if (result instanceof Error) {
return reply.code(400).send({
error: result.message,
});
};
if (result === null) {
return reply.code(400).send({
error: 'Object is null',
});
};
return reply.send({professor: result});
});
The object comes normally, but it arrives empty in the response. I added a console.log on result before reply.send