DB Helper for controller with node

Hi,

I am writing an application using the MERN stack.

I find myself repeating the same controllers through my application read, list, delete, etc.

A lot of the code is repeated. I am wondering if anyone has a suggested work around. At first I thought classes - but with node I I understand that those are now discouraged and a more functional programming - however I am lost - does anyone have an example of what a class / object type approach would be for creating controllers that you could just pass the data through by way of functions? I would love to see how that might look like in practice … rather than rewriting pretty much the same list, read, create controllers for all of my different routes

Maybe like a controller function helper where you just pass the controller in for by way of parameters ?

In PHP I had a class called DB helpers and used it that way – passing in my parameters.- has anyone made anything like that with node and are able to share.

thx!
Karen

I don’t know if classes are really discouraged in Nodejs. I have never heard that.

As for repeat code, just extract what is repeated into a class or function and call that from the routes. In express you can put in function callbacks and have each route call the appropriate function. That could be a function that serves multiple routes.

You could also create a generic controller and have all the routes point at the same controller method.

Thanks, yes I am working on that. I think I can try to reduce some of this code. Apologies as I had meant to put in there React – -not node. I am using the fetch from the back axios etc and got confused between server and front end for a moment.

React code bloats up so quickly.

I will give the classes a try.

(Pardon the pun :slight_smile:
Karen

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.