avatarMarcos Henrique da Silva

Free AI web copilot to create summaries, insights and extended knowledge, download it at here

3901

Abstract

ns as <b>Middlewares</b> in our next article! Don’t worry much about <code>[]</code> now</p></blockquote><p id="7012">So, before finishing the routes, let’s create our controller. First of all, let’s create a folder called <code>controllers</code> inside the <code>users</code> folder. Now, create the file <code>users.controller.ts</code> and add the following code:</p><div id="97b9"><pre><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;</pre></div><div id="3fb6"><pre><span class="hljs-keyword">export</span> <span class="hljs-keyword">class</span> <span class="hljs-title class_">UsersController</span> {</pre></div><div id="fce1"><pre><span class="hljs-built_in">listUsers</span>(req: express.Request, res: express.Response) { res<span class="hljs-selector-class">.status</span>(<span class="hljs-number">200</span>)<span class="hljs-selector-class">.send</span>(Get to users); }</pre></div><div id="17c2"><pre>getUserById(req: express.Request, res: express.Response) { res.status(200).send(<span class="hljs-built_in">Get</span> <span class="hljs-keyword">to</span><span class="hljs-built_in"> user </span><span class="hljs-variable">${req.params.userId}</span>); }</pre></div><div id="3c26"><pre>createUser(req: express.Request, res: express.Response) { res.status(<span class="hljs-number">200</span>).send(Post to <span class="hljs-keyword">user</span> <span class="hljs-title">$</span>{req.<span class="hljs-keyword">params</span>.userId}); }</pre></div><div id="7ec7"><pre>patch(req: express.Request, res: express.Response) { res.status(<span class="hljs-number">200</span>).send(Patch to <span class="hljs-keyword">user</span> <span class="hljs-title">$</span>{req.<span class="hljs-keyword">params</span>.userId}); }</pre></div><div id="398b"><pre>put(req: express.Request, res: express.Response) { res.status(<span class="hljs-number">200</span>).send(Put to <span class="hljs-keyword">user</span> <span class="hljs-title">$</span>{req.<span class="hljs-keyword">params</span>.userId}); }</pre></div><div id="4cf3"><pre>removeUser(req: express.Request, res: express.Response) { res.status(<span class="hljs-number">200</span>).send(Delete to <span class="hljs-keyword">user</span> <span class="hljs-title">$</span>{req.<span class="hljs-keyword">params</span>.userId}); }</pre></div><div id="fe61"><pre>}</pre></div><blockquote id="2826"><p>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 ;)</p></blockquote><p id="292e">Great, now we can add the UsersController to the User’s routes! Let’s open back again the <code>user.routes.config.ts</code> and update the code:</p><div id="b20b"><pre><span class="hljs-keyword">import</span> {CommonRoutesConfig, configureRoutes} <span class="hljs-keyword">from</span> <span class="hljs-string">'../common/common.routes.config'</span>; <span class="hljs-keyword">import</span> {UsersController} <span class="hljs-keyword">from</span> <span class="hljs-string">'./controllers/users.controller'</span>;</pre></div><div id="939c"><pre><span class="hljs-keyword">import</span> express <span class="hljs-keyword">from</span> <span class="hljs-string">'express'</span>;</pre></div><div id="7ef9"><pre><span class="hljs-keyword">export</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">UsersRoutes</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">CommonRoutesConfig</span> <span class="hljs-title">implements</span> <span class="hljs-title">configureRoutes</span></span>{ constructor(ap

Options

p: express.<span class="hljs-type">Application</span>) { <span class="hljs-keyword">super</span>(app, '<span class="hljs-type">UsersRoute</span>'); <span class="hljs-keyword">this</span>.configureRoutes(); }</pre></div><div id="b858"><pre><span class="hljs-title function_">configureRoutes</span>(<span class="hljs-params"></span>) { <span class="hljs-keyword">const</span> usersController = <span class="hljs-keyword">new</span> <span class="hljs-title class_">UsersController</span>(); <span class="hljs-variable language_">this</span>.<span class="hljs-property">app</span>.<span class="hljs-title function_">get</span>(<span class="hljs-string">/users</span>, [ usersController.<span class="hljs-property">listUsers</span> ]);</pre></div><div id="947c"><pre>this.app.post(/users, [ usersController.createUser ])<span class="hljs-comment">;</span></pre></div><div id="1f6f"><pre>this.app.<span class="hljs-keyword">put</span>(/users/:userId, [ usersController.<span class="hljs-keyword">put</span> ]);</pre></div><div id="24a8"><pre><span class="hljs-keyword">this</span>.app.patch(<span class="hljs-string">/users/:userId</span>, [ usersController.patch ]);</pre></div><div id="b53a"><pre><span class="hljs-keyword">this</span>.app.<span class="hljs-keyword">delete</span>(<span class="hljs-string">/users/:userId</span>, [ usersController.removeUser ]); <span class="hljs-keyword">this</span>.app.get(<span class="hljs-string">/users/:userId</span>, [ usersController.getUserById ]); }</pre></div><div id="a55e"><pre>}</pre></div><p id="75f4">And that’s it, if you run <code>npm start</code> and the code should be working normally.</p><p id="232c">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 ;)</p><p id="d187">Thanks for reading and see you at the <a href="https://readmedium.com/another-expressjs-api-tutorial-for-2020-part-05-configuring-services-2fb8c64a437c">next article</a>!</p><div id="f620" class="link-block"> <a href="https://readmedium.com/another-expressjs-api-tutorial-for-2020-part-05-configuring-services-2fb8c64a437c"> <div> <div> <h2>Another ExpressJS API tutorial for 2020, part 05 — Configuring services</h2> <div><h3>At the part five of this articles we are going to configure services which will communicate between controllers and the…</h3></div> <div><p>medium.com</p></div> </div> <div> <div style="background-image: url(https://miro.readmedium.com/v2/resize:fit:320/1*eWYm3Dm7s0t8lLWYRW4pow.jpeg)"></div> </div> </div> </a> </div><p id="7f46">tips:</p><ul><li>the full code of this article is <a href="https://github.com/makinhs/expressjs-api-tutorial/tree/004-configurando-controller">HERE</a></li><li>don’t forget to use a nice app to test your API such as <a href="https://www.postman.com/">Postman</a> or <a href="https://insomnia.rest/">Insomnia</a></li><li>I know you still didn’t… Read the ExpressJS <a href="https://expressjs.com/en/4x/api.html">documentation</a>!</li><li>Book suggestion: <a href="https://amzn.to/3dgcWwI">Clean Code</a> and again <a href="https://amzn.to/2WGb1f5">Design Patterns</a></li><li>Brazilian? PT-BR Book suggestion: <a href="https://amzn.to/2wnMel1">Clean Code</a> and <a href="https://amzn.to/2U6uXWI">Design Patterns</a></li><li>Complete project is <a href="https://github.com/makinhs/expressjs-api-tutorial">here</a>!</li></ul></article></body>

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

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:

Recommended from ReadMedium