2 回答

TA貢獻(xiàn)1816條經(jīng)驗(yàn) 獲得超6個(gè)贊
因此,通過遵循 @doublesharp 幫助,我能夠通過使用續(xù)集數(shù)據(jù)類型VIRTUAL以及使用getDataValue來確定當(dāng)前用戶是否喜歡該帖子
更新代碼
崗位(模型)
"use strict";
module.exports = (sequelize, DataTypes) => {
var Post = sequelize.define("Post", {
title: DataTypes.STRING,
postContent: DataTypes.STRING,
liked: {
type: DataTypes.VIRTUAL,
allowNull: false,
defaultValue: false,
get: function () {
return this.getDataValue('Likes').length ? true : false;
}
},
likeCounts: {
type: DataTypes.INTEGER,
allowNull: false,
defaultValue: 0,
validate: {
min: 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"
});
};
return Post;
};
//# sourceMappingURL=post.js.map

TA貢獻(xiàn)1784條經(jīng)驗(yàn) 獲得超7個(gè)贊
我相信您看到的錯(cuò)誤是因?yàn)槟鷽]有解決由以下人員返回的承諾:
post.increment("likeCounts", { by: 1 });
post.update({ liked: req.session.user.id ? true : false });
這意味著將在這些查詢執(zhí)行之前發(fā)送響應(yīng)。該post.liked值將user.id在會(huì)話中的任何時(shí)候設(shè)置為 true 。如果稍后的查詢失敗,您可能需要考慮使用事務(wù)來回滾一些較早的查詢。我還建議使用Promise.all()進(jìn)行并發(fā)查詢(它會(huì)更快)并且只使用async/await不混入thenables.
likePost: async (req: any, res: Response) => {
// fetch created and post at the same time
const [ created, post ] = await Promise.all([
models.Likes.findOne({
where: {
userId: req.session.user.id,
resourceId: req.params.id
}
}),
models.Post.findOne({
where: {
id: req.params.id
}
}),
]);
// no post, no updates
if (!post) {
return res.status(200).send({
message: "there is no post to be liked"
});
}
// we are going to make updates, so use a transaction, you will need to reference sequelize
let transaction;
try {
transaction = await sequelize.transaction();
if (!created && post) {
// use Promise.all() for concurrency
await Promise.all([
models.Likes.create({
userId: req.session.user.id,
resourceId: req.params.id
}, { transaction }),
post.increment("likeCounts", { by: 1, transaction }),
post.update({ liked: req.session.user.id ? true : false }, { transaction }),
]);
await transaction.commit();
return res.status(200).send({
message: "You liked this post"
});
}
await Promise.all([
models.Likes.destroy({
where: {
userId: req.session.user.id
}
}, { transaction }),
post.decrement("likeCounts", { by: 1, transaction }),
]);
await transaction.commit();
return res.status(200).send({
message: "You unliked this post"
});
} catch (err) {
if (transaction) {
await transaction.rollback();
}
console.log('There was an error', err);
return res.status(500);
}
}
僅Likes在 getPost() 上返回當(dāng)前用戶
getPosts: async (req: any, res: Response) => {
const posts = await models.Post.findAll({
include: [
{ model: models.User, as: "author", attributes: ["username"] },
// limit the likes based on the logged in user
{ model: models.Likes, required: false,
where: { userId: req.session.user.id },
},
],
order: [["createdAt", "DESC"]],
limit: 6
});
return res.json(posts);
},
添加回答
舉報(bào)