验证检查在存储库模式中去哪里?

发布于 2024-10-10 16:27:43 字数 501 浏览 1 评论 0原文

假设我有一个名为 User 的实体,它有很多帖子。我的删除帖子的服务如下所示:

void DeletePost(int postId, int userId);

我的验证码去了哪里? (确保用户有删除权限)。我应该在存储库中通过 1 次数据库调用来执行此操作吗?或者我应该在进行 2 个调用的服务层中进行此检查:

  1. 通过 userId 获取用户。
  2. 对用户进行验证后调用删除。

我将有 2 个存储库,1 个用于用户,1 个用于帖子,每个存储库如下所示:

// From the PostRepository.
void Delete(int postId); //May have to add a userId param if I do validation in repository
//From the UserRepository.
User GetUser(int userId);

Lets say I have an entity called User which has many Posts. My service looks like this for the deletion of a post:

void DeletePost(int postId, int userId);

Where does my validation code go? (ensure that the user has permission to delete). Should I do this in the repository with 1 database call? Or should I do this check in the Service layer where I make 2 calls:

  1. Get the user by userId.
  2. Call delete after validation has been done on the user.

I will have 2 repositories, 1 for the user and 1 for the post, each looking like this:

// From the PostRepository.
void Delete(int postId); //May have to add a userId param if I do validation in repository
//From the UserRepository.
User GetUser(int userId);

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

油饼 2024-10-17 16:27:44

这是一个业务规则,所以我不会将其放在数据访问层(存储库)上。我想说最好的地方是服务层。

That's a business rule so I wouldn't place it on the data access layer (Repository). I'd say the best place is the service layer.

堇年纸鸢 2024-10-17 16:27:44

我认为在进入域模型/业务层中的存储库之前应该进行一些验证。

您可以选择深度验证并在存储库层中执行验证;这可能是也可能不是一个好主意,具体取决于验证的目的;如果验证是特定于域的,那么我觉得验证应该在域模型中。另一方面,如果验证在本质上不太特定于领域并且更通用,那么将其放在存储库/数据访问层中意味着可以在重用数据访问层的其他项目中重用该验证。

I think some validation should happen before you get to the repository i.e. in the domain model / business layer.

You may opt to validate in depth and perform validation also in the repository layer; this may or may not be a good idea depending on what the validation is for; if the validation is domain specific then it strikes me that the validation should be in the domain model. On the other hand, if the validation is less domain specific and more general in its nature, then having it in the repository / data access layer means that the validation can be reused across other projects in which the data access layer is reused.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文