NodeJS

What is NodeJS ?
Node.js is a cross-platform, open-source JavaScript runtime environment that can run on Windows, Linux, Unix, macOS, and more. Node.js runs on the V8 JavaScript engine, and executes JavaScript code outside a web browser. Node.js lets developers use JavaScript to write command line tools and for server-side scripting.The "node" stands for "Network Open Distributed Environment" and it represents a specific location in a network.

Install

We must install folowing packages.
constants.ts.
mkdir mynodeapp
cd mynodeapp
npm init -y
npm install cors
npm install dotenv
npm install express
npm install mongoose or npm install mysql
npm install @typegoose/typegoose --save-dev

Create Models in Project

We are using mongodbd in this project.
We should create object data type model.
                
                import { modelOptions, prop, getModelForClass } from '@typegoose/typegoose';
                  @modelOptions({ schemaOptions: { timestamps: true } })
                  export class Product {
                    public _id!: string;

                    @prop({ required: true })
                    public pid!: string;

                    @prop({ required: true })
                    public name!: string;

                    @prop({ required: true, unique: true })
                    public slug!: string;

                    @prop({ required: true })
                    public image!: string;

                    @prop({ required: true })
                    public brand!: string;

                    @prop({ required: true })
                    public category!: string;

                    @prop({ required: true })
                    public description!: string;

                    @prop({ required: true, default: 0 })
                    public price!: number;

                    @prop({ required: true, default: 0 })
                    public countInStock!: number;

                    @prop({ required: true, default: 0 })
                    public rating!: number;

                    @prop({ required: true, default: 0 })
                    public reviews!: number;
                  }

                  export const ProductClassModel = getModelForClass(Product);
                
              

Create Routes in Project

We should create routes productRouter
routers/productRouter
                
                // routers/productRouter 
import express from 'express'; import asyncHandler from 'express-async-handler'; import { ProductClassModel } from '../models/productModel'; export const productRouter = express.Router(); // /api/products productRouter.get( '/', asyncHandler(async (req, res) => { const products = await ProductClassModel.find(); res.json(products); }) ); // /api/pid/2 productRouter.get( '/pid/:pid', asyncHandler(async (req, res) => { const product = await ProductClassModel.findOne({ pid: req.params.pid }); if (product) { res.json(product); } else { res.status(404).json({ message: 'Product Not Found' }); } }) );
We should create route for fake date seeding to insert data in database. routers/seedRouter
                
                  // routers/seedRouter 
                  import express, { Request, Response } from 'express';
                  import asyncHandler from 'express-async-handler';
                  import { ProductClassModel } from '../models/productModel';
                  import { sampleProducts } from '../data';

                  export const seedRouter = express.Router();

                  seedRouter.get(
                    '/',
                    asyncHandler(async (req: Request, res: Response) => {
                      await ProductClassModel.deleteMany({});
                      const createProducts = await ProductClassModel.insertMany(sampleProducts);
                      res.json({ createProducts });
                    })
                  );
                
              

Create Types file

We should create types for data object model. types/Product.ts
                
                //types/Product.ts
                  export type Product = {
                    pid: string;
                    name: string;
                    slug: string;
                    category: string;
                    image: string;
                    brand: string;
                    price: number;
                    countInStock: number;
                    rating: number;
                    reviews: number;
                    description: string;
                  };
                
              

Main File (index.ts)

We should create main root file index.ts, where we implement for api logic. index.ts
Mongodb implementation in index.ts
                
                // index.ts
                  import cors from 'cors';
                  import dotenv from 'dotenv';
                  import express, { Request, Response } from 'express';
                  import { sampleProducts } from './data';  // check below
                  import mongoose from 'mongoose';
                  import { productRouter } from './routers/productRouter';
                  import { seedRouter } from './routers/seedRouter';

                  dotenv.config();
                  const app = express();
                  const MONGODB_URI = process.env.MONGODB_URI || 'mongodb://localhost/eshopcart';
                  mongoose.set('strictQuery', true);
                  mongoose
                    .connect(MONGODB_URI)
                    .then(() => {
                      console.log('Connected to mongodb');
                    })
                    .catch(() => {
                      console.log('Connection error with mongodb');
                    });

                  app.use(
                    cors({
                      credentials: true,
                      origin: ['http://localhost:5173'],
                    })
                  );

                  //If we have separate product router defined
                  app.use('/api/products', productRouter);

                  //Seeding fake data in mongodb using seeder
                  // app.use('/api/seed', seedRouter);

                  const PORT = 4000;

                  app.listen(PORT, () => {
                    console.log(`Server started at http://localhost:${PORT}`);
                  });

                  /* 
                  app.get('/api/products', (req: Request, res: Response) => {
                    res.json(sampleProducts);
                  });

                  app.get('/api/products/:pid', (req: Request, res: Response) => {
                    res.json(sampleProducts.find((item) => item.pid === req.params.pid));
                  });
                  */
                
              
We should have fake data file(data.ts).
                
                 //data.ts
                    import { Product } from './types/Product';
                    export const sampleProducts: Product[] = [
                      {
                        pid: '1',
                        name: 'Nike Slim Shirt',
                        slug: 'nike-slim-shirt',
                        category: 'Shirts',
                        image: '../images/p1.jpg',
                        brand: 'Nike',
                        price: 120,
                        countInStock: 10,
                        rating: 2.5,
                        reviews: 10,
                        description: 'high quality shirt',
                      },
                      {
                        pid: '2',
                        name: 'Adidas jeans',
                        slug: 'addidas-jeans',
                        category: 'Jeans',
                        image: '../images/p2.jpg',
                        brand: 'Addidas',
                        price: 799,
                        countInStock: 5,
                        rating: 1.5,
                        reviews: 12,
                        description: 'high quality jeans',
                      },
                      {
                        pid: '3',
                        name: 'Leecost Jackat',
                        slug: 'leecost-jackat',
                        category: 'Jackat',
                        image: '../images/p3.jpg',
                        brand: 'Leecost',
                        price: 1199,
                        countInStock: 8,
                        rating: 3.5,
                        reviews: 10,
                        description: 'high quality jackat',
                      },
                      {
                        pid: '4',
                        name: 'Zara Leather Shoe',
                        slug: 'zara-shoe',
                        category: 'Shoes',
                        image: '../images/p4.jpg',
                        brand: 'Leecost',
                        price: 490,
                        countInStock: 5,
                        rating: 5,
                        reviews: 8,
                        description: 'high quality leather shoe',
                      },
                    ];