jeudi 14 juin 2018

Node Express writing API functions styles/design patterns best practice

I use the MEAN stack and I am writing some REST API functions to manipulate data with routing functions...

I just have the problem that I am quite new to REST Api and the MEAN stack and also Javascript... so I was wondering, that there are many different styles of writing those javascript functions, e.g. to get some data (and even how to do data manipulation, e.g by mongoose /mongoDB driver api function like aggregate / find, or doing the selection or filtering of data manually with javascript). Just to show some examples:

exports.getTestbyIDRange = function(req, res) {
    Test.aggregate([{"$match": {"$and": [{ "_id": {"$gte": +req.params.start, "$lte": +req.params.end}}]}}])
    //Test.find({"_id": {"$gte": Number(req.params.start), "$lte": Number(req.params.end)}})
    .exec(function(err, demo) {
        console.log("Anzahl gefundener Dokumente: ", demo.length)
        res.json(demo)
        for (let elem of demo) {
            console.log("ID: ", elem["_id"])    
        }   }   )   }

here, after the query I am using .exec(function..., but I also have seen ..,function(err, Test) {...} or a then-clause:

 }).then( doc => {
  // do something with matched document
}).catch(e => { console.err(e); res.send(e); })

So I am quite confused, is there a "best practice" style approach / design pattern for writing those functions? Or are all those styles equivalent? Which is best in terms of error handling? Or in case of errors / error handling, which is best to continue your app in case of some minor errors? I don't want my backend to get stuck or hang up.... Is there maybe some good literature to find online about styles?

Second question: When writing queries or data aggregation operations, should I do it with mongodb operations like find and aggregate, or can I also do it with plain javascript code ? (I find that sometimes easier because I am quite new to MongoDB) The thing here is that my backend functions are all running on the same server like where my MongoDB is sitting, so its basically localhost, that means it shouldnt be too bad performance when retrieving complete documents from the server and then doing javascript code on it, otherwise if it would be by network, then it's understandable that I should do database operations with db drivers first...

Aucun commentaire:

Enregistrer un commentaire