beginner

Introducing views and transformers


Now we can work with our data but how do we send that data back to our clients? Using res.end? Pretty much, but we are going to wrap it inside, you guessed it, classes called Views(for returning views) and/or Transformers(for returning JSON/XML or other non-view data).

Let’s delete our old TestController.js and instead create new UserController.js. Inside we are going to create a couple of methods.

class UserController {
  async get({ req, res }) {
    return res.end(
      JSON.stringify({
        success: true,
        message: "Works.",
      }),
    );
  }
  create({ req, res }) {
    return res.end(
      JSON.stringify({
        success: true,
        message: "Works with data.",
      }),
    );
  }
  update({ req, res }) {
    return res.end(
      JSON.stringify({
        success: true,
        message: "Works with data.",
      }),
    );
  }

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

module.exports = UserController;

We see that we get duplicates of responses with message Works with data. so why don’t we move it to its own class? Create a new folder called Transformers in the root of the project and inside create SuccessTransformer.js

SuccessTransformer.js

class SuccessTransformer {
  transform(message) {
    return JSON.stringify({
      success: true,
      message: message,
    });
  }
}

module.exports = SuccessTransformer;

now update UserController.js

const SucessTransformer = require("../Transformers/SucessTransformer");

class UserController {
  async get({ req, res }) {
    return res.end(new SucessTransformer("Works."));
  }
  create({ req, res }) {
    return res.end(new SucessTransformer("Works with data."));
  }
  update({ req, res }) {
    return res.end(new SucessTransformer("Works with data."));
  }

  delete({ req, res }) {
    return res.end(new SucessTransformer("Works with data."));
  }
}

module.exports = UserController;

This looks much better and makes a lot more sense. We also need to update our routes.js

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

const userController = new UserController();

Route.get("users", (context) => {
  return userController.get(context);
});

Route.post("users", (context) => {
  return userController.post(context);
});

And now if you go to http://localhost:3334/users you will get result back.

Folder structure

index.js
routes.js
Route.js
Ignitor.js
Transformers(folder)
 - SucessTransformer.js
Models(folder)
 - User.js
Controllers(folder)
 - UserController.js
package.json
package-lock.json
.env
node_modules(folder)
Previous Introducing Models