Yesterday was tiring, I had to take a nap which is something I dont do all the time. 😅 I think that messed up my sleep though because I feel asleep at like 6am so I woke up late today… Naps are evil👿
Last night I made some good progress on optimizing the api for my client app. I removed like 400 more lines of code from the huge server.js file and separated it out👍🏽
I’m splitting it up into 3 file: Routes, Service, and a controller.
Routes will act as a cop who directs traffic, when the request hits that route it will just tell the code where to go, it doesnt have any logic, just calls a function in the service and returns the data. 🛣
The service is where all the fancy stuff happens, all my business logic is here🕴So this file will typically call a function in the controller, and then if it needs to manipulate the data or whatever this is where that happens. 💁🏽♂️
The controller, is the only file that accesses the database. All this does is make the query and return the data. Just like the routes there is not logic here. 😅
Separating the api like that is super useful, since my routes is the only file that uses express, lets say I wanted to switch that out for something else, I could and it wouldnt really affect the other files.👍🏽 Or maybe I want to switch the Database to be mongo db all I would have to do is rewrite the controller and not the other parts of the api, because all they’re expecting is the data they dont care where it comes from.
It took a while for me to understand this way of breaking down the api, so I figured Id share the TLDR to help, does anyone else write api’s like this? If you dont, then please share your way with us also👇🏽