Is there a problem using objects like this in Node.js?

Asked

Viewed 84 times

2

I’m working on a system that contains a simple CRUD for tables from a Postgres database, in which new tables can be added eventually. So to avoid rewriting the controllers all the time, I did the following:

const repositorio1 = require('caminho/do/repositorio1');
const repositorio2 = require('caminho/do/repositorio2');
const repositorio3 = require('caminho/do/repositorio3');

const repos = {
'rep1' : repositorio1,
'rep2' : repositorio2,
'rep3' : repositorio3
}

//exemplo de um get
exports.get = async(req, res, next) => {
  let rep = (req.url).split('/')[1];
  try{
    var data = await repos[rep].get();
    res.status(200).send(data);
  }catch(e){
    res.status(500).send("erro");
  }
};

That way there’s only one controller for all repositories.

I lose performance with code written that way?

There’s a difference between me writing it like this?

const repos = {
'rep1' : require('caminho/do/repositorio1'),
'rep2' : require('caminho/do/repositorio2'),
'rep3' : require('caminho/do/repositorio3')
}

1 answer

4


Declaring constants before or having the require directly inside the object is irrelevant in terms of performance. It is good practice to have the requires declared at the beginning of the file, so you can choose that version which is how you have it.

Having only one controller is great. It’s DRY and therefore easy to maintain and is also a single function to have in memory. This type of functionality in an application is good not to have spread across multiple sites or functions, even if it is not repeated code.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.