gpt4 book ai didi

javascript - sequelize findAll 不检查当前用户是否喜欢帖子

转载 作者:行者123 更新时间:2023-11-30 10:59:08 28 4
gpt4 key购买 nike

我有一个场景,如果你喜欢一个帖子,它就会改变

liked:falseliked:true

这个喜欢是基于当前用户是否喜欢这个帖子。问题是当新用户注册时,它仍然会显示 liked 为 true,尽管新用户不喜欢该帖子。

我如何才能检查当前用户是否喜欢该帖子?就检查当前用户是否喜欢该帖子而言,我认为我的逻辑有些不对。

我想保留 findAll 功能,我应该获取所有帖子,而不仅仅是当前用户的帖子。

有点像 instagram 或 facebook。

这是帖子数组

enter image description here

这就是我喜欢一个帖子的方式

likePost

likePost: async (req: any, res: Response) => {
const created = await models.Likes.findOne({
where: {
userId: req.session.user.id,
resourceId: req.params.id
}
});
console.log(created);
const post = await models.Post.findOne({ where: { id: req.params.id } });
// if like not created then do this
if (!created && post) {
await models.Likes.create({
userId: req.session.user.id,
resourceId: req.params.id
}).then(() => {
post.increment("likeCounts", { by: 1 });
post.update({ liked: req.session.user.id ? true : false });
res.status(200).send({
message: "You liked this post"
});
});
// else if post does not exist
} else if (!post) {
res.status(200).send({
message: "there is not post to be liked"
});
} else {
// else if a like does exist destroy like
await models.Likes.destroy({
where: {
userId: req.session.user.id
}
}).then(() => {
post.decrement("likeCounts", { by: 1 });
res.status(200).send({
message: "You unliked this post"
});
});
}

这就是我获取帖子的方式。

获取帖子

 getPosts: async (req: any, 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.js(模型)

"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,
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;
};

最佳答案

我相信您看到的错误是因为您没有解决返回的 promise :

    post.increment("likeCounts", { by: 1 });
post.update({ liked: req.session.user.id ? true : false });

这意味着响应将在这些查询执行之前发送。只要 session 中有 user.idpost.liked 值就会设置为 true。如果后面的查询失败,您可能需要考虑使用事务来回滚一些较早的查询。我还建议使用 Promise.all() 进行并发查询(它会更快)并专门使用 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);
}
}

在 getPost() 上只返回当前用户的 Likes

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);
},

关于javascript - sequelize findAll 不检查当前用户是否喜欢帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58651479/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com