I have two models in database, user and post
const User = sequelize.define('user', {
id: {type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true},
email: {type: DataTypes.STRING, unique: true},
password: {type: DataTypes.STRING},
});
const Post = sequelize.define('post', {
author: {type: DataTypes.STRING},
title: {type: DataTypes.STRING},
content: {type: DataTypes.STRING}
});
And there is a method that creates a user post:
async createPost(req,res) {
try {
console.log(req.headers.authorization);
const {author} = await User.findOne({where: {email}});
const {title, content} = req.body;
/*if(!title || !content) {
return res.status(400).json({message: 'Title or content cannot be empty'});
}
const post = await Post.create({})*/
return res.json({message: 'All right'});
} catch (e) {
console.log(e.message);
}
}
}
How do I get the user's email from another table and store it in the author variable. Only a registered user can write a post. There was an option using jwt-decode to decrypt the jwt token and find the email field there, but can it be simpler?