Reputation: 1065
Is it possible to add a custom response in Express JS, like add an attribute that not exists in the database?
My Controller:
createNewPersonalData: function (req, res) {
var name = req.body.name,
date_of_birth = req.body.date_of_birth;
var getAge = function () {
var today = new Date();
var dob = new Date(date_of_birth);
var count = today.getFullYear() - dob.getFullYear();
var m = today.getMonth() - dob.getMonth();
if (m < 0 || (m === 0 && today.getDate() < birthDate.getDate())) {
count = count - 1;
}
return count;
};
PersonalInfo.create({
name : name,
date_of_birth : date_of_birth,
age : getAge()
}).then(data => {
res.json({
'status': 'OK',
'messages': 'Personal Info Created',
'data': data
})
});
but the response is only all attribute from the database table. There's no attribute/field age
.
{
"code": 200,
"status": true,
"data": {
"id": 1,
"name": "John",
"date_of_birth": "1995-01-28T17:00:00.000Z",
}
}
the response what I expected is like:
{
"code": 200,
"status": true,
"data": {
"id": 1,
"name": "John",
"date_of_birth": "1995-01-28T17:00:00.000Z",
"age": 24
}
}
How do I can add that age
?
Upvotes: 1
Views: 3097
Reputation: 2545
Since you said using sequelize.js, you can use DataTypes.VIRTUAL on schema. And there is nothing you need to do in handlers for age calculation.
sequelize.define('PersonalInfo', {
name: DataTypes.STRING,
date_of_birth: DataTypes.DATE
age: {
type: DataTypes.VIRTUAL,
get: function() {
return getAge(this.get('date_of_birth'))
}
}
})
Upvotes: 2
Reputation: 3994
Just add the age
property to the data object after converting it to a JSON object with the toJSON
function in the Promise response.
PersonalInfo.create({
name : name,
date_of_birth : date_of_birth,
//age : getAge()
}).then(data => {
var info = data.toJSON({ versionKey:false });
info['age'] = getAge();
res.json({
'code':200,
'status': 'OK',
'messages': 'Personal Info Created',
'data': info
})
});
Upvotes: 2