简体   繁体   中英

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. However, I need to bring some of this logic to my NodeJS backend.

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. 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. 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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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