Another ExpressJS API tutorial for 2021, part 04— Configuring controllers

Marcos Henrique da Silva
4 min readMar 18, 2020

In our article number 4 we are going to configure controllers for our API using ExpressJS!

Hi, if you are arriving to this series of articles for the first time then here is what you are missing: This is a series of small articles that will guide you up to build an API using ExpressJS with Typescript.

Just as a quick overview, here is the series of articles that we are writing:

Now that we made all the overview, let’s start on the controllers!

At our last article, we finished the routes configuration for an USER resource. You can grab the code here.

Our target now is to build a structure that would work for better code maintenance and to easy it up the way we will read the code.

We have now something like the following:

this.app.get(`/users`, (req: express.Request, res: express.Response) => {
res.status(200).send(`List of users`);
});

Using ExpressJS, we first define the HTTP method (*get* in this case), then we pass the name of the endpoint (‘/users’) and after we pass a function that will handle the request. But, for a standard of coding, it is a nice idea to use the routes configuration file just to set up the name of the endpoints and who are the responsible of dealing with it. This last part we will call as Controller.

ExpressJS also allows us to pass several functions at the request in order to do specific handlings before sending an answer to the client.

What we want to do is the following:

this.app.get(`/users`, [
UserController.listUsers
]);

We are now passing an array [] and using a UserController (that we will create now)

We will be using more functions as Middlewares in our next article! Don’t worry much about [] now

So, before finishing the routes, let’s create our controller. First of all, let’s create a folder called controllers inside the users folder. Now, create the file users.controller.ts and add the following code:

import express from 'express';export class UsersController {listUsers(req: express.Request, res: express.Response) {
res.status(200).send(`Get to users`);
}
getUserById(req: express.Request, res: express.Response) {
res.status(200).send(`Get to user ${req.params.userId}`);
}
createUser(req: express.Request, res: express.Response) {
res.status(200).send(`Post to user ${req.params.userId}`);
}
patch(req: express.Request, res: express.Response) {
res.status(200).send(`Patch to user ${req.params.userId}`);
}
put(req: express.Request, res: express.Response) {
res.status(200).send(`Put to user ${req.params.userId}`);
}
removeUser(req: express.Request, res: express.Response) {
res.status(200).send(`Delete to user ${req.params.userId}`);
}
}

For now it seems that we just removed code from the routes file and put into the Controller without coding anything further. For this article we won’t go much further but in the future articles we are going to develop more coding using this approach. Just keep following it ;)

Great, now we can add the UsersController to the User’s routes! Let’s open back again the user.routes.config.ts and update the code:

import {CommonRoutesConfig, configureRoutes} from '../common/common.routes.config';
import {UsersController} from './controllers/users.controller';
import express from 'express';export class UsersRoutes extends CommonRoutesConfig implements configureRoutes{
constructor(app: express.Application) {
super(app, 'UsersRoute');
this.configureRoutes();
}
configureRoutes() {
const usersController = new UsersController();
this.app.get(`/users`, [
usersController.listUsers
]);
this.app.post(`/users`, [
usersController.createUser
]);
this.app.put(`/users/:userId`, [
usersController.put
]);
this.app.patch(`/users/:userId`, [
usersController.patch
]);
this.app.delete(`/users/:userId`, [
usersController.removeUser
]);
this.app.get(`/users/:userId`, [
usersController.getUserById
]);
}
}

And that’s it, if you run npm start and the code should be working normally.

In the next article we are going to talk and implement properly the user controller to have it working better. We will also be using a concept of services to add a temporary database that in one of the lates articles to be changed to a Mongo database. Hope to see you all there ;)

Thanks for reading and see you at the next article!

tips:

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

No responses yet

Write a response