简体   繁体   English

我应该为这些任务使用什么模式?

[英]What pattern should I use for such tasks?

PS I probably didn't quite understand the mvc principle, but I always thought that business logic should happen in models - correct me if I'm wrong PS我可能不太了解mvc原理,但我一直认为业务逻辑应该发生在模型中-如果我错了请纠正我

I am writing project and using the mvc pattern.我正在编写项目并使用 mvc 模式。 router accepts requests and passes to controller, it takes data and sends it to model.路由器接受请求并传递给 controller,它获取数据并将其发送到 model。 Model checks the data for validation and, if successful, works with the database. Model 检查数据以进行验证,如果成功,则使用数据库。 My models have very large code and mix with validation.我的模型有非常大的代码并与验证混合。

exports.modelFunction = (data) => {
// validation data ...
// working with the database
}

With new fixes it becomes difficult for me to read the code.随着新的修复,我很难阅读代码。
I decided to create a utils / validation / folder where I will handle all possible model validations and yes, now the code is more readable我决定创建一个 utils / validation / 文件夹,我将在其中处理所有可能的 model 验证,是的,现在代码更具可读性

exports.modelFunction = (data) => {
  const validation = validationModel(data);
  if (!validation) return {ok: false, message: 'Validation failed'}
  // working with the database
}

I thought that there are already some other patterns that adhere to the separation of logic and solve problems like mine.我认为已经有一些其他模式坚持逻辑分离并解决像我这样的问题。 So I decided to ask you for a hint.所以我决定问你一个提示。

I think you're confused with data validation with business logic.我认为您将数据验证与业务逻辑混淆了。

The controller is where your business logic lives. controller 是您的业务逻辑所在。 It it is the gateway to allow for model access.它是允许 model 访问的网关。

If the controller decides that the user can access/modify the data, then it passes that data down to your model to do work.如果 controller 决定用户可以访问/修改数据,那么它将将该数据传递给您的 model 进行工作。

Your model should validate the data and see if it has all the required attributes to work with the database.您的 model 应该验证数据并查看它是否具有使用数据库所需的所有属性。 If it doesn't then it fails and is returned to your controller.如果没有,则失败并返回到您的 controller。 If that happens, then your controller needs to do your business logic and respond back to the request with the status.如果发生这种情况,那么您的 controller 需要执行您的业务逻辑并使用状态回复请求。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM