How would i be able to check if the current user liked the post or not. Ideally this would be similar to liking a post on instagram. The heart is filled red indicating that YOU liked it.
how would i be able to add a similar functionality for the backend.
I know the backend would have a boolean that indicates a user has like there own post. I'm using sequelize, given my model, what should i do to make this functionality work.
Ideally the liked column in post should indicate if i liked post or not.
req.session.user.id
gets the current user.
post.controller
getPosts: async (req: Request, res: Response) => {
await models.Post.findAll({
include: [
{ model: models.User, as: "author", attributes: ["username"] },
{ model: models.Likes }
],
order: [["createdAt", "DESC"]],
limit: 6
}).then(posts => {
res.json(posts);
});
},
Post (model)
"use strict";
module.exports = (sequelize, DataTypes) => {
var Post = sequelize.define("Post", {
title: DataTypes.STRING,
postContent: DataTypes.STRING,
liked: {
type: DataTypes.BOOLEAN,
allowNull: false,
defaultValue: false
},
likeCounts: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0
},
authorId: DataTypes.INTEGER
}, {});
Post.associate = function (models) {
Post.belongsTo(models.User, {
as: "author",
foreignKey: "authorId",
onDelete: "CASCADE"
});
Post.hasMany(models.Likes, {
foreignKey: "resourceId",
timestamps: false,
targetKey: "id",
onDelete: "CASCADE"
});
};
Post.prototype.likedByMe = postId => { };
return Post;
};
//# sourceMappingURL=post.js.map
Like (model)
"use strict";
module.exports = (sequelize, DataTypes) => {
var Likes = sequelize.define("Likes", {
userId: DataTypes.INTEGER,
resourceId: DataTypes.INTEGER,
likeByMe: {
type: DataTypes.BOOLEAN,
defaultValue: false,
allowNull: false
}
});
Likes.associate = function (models) {
// associations can be defined here
Likes.belongsTo(models.User, {
foreignKey: "userId",
timestamps: false,
onDelete: "CASCADE"
});
Likes.belongsTo(models.Post, {
foreignKey: "resourceId",
timestamps: false,
onDelete: "CASCADE",
targetKey: "id"
});
};
return Likes;
};
//# sourceMappingURL=likes.js.map
something like
const iLikeIt = Like.findOne({ where: {
resourceId: postId,
userId: req.session.user.id,
}})
if (iLikeIt) {
// i liked it
} else {
// i didn't like it
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.