Create List Products with Dummy Data in Nest JS

In this article, we will implement functionality to list products and to be able to click those products and display their data in a separate section.

Listing products

Let’s start by creating a new controller to implement the list products functionality.

Products controller

In src/ , create a new file called products.controller.ts , and fill it with the following code.

Let’s analyze the code by parts.

Analyze Code

@Controller('/products')

We use the @Controller decorator and pass in a path prefix (“/products”). This allows us to group a set of related routes and minimize repetitive code. All methods defined in this controller will automatically include the “/products” path prefix.

Analyze Code

static products = [

    {

        id: '1',

        name: 'TV',

        description: 'Best tv',

        image: 'game.png',

        price: '1000',

    },

products is an array that contains a set of products with its data. In the array index 0, we have the product with id=1 (the “TV”). We have four dummy products. Currently, they are stored as a static attribute of the ProductsController class. We will later retrieve product data from a MySQL database in upcoming chapters.

The index method gets the array of products and sends them to the products/index view to be displayed.

Products index view

In views/ , create a subfolder called products . Then, in views/products , create a new file called index.hbs , and fill it with the following code.

The important part of the previous code is the {{#each viewData.products}} . each is a hbs built-in helper which allows us to iterate over a list. We iterate through each product and display the product image and name. More information about hbs built-in helpers can be found here: https://handlebarsjs.com/guide/builtin-helpers.html.

Analyze Code

<a href="/products/{{id}}" class="btn bg-primary text-white">{{name}}</a>

Finally, we put a link to the product name. The link will route to a new ProductsController method (which will be defined later) and it requires a parameter to be sent. In this case, we send the product id of the current iterated product.

Showing a specific product

Products controller

In src/products.controller.ts , make the following changes in bold.

Modify Bold Code

import { Controller, Get, Render, Param } from '@nestjs/common';

@Controller('/products')

export class ProductsController {

    

    @Get('/')

    @Render('products/index')

    index() {

        

    }

    @Get('/:id')


    @Render('products/show')

    show(@Param() params) {

        const product = ProductsController.products[params.id - 1];

        const viewData = [];

        viewData['title'] = product.name + ' - Online Store';

        viewData['subtitle'] = product.name + ' - Product Information';

        viewData['product'] = product;

        return {

            viewData: viewData,

        };

    }

}


First, we import the Param decorator. This decorator will be used to collect route parameters later.

We link the show method to the (“/:id”) route. Because we include the ProductsController path prefix, the complete route is (“products/:id”). “/products/:id” takes a parameter called id . This parameter is the product id to identify which product data to show. For example, if we access “/products/1” URL, the application will display the data of the product with id=1.

The show method contains a params argument decorated with @Param() . @Param() makes the route parameters available as properties inside the method. We can access the id parameter by referencing params.id . Then, we extract the corresponding product (from the ProductsController.products array) based on the params.id value. We subtract one unit since we stored the product with id=1 in the ProductsController.products array index 0, the product with id=2 in the ProductsController.products array index 1, and so on. We then send the product data to the products/show view.

Product show view

In views/products , create a new file called show.hbs , and fill it with the following code

The with hbs helper dives into the viewData.product object and gives us direct access to the product properties( name , description , image , and price ). We show the product image , name , price , and description in the markup. Remember, we are using dummy data. This will change in upcoming chapters.

TIP: In the last examples, we have defined a structure to store our controllers, controllers’ methods, routes, and views. For example, the products/ route, is linked to the ProductsController index method, which displays the products/index view. Try to use this strategy across the entire project as it facilitates finding the views of the corresponding controllers’ methods and vice versa.

Introducing Nest Modules

Modules are classes annotated with a @Module() decorator. The @Module() decorator provides metadata that Nest uses to organize the application structure. Each application has at least one module, a root module. The root module is the starting point Nest uses to build the application. In our case, src/app.module.ts is our root module.

The @Module() decorator allows defining a set of properties:

  • controllers: the set of controllers in this module to be instantiated.
  • providers: the providers that will be instantiated by the Nest injector and shared at least across this module.
  • imports: the list of imported modules required in this module.
  • exports: the subset of providers provided by this module and available to other modules.

You can design small Nest applications which consist of only one module. However, for complex applications, it is recommended to employ multiple modules. We will split our Online Store application into four modules (detailed later).

Registering ProductsController in AppModule

Let’s register the ProductsController in our AppModule . In src/app.module.ts , make the following changes in bold.

We import our newly created ProductsController , and register it in the AppModule controllers property. This way, all the ProductsController routes will be available for access from the browser.

Updating links in Header

Now, let’s include the products links in the header. In views/layouts/app.hbs , make the following changes in bold.

Running the app

In the Terminal, go to the project directory, and execute the following:

Execute in Terminal

npm run start:dev

Now, you can go to the Products page and navigate to a specific product 

 


See Next Article Nest JS ...

Post a Comment for "Create List Products with Dummy Data in Nest JS"