问题描述:

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
}
相关阅读:
Top