Building an E-Commerce API Using Nestjs, SQLite, and TypeORM | by Arctype | Apr, 2022

Building an E-Commerce API using Nestjs, SQLite, and TypeORM

Nestjs is a cutting-edge Node.js framework for growing server-side functions which can be environment friendly, reliable, and scalable.

It’s easy to combine with NoSQL and SQL databases equivalent to MongoDB, Yugabyte, SQLite, Postgres, MySQL, and others. It helps common object-relational mappers equivalent to TypeORM Sequelize and Mongoose.

On this tutorial, we’ll create an e-commerce utility with SQLite and TypeORM. We’ll additionally take a look at Arctype, a strong SQL consumer and database administration device.

Let’s get began!

This tutorial is a hands-on demonstration to get you began. Make sure you’ve met the next necessities:

  • You’ve gotten Node (>= 10.13.0, aside from v13) put in
  • You’ve gotten a foundational data of JavaScript
  • Arctype put in

To get began with Nestjs, set up the Nestjs CLI with the command under:

npm i -g @nestjs/cli

As soon as the set up is accomplished, create a Nestjs venture with the command under:

nest new ecommerce

Select your npm because the bundle supervisor, hit the enter button, and look forward to Nest to put in the required packages to run this utility.

As soon as the set up is accomplished, change the listing to the venture folder with the command under:

cd ecommerce

Then open the venture listing in your favourite textual content editor or IDE. After that, open a brand new terminal, and run the server on improvement mode (this may allow sizzling reload and permits us to see potential errors on the console) with the command under:

npm run begin:dev

With the server up and working, open a brand new terminal window so that you don’t give up the server. It will assist you to see the impact of the adjustments made to the codebase all through this tutorial.

Now set up the next dependencies:

You are able to do this with the command under:

npm set up --save @nestjs/passport passport passport-local @nestjs/jwt passport-jwt @nestjs/typeorm typeorm sqlite3 bcrypt

Then set up the dev dependencies with the command under:

npm set up --save-dev @sorts/passport-local @sorts/passport-jwt @sorts/bcrypt

You possibly can seize a cup of espresso whereas the npm installs the packages. As soon as the set up is accomplished, let’s get our palms soiled.

With all the mandatory packages required to run the applying, let’s proceed to create the applying modules. To construct a clear and easily-maintained utility, you’ll generate separate modules for all of the options applied on this utility.

Since that is an e-commerce utility, you’ll have authentication, cart, merchandise, and orders. All these shall be in their very own separate modules. Let’s begin with the authentication module.

Create authentication module

Generate an authentication module with the command under:

nest g module auth

The above command creates an auth folder within the venture’s src listing with the mandatory boilerplates and registers the module within the venture root module(app.module.ts file).

Subsequent, create a product, cart, and order module with the command under:

#Create a product module
nest g module product

#Create cart module
nest g module cart

#Create cart module
nest g module order

The above will create a product, cart, and order folder within the venture’s src folder with the essential boilerplates and register these modules within the venture’s root app module.

With the app modules put in, arrange TypeORM to attach your utility to SQLite Database and create your module entities. To get began, open the app.module.ts and configure your SQLite database with the code snippets under:

imports: [

TypeOrmModule.forRoot(
type :"sqlite",
database: "shoppingDB",
entities: [__dirname + "/**/*.entity.ts,.js"],
synchronize: true
)
],

Within the above code snippet, you linked the applying to an SQLite database utilizing the TypeORM forRoot, specifying the database sort, database identify, and the situation the place Nestjs can discover the mannequin entities.

As soon as the server refreshes, it’s best to see a shoppingDB file created within the root listing of this venture.

With the database setup, let’s create the entity fashions for our app modules. We’ll begin with the auth module. Generate an entity file within the auth module folder with the command under:

nest generate class auth/person.entity –flat

Then add the code snippet under to outline the person desk properties with the code snippet under:

Within the code snippet, you imported the decorators required to arrange your database desk. You additionally imported the cartEntity and orderEntity class which you’ll create shortly. Utilizing the typeorm decorator, we outlined the database properties of the person’s mannequin.

Lastly, we created one-to-one and one-to-many relationships between the person’s entity and the cartEntity and orderEntity. This manner, you may affiliate a cart merchandise with a person. The identical applies to the person’s order.

Subsequent, create the product entity class with the command under:

nest generate class product/product.entity –flat

The above command will generate a product.entity.ts file within the merchandise module folder.

Now configure the product desk properties with the code snippet under:

Within the above code snippet, we configured the properties of the product desk and created a one-to-many relationship with the cart entity.

Then create the cart entity with the command under:

nest generate class cart/cart.entity –flat

The above command will generate a cart.entity.ts file within the cart module folder. Now add the code snippet under to the file you created to configure the cart desk properties.

Within the above code snippet, you configured the properties of the cart desk and created a many-to-one relationship between the cart entity and a many-to-one relationship with the person’s entity.

Lastly, create the order entity with the command under:

nest generate class order/order.entity –flat

The above command will generate an order.entity.ts file within the order module folder. Open the order.entity.ts and configure the database desk with the command under:

Within the above code snippet, you created a one-to-one relationship between the person’s entity and a one-to-many relationship with the product’s entity.

At this level, your database entities are set and linked. Now create your small business logic to retailer data on these entities.

Now create the companies for the modules on this utility. Right here you’ll permit the admin so as to add merchandise to the product desk, authenticate customers, permit customers so as to add the merchandise within the retailer to the cart, and order the product by way of their cart.

Create the auth service

To create the auth service, run the command under to generate the service for the auth module.

nest generate service auth/service/auth --flat

The above command will generate an auth.service.ts file within the src/auth/service folder. Now open the auth.service.ts file and add the code snippet under:

Within the above code snippet, you imported InjectRepository, Repository decorator, JwtService, and bcrypt modules. Then, utilizing the InjectRepository decorator, you made the person.entity class out there within the auth service, offering the tactic to carry out CRUD operations in your person.entity.

Then, create a signup methodology to permit customers to register within the utility with the code snippet under:

async signup(person: Customers): Promise<Customers> 
const salt = await bcrypt.genSalt();
const hash = await bcrypt.hash(person.password, salt);
person.password = hash
return await this.userRepository.save(person);

Now create the validateUser methodology to validate the customers’ particulars and the login methodology to generate a jwt token for the authenticated person.

Now, we are able to implement our Passport native authentication technique. Create a file known as native.technique.ts within the auth module folder, and add the next code:

Within the above code snippet, you’ve applied a passport-local technique. There aren’t any configuration choices, so our constructor merely calls tremendous() with out an choices object.

You’ve additionally applied the validate() methodology. Passport will name the confirm operate for every technique utilizing an applicable strategy-specific set of parameters. For the local-strategy, Passport expects a validate() methodology with the next signature: validate(username: string, password:string): any.

Then create a jwt-auth.guard.ts file within the auth module folder and outline a customized auth guard with the code snippet under:

import  Injectable  from '@nestjs/widespread';
import AuthGuard from '@nestjs/passport';

@Injectable()
export class LocalAuthGuard extends AuthGuard('native')

You’ll use the AuthGuard created within the code snippet to guard your API routes from unauthorized customers.

Now create a jwt-strategy file within the auth module folder to authenticate customers and generate jwt tokens for logged in customers with the code snippet under:

Then. configure the jwt module within the auth.module.ts file within the auth module folder. Earlier than that, create a constants.ts file in the identical auth module folder to outline a jwt secret with the code snippet under:

export const jwtConstants = 
secret: 'wjeld-djeuedw399e3-uejheuii33-4jrjjejei3-rjdjfjf',

You possibly can generate a extra secured jwt secret on manufacturing, however we’ll use this one for demonstration sake.

Now, import all of the required modules in your auth.module.ts file with the code snippet under:


import JwtModule from '@nestjs/jwt';
import jwtConstants from './constants';
import JwtStrategy from './jwt.technique';
import PassportModule from '@nestjs/passport';
import LocalStrategy from './native.technique';
import TypeOrmModule from '@nestjs/typeorm';
import Customers from './person.entity';

Then, within the array of imports, configure jwt with the code snippet under:


imports: [
PassportModule,
JwtModule.register(
secret: jwtConstants.secret,
signOptions: expiresIn: '60m' ,
),

In the above code snippet, we add the PassModule package to allow passport to handle the users’ authentication and configured jwt using the JwtModule register method. We pass in the secret we created in the constants file and specify the generated token’s expiration time (You can reduce or increase the time depending on the use case).

With the auth service setup, generate a product service with the command below:

nest generate service product/service/product

Now open the product.service.ts file generated by the above command in the product module and add the code snippets below:

In the above snippet, we created our CRUD services. The create, update, and delete methods are restricted from the users. Only the admin can create a product, delete or update a product.

Now, open the product.module.ts file and make the product entity accessible with the code snippet below:

imports: [TypeOrmModule.forFeature([ProductEntity])],

At this level, the admin can add merchandise to the database, and authenticated customers can see all out there merchandise. Now let’s permit the customers so as to add the objects they wish to the cart. To get began, generate a Cart service with the command under:

nest generate service cart/service/cart –flat

Then open the cart.service.ts file generated by the command, and add the code snippet under:

You imported the modules required to create a Nest.js service within the above code snippet. We additionally imported them right here because you created a relationship between the cart, person, and product entities. Then, you make a constructor methodology to bind these entities to the CartService class. Now, create a way so as to add an merchandise to the cart.

Within the above code snippet, you created an addToCart methodology that takes the productId, amount, and person as arguments. Then verify if the person has the merchandise already of their cart. In that case, you increment the amount and replace the whole worth of that merchandise. Else, you add the merchandise to the person’s cart.

Subsequent, make the cartEntity, productEntity , userentity, and the productService accessible within the cartService by registering them within the cart.module.ts file with the code snippet under:

Lastly, create a getItemsInCart methodology that takes a person as an argument to return all of the carts belonging to a selected person.

async getItemsInCard(person: string): Promise<CartEntity[]> 
const userCart = await this.cartRepository.discover( relations: ["item",'user'] );
return (await userCart).filter(merchandise => merchandise.person.username === person)

When customers are achieved purchasing, they’ll order the objects of their cart. Generate an order service with the command under:

nest generate service order/service/order –flat

Now open the order.service.ts file generated from working the above command and add the code snippet under:

You imported the modules required to create a Nest.js service within the above code snippet. We additionally imported them right here because you created a relationship between the cart, person, and product entities. Then, you created a constructor methodology to bind these entities to the OrderService class. Now, create a way to order the objects within the person’s cart.

Then create one other methodology to get a person’s order from the array of orders from the database with the code snippet under:


async getOrders(person: string): Promise<OrderEntity[]>
const orders = await this.orderRepository.discover( relations: ['user'] );
return orders.filter(order => order.person?.username === person)

}

Lastly, open the order.module.ts file and make the customers, product, and cart entities accessible within the orderService with the code snippet under:

With the applying companies efficiently created, let’s create the API routes for the app companies.

Create the auth controller

Generate an auth controller with the command under:

nest generate controller auth/controller/auth –flat

Now open the auth.controller.ts file generated from working the above command and configure the auth routes with the code snippet under:

Create the product controller

With the auth controller routes configured, generate a product controller with the command under:

nest generate controller product/controller/product –flat

Open the product.controller.ts file generated from working the above command and configure the product routes with the code snippet under:

Within the above code snippet, you outlined the CRUD routes for the product service. We used the UseGuard decorator passing your JwtAuthGaurd to guard the routes from unauthorized customers.

Create the cart controller

Now, generate a cart controller with the command under:

nest generate controller cart/controller/cart –flat

Then open the cart.controller.ts file generated from working the above command and configure the cart routes with the code snippet under:

Create the order controller

With the cart routes configured, create an order controller with the command under:

nest generate controller order/controller/order –flat

Then open the order.controller.ts file generated from working the above command and configure the cart routes with the code snippet under:

At this level, all of your API routes have been configured.

Now let’s check them out utilizing Postman. The outcomes of some exams are proven under:

Building an E-Commerce API using Nestjs, SQLite, and TypeORM
Building an E-Commerce API using Nestjs, SQLite, and TypeORM
Building an E-Commerce API using Nestjs, SQLite, and TypeORM

Be happy to check the opposite routes and mess around with the code here on Github.

Arctype is an SQL consumer and database administration device that’s enjoyable to make use of. It permits you to have a visible illustration of your database tables, and you’ll carry out the CRUD operations listing in your database utilizing Arctype. Connecting Arctype to an SQLite database is a simple course of. To get began, comply with the steps under:

First, launch Arctype. You’ll see a display just like the one under, permitting you so as to add your credentials:

Building an E-Commerce API using Nestjs, SQLite, and TypeORM

Click on on the SQLite tab. It will carry up the display under:

Building an E-Commerce API using Nestjs, SQLite, and TypeORM

Click on on the Select SQLite File button and navigate to your venture folder. Choose the applying database file and press the open button. Press the save button, and it’s best to see your database entities, as proven within the screenshot under.

Building an E-Commerce API using Nestjs, SQLite, and TypeORM

By constructing a demo venture, we’ve realized how one can make an e-commerce utility utilizing Nestjs and SQLite Database. First, we began with the introduction of NestJS. Then, we created a NestJS utility, linked the applying to an SQLite database utilizing TypeORM, and carried out CRUD operations.

Now that you just’ve gotten the data you search, be happy so as to add additional performance to the applying.

More Posts