正确使用 SailsJs 策略、服务和模型

Correctly using SailsJs policies, services and models

我是 NodeJs 和 SailsJs 的新手,请多关照。

我一直在使用策略来完成 POST 最终会创建新模型的请求;

  1. 检查所有请求参数是否存在的策略,如果缺少任何参数则用 404 或类似的响应
  2. 调用服务以检查数据库中是否存在某个模型以及它是否具有正确状态以进行请求的策略。此策略可能会向请求添加其他参数,以便稍后在创建新模型时使用。
  3. 同上不同型号。
  4. 现在我们知道这两个模型存在并且正确,我们可以使用在步骤 3 和 4 中使用的类似服务来修改它们。
  5. 现在我们所有的策略都已通过,为新创建的模型调用 OnCreate,这将对新创建的模型做一些最后的修改。

为了检查请求并向请求添加其他参数,这些策略似乎是个好主意。但这似乎有点麻烦。在最终修改其他模型之前,我需要检查所有内容。

似乎交易会在这里有所帮助,因为这将允许我同时检查和更新所有内容。

我正在使用 MongoDb。

我也是 SailsJS 的新手。我使用策略只是为了验证 authentication and insert logged user in the request (when I need it). For other verifications I use beforeCreate(...) Lifecycle callback

可能值得我引用 "Sails in action",因为我今天早上实际上正在阅读他们的政策最佳实践!

Policies shouldn't be a core part of your business logic Policies are not a good tool for structuring logic in your app. Using them this way makes them just as versatile as raw Express/Connect middleware-- and unfortunately it also makes them just as dangerous and developer-specific. If you use policies to help with queries, or create a complex chain of policies to manage permission systems in your applicaiton, you are likely to create a code base that is very difficult for any other developer to understand.

话虽如此,它继续建议:

Policies are not a good tool for structuring logic in your app. Using them this way makes them just as versatile as raw Express/Connect middleware-- and unfortunately it also makes them just as dangerous and developer-specific. If you use policies to help with queries, or create a complex chain of policies to manage permission systems in your applicaiton, you are likely to create a code base that is very difficult for any other developer to understand.

根据以上引述,我认为您质疑政策的使用是正确的。我认为你所描述的肯定是进入了第一句话所描述的世界(接近尾声)。

对我来说,我会尽可能地呼叫服务。本质上,如果我最终在多个文件中使用代码 3 次以上,那么它需要存在于服务中。如果代码是每个动作的自定义代码,那么放在控制器中就可以了。参数检查您是否属于控制器操作,除非您构建服务,否则您可以提供一些选项进行验证。

我检查了控制器中的参数,但您认为在什么时候在模型级别执行验证可能更有用?无论接收到什么,模型都需要满足它具有有效属性。也许将逻辑移到更接近您的模型并移出服务领域。

很高兴进一步讨论,sails 的好处是从来没有最佳实践,但有些人以前经历过痛苦,可以提供一些指导。

Don't look at parameters - Truly reusable policies should only look at req.session and the database- NOT at parameters! Relying on parameters makes your policy context-specific and only usable in very specialized circumstances. And in that case, why not just put the code in the relevant action(s)?