[英]How to structure/modularize my NodeJS server-side processing?
I have some processing logic that is currently in my AngularJS front end, modularized away into services in order to keep my controllers clean. 我的AngularJS前端中目前有一些处理逻辑,已模块化处理成服务,以保持控制器整洁。 However, I need to bring some of this logic to my NodeJS backend. 但是,我需要将某些逻辑带到我的NodeJS后端。
For example: 例如:
function processPost(post){ // In reality I have many many functions so I would like to modularize
if(post.verified == true){
post.status = 'Safe to trust!'
}
}
Where should I put this code in my backend and how can I modularize it? 我应该将该代码放在后端的什么地方,以及如何对其进行模块化? Should it be in the middleware or perhaps in my routes? 应该在中间件中还是在我的路由中?
I would put it in a commonjs module and then use it in the route. 我将其放在commonjs模块中 ,然后在路由中使用它。 This way you can use the exact same file/code on the server and client to verify the form data or whatever that function does. 这样,您可以在服务器和客户端上使用完全相同的文件/代码来验证表单数据或该功能执行的任何操作。 You'd have to load it on the client with something like systemjs or webpack. 您必须使用诸如systemjs或webpack之类的文件将其加载到客户端。 By the name of the function, I would guess you want to run that whenever the user posts a certain form, so putting it in the route, which is the code that will be called whenever they post, would make the most sense to me. 通过函数的名称,我想您想在用户发布某种表单时就运行它,因此将其放在路由中(这是他们发布时将被调用的代码)对我来说最有意义。
module.exports = function processPost(post){
if(post.verified == true){
post.status = 'Safe to trust!'
}
}
If you have multiple functions you'd like to export from one file you could do: 如果您要使用多种功能,则可以从一个文件中导出:
module.exports.processPost = function processPost(post){
if(post.verified == true){
post.status = 'Safe to trust!'
}
}
module.exports.processGet = function processGet(){
//Do work
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.