DEV Community

Viraj Nirbhavane
Viraj Nirbhavane

Posted on

3 2

Controllers

A GET request route set up in a seperate route File instead of the server.js file.

/** greetingRoute.js */ 
...
router.get('/', (req,res) => {
   res.status(200).json({ message: "Greetings!"});
});
...
Enter fullscreen mode Exit fullscreen mode

We could set up routes like this, they aren't doing much currently but they are set up. We could proceed to add our functionality in the body of these callback functions but it's much better practice to create a controller and have your functions there.

So, in the backend folder that we had, create a controllers folder and add a file for the corresponding controller. Lets say, greetingController.js

Here, we can create some functions. For instance, lets have a getGreeting function

/** greetingController.js */

const getGreeting = (req,res) => {
    res.status(200).json({ message: "Greetings!"});
}

module.exports = {
    getGreeting,
}
Enter fullscreen mode Exit fullscreen mode

We need to export it in order to use it in our routes file.
The modules.exports is a Object here because we might wanna add more functions to it later as routes grow.

So, now in our routes file we need to require it.

/** greetingRoute.js */
...
const { getGreeting } = require('../controllers/greetingController.js');
...

router.get('/', getGreeting);

...
Enter fullscreen mode Exit fullscreen mode

Notice how we replaced the callback function body with the getGreeting function that we pulled in via require above.
And it should still work!

You wanna do these with rest of the routes as well and clear the clutter from the routes file as well.

And when you are done with all the routes, you can chain same routes but different request types together, like so

...

router.route('/').get(getGreeting).post(setGreeting);
router.route('/:id').update(updateEntity).delete(deleteEntity);

...
module.exports = router;
Enter fullscreen mode Exit fullscreen mode

That's it for this one. Leave a like!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Billboard image

Try REST API Generation for MS SQL Server.

DevOps for Private APIs. With DreamFactory API Generation, you get:

  • Auto-generated live APIs mapped from database schema
  • Interactive Swagger API documentation
  • Scripting engine to customize your API
  • Built-in role-based access control

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay