beginner

Introducing Controllers


Currently we are handling our main/business logic inside our routes.js file. We want to change this by extracting our main/business logic to separate files. These files are called Controllers.

Introducing Controllers

First we want to create a new folder Controllers and a new file TestController.js inside that folder. As you can see it is just a normal class. We moved our main/business logic from routes.js to these functions.

TestController.js

class TestController {
  getTest({ req, res }) {
    return res.end(
      JSON.stringify({
        success: true,
        message: "Works.",
      }),
    );
  }
  postTest({ req, res }) {
    return res.end(
      JSON.stringify({
        success: true,
        message: "Works with data.",
      }),
    );
  }
}

module.exports = TestController;

And in our routes.js we require that controller and since we are importing a class we must instantiate it which we immediately do. Later we can call a method from that controller and pass in a context paramater which is our name for object of {req,res}.

const Route = require("./Route.js");
const TestController = require("./Controllers/TestController.js");

const testController = new TestController();

Route.get("test", (context) => {
  return testController.getTest(context);
});

Route.post("test", (context) => {
  return testController.postTest(context);
});

Why?

Because organization matters, because separation of concerns matters. It would be a very bad idea to keep all of your logic inside of a same file similar to how it would be a very bad idea to have your cleaning products in your fridge, next to your food. Is it possible? Sure, but its not advised and a really bad idea.

Folder structure

index.js
routes.js
Route.js
Ignitor.js
Controllers(folder)
 - TestController.js
package.json
package-lock.json
.env
node_modules(folder)
Previous Creating NodeJS project
Next Introducing Models