Code Error eka hadaganna help..

SL MULTIMEDIA TUTORIAL

Well-known member
  • Jul 27, 2020
    1,632
    6,937
    113
    United States
    මේකට තමයි Code කරන්න ඕනේ

    Use case

    A retail shop needs to maintain a product stock and purchase orders through a web

    application. The customers can submit their orders via the web application. As a backend developer, you

    need to develop an API to register a customer in the system.

    Below, please find a sample request and response JSON data for registering a customer.

    Sample Request JSON for registering a customer

    request


    Sample Response JSON for a successful registration
    response

    customerId: This should be the generated id from the database

    1. Update the database.js file with the required data definition (CREATE TABLE statement) to create the


    data table to store the data of customers
    Table name: customer
    2. Implement a new API in the server.js file to register a customer and add the data record to the table.

    The method of the API should be POST
    Include the proper error handling
    HTTP error codes
    Success: 201 Created
    An Error: 400 Bad Request
    Reference for HTTP error codes - Link
    3. Implement validation to validate POST data to the same API as below

    Email address validation
    Credit card number validation (12 digits)
    Resources:
    To test the expected outcome, you can pull the codebase from the below repository and edit the relevant files(database.js and server.js)
    .

    Git repository: https://github.com/opencourse5tutor/products-api

    Answer Submission Instructions

    Students should submit the following files.



    1. A screenshot of a successful customer registration using the Postman tool.
    2. database.js file
    3. server.js file
    mn code karapu Files tika

    server.js

    JavaScript:
    var express = require("express");
    var app = express();
    var db = require("./database1.js");
    var bodyParser = require("body-parser");
    const { request, response } = require("express");
    const res = require("express/lib/response");
    app.use(bodyParser.json());
    
    let HTTP_PORT = 8080;
    
    app.listen(HTTP_PORT, () => {
        console.log("Server is running on %PORT%".replace("%PORT%", HTTP_PORT))
    });
    
    app.post("/api/customers/", (req, res, next) => {
    
        try {
            var errors = []
    
            if (!req.body) {
                errors.push("An invalid input");
            }
    
            const {
                name ,
                address,
                email ,
                dateOfBirth ,
                gender,
                age ,
                cardHolderName ,
                cardNumber,
                expiryDate,
                cvv ,
                timeStamp
            } = req.body;
            var sql = 'INSERT INTO customers (name,address,email,dateOfBirth,gender,age,cardHolderName,cardNumber,expiryDate,cvv,timeStamp) VALUES (?,?,?,?,?,?,?,?,?,?,?)'
            var params = [name,address,email,dateOfBirth,gender,age,cardHolderName,cardNumber,expiryDate,cvv,timeStamp]
     
    
              db.run(sql, params, function (err, result) {
    
                if (err) {
                    return;
                } else {
    
                    res.json({
                        "message": "customer " + req.body.name +" registered",
                        "customerid": this.lastID
                    })
                }
    
            });
               
        }catch (E) {
                res.status(400).send(E);
        }
     });
    
    app.get("/api/customers/:customerid", (req, res, next) => {
    
        try {
            var sql = "select * from customers WHERE customerid =?"
            var params = [req.params.customerid]
            db.all(sql, params, (err, rows) => {
                if (err) {
                    res.status(400).json({ "error": err.message });
                    return;
                }
                res.json({
                    "message": "success",
                    "data": rows
                })
            });
        } catch (E) {
            res.status(400).send(E);
        }
    });
    
    
    app.get("/api/customers", (req, res, next) => {
    
        try {
            var sql = "select * from customers"
            var params = []
            db.all(sql, params, (err, rows) => {
                if (err) {
                    res.status(400).json({ "error": err.message });
                    return;
                }
                res.json({
                    "message": "success",
                    "data": rows
                })
            });
        } catch (E) {
            res.status(400).send(E);
        }
    });
    
    app.patch("/api/customers/:customerid", (req, res, next) => {
        const {
                name,
                address,
                email ,
                dateOfBirth ,
                gender,
                age ,
                cardHolderName ,
                cardNumber,
                expiryDate,
                cvv ,
                timeStamp
        } = req.body;
            db.run(`UPDATE customers set name =?,address=?,email=?,dateOfBirth=?,gender=?,age=?,cardHolderName=?,cardNumber=?,expiryDate=?,cvv=?,timeStamp=? WHERE customerid = ?`,
        [name,address,email,dateOfBirth,gender,age,cardHolderName,cardNumber,expiryDate,cvv,timeStamp,req.params.customerid],      
            function (err, result) {
                if (err) {
                    res.status(400).json({ "error": res.message })
                    return;
                }
                res.status(200).json({ "updated customerid": req.params.customerid })
            });
    });
    
    app.delete("/api/customers/:customerid", (req, res, next) => {
        try {
            db.run('DELETE FROM customers WHERE customerid = ?',
                req.params.customerid,
                function (err, result) {
                    if (err) {
                        res.status(400).json({ "error": res.message })
                        return;
                    }
                    res.json({ "message": "deleted customer id "+ req.params.customerid})
                });
        } catch (E) {
            res.status(400).send(E)
        }
    
    });


    database.js

    JavaScript:
    var sqlite3 = require('sqlite3').verbose();
    var md5 = require('md5');
    
    const DBSOURCE = 'db.sqlite';
    
    let db = new sqlite3.Database(DBSOURCE, (err) => {
      if (err) {
        // Cannot open database
        console.error(err.message);
        throw err;
      } else {
        console.log('Connected to the SQlite database.');
        db.run(
          `CREATE TABLE customers (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                customerName text,
                address text,
                email VARCHAR,
                dateofBirth VARCHAR,
                gender VARCHAR,
                age INTEGER,
                cardHolderName text,
                expirytdate VARCHAR,
                cvv INTEGER,
                timpStamp text
                )`,
          (err) => {
            if (err) {
              // Table already created
            } else {
              // Table just created, creating some rows
              var insert =
                ' INSERT INTO customers (customerName,address, email, dateofBirth, gender, age,cardHolderName,expirytdate,cvv , timpStamp )  VALUES (?,?,?,?,?,?,?,?,?,?)';
              db.run(insert, [
               
                'Jems Watson',
                'No 324/A ra de Mel Road , kadawataha',
                '[email protected]',
                '2002.02.25',
                'male',
                '20',
                'J.watson',
                '425678588956',
                '12/2026',
                '245',
                '2022-12-31 23:59:59',
              ]);
            }
          }
        );
      }
    });


    mn request damme Insomnia eken mehema error ekak enawa . :sorry:

    6b49d8883ec8f892f5efa.jpg
     
    Last edited:

    HAneo

    Well-known member
  • Jan 30, 2007
    12,970
    29,167
    113
    Homagama
    මේකට තමයි Code කරන්න ඕනේ

    Use case

    A retail shop needs to maintain a product stock and purchase orders through a web

    application. The customers can submit their orders via the web application. As a backend developer, you

    need to develop an API to register a customer in the system.

    Below, please find a sample request and response JSON data for registering a customer.

    Sample Request JSON for registering a customer

    request


    Sample Response JSON for a successful registration
    response

    customerId: This should be the generated id from the database

    1. Update the database.js file with the required data definition (CREATE TABLE statement) to create the


    data table to store the data of customers
    Table name: customer
    2. Implement a new API in the server.js file to register a customer and add the data record to the table.

    The method of the API should be POST
    Include the proper error handling
    HTTP error codes
    Success: 201 Created
    An Error: 400 Bad Request
    Reference for HTTP error codes - Link
    3. Implement validation to validate POST data to the same API as below

    Email address validation
    Credit card number validation (12 digits)
    Resources:
    To test the expected outcome, you can pull the codebase from the below repository and edit the relevant files(database.js and server.js)
    .

    Git repository: https://github.com/opencourse5tutor/products-api

    Answer Submission Instructions

    Students should submit the following files.



    1. A screenshot of a successful customer registration using the Postman tool.
    2. database.js file
    3. server.js file
    mn code karapu Files tika

    server.js

    JavaScript:
    var express = require("express");
    var app = express();
    var db = require("./database1.js");
    var bodyParser = require("body-parser");
    const { request, response } = require("express");
    const res = require("express/lib/response");
    app.use(bodyParser.json());
    
    let HTTP_PORT = 8080;
    
    app.listen(HTTP_PORT, () => {
        console.log("Server is running on %PORT%".replace("%PORT%", HTTP_PORT))
    });
    
    app.post("/api/customers/", (req, res, next) => {
    
        try {
            var errors = []
    
            if (!req.body) {
                errors.push("An invalid input");
            }
    
            const {
                name ,
                address,
                email ,
                dateOfBirth ,
                gender,
                age ,
                cardHolderName ,
                cardNumber,
                expiryDate,
                cvv ,
                timeStamp
            } = req.body;
            var sql = 'INSERT INTO customers (name,address,email,dateOfBirth,gender,age,cardHolderName,cardNumber,expiryDate,cvv,timeStamp) VALUES (?,?,?,?,?,?,?,?,?,?,?)'
            var params = [name,address,email,dateOfBirth,gender,age,cardHolderName,cardNumber,expiryDate,cvv,timeStamp]
     
    
              db.run(sql, params, function (err, result) {
    
                if (err) {
                    return;
                } else {
    
                    res.json({
                        "message": "customer " + req.body.name +" registered",
                        "customerid": this.lastID
                    })
                }
    
            });
              
        }catch (E) {
                res.status(400).send(E);
        }
     });
    
    app.get("/api/customers/:customerid", (req, res, next) => {
    
        try {
            var sql = "select * from customers WHERE customerid =?"
            var params = [req.params.customerid]
            db.all(sql, params, (err, rows) => {
                if (err) {
                    res.status(400).json({ "error": err.message });
                    return;
                }
                res.json({
                    "message": "success",
                    "data": rows
                })
            });
        } catch (E) {
            res.status(400).send(E);
        }
    });
    
    
    app.get("/api/customers", (req, res, next) => {
    
        try {
            var sql = "select * from customers"
            var params = []
            db.all(sql, params, (err, rows) => {
                if (err) {
                    res.status(400).json({ "error": err.message });
                    return;
                }
                res.json({
                    "message": "success",
                    "data": rows
                })
            });
        } catch (E) {
            res.status(400).send(E);
        }
    });
    
    app.patch("/api/customers/:customerid", (req, res, next) => {
        const {
                name,
                address,
                email ,
                dateOfBirth ,
                gender,
                age ,
                cardHolderName ,
                cardNumber,
                expiryDate,
                cvv ,
                timeStamp
        } = req.body;
            db.run(`UPDATE customers set name =?,address=?,email=?,dateOfBirth=?,gender=?,age=?,cardHolderName=?,cardNumber=?,expiryDate=?,cvv=?,timeStamp=? WHERE customerid = ?`,
        [name,address,email,dateOfBirth,gender,age,cardHolderName,cardNumber,expiryDate,cvv,timeStamp,req.params.customerid],     
            function (err, result) {
                if (err) {
                    res.status(400).json({ "error": res.message })
                    return;
                }
                res.status(200).json({ "updated customerid": req.params.customerid })
            });
    });
    
    app.delete("/api/customers/:customerid", (req, res, next) => {
        try {
            db.run('DELETE FROM customers WHERE customerid = ?',
                req.params.customerid,
                function (err, result) {
                    if (err) {
                        res.status(400).json({ "error": res.message })
                        return;
                    }
                    res.json({ "message": "deleted customer id "+ req.params.customerid})
                });
        } catch (E) {
            res.status(400).send(E)
        }
    
    });


    database.js

    JavaScript:
    var sqlite3 = require('sqlite3').verbose();
    var md5 = require('md5');
    
    const DBSOURCE = 'db.sqlite';
    
    let db = new sqlite3.Database(DBSOURCE, (err) => {
      if (err) {
        // Cannot open database
        console.error(err.message);
        throw err;
      } else {
        console.log('Connected to the SQlite database.');
        db.run(
          `CREATE TABLE customers (
                id INTEGER PRIMARY KEY AUTOINCREMENT,
                customerName text,
                address text,
                email VARCHAR,
                dateofBirth VARCHAR,
                gender VARCHAR,
                age INTEGER,
                cardHolderName text,
                expirytdate VARCHAR,
                cvv INTEGER,
                timpStamp text
                )`,
          (err) => {
            if (err) {
              // Table already created
            } else {
              // Table just created, creating some rows
              var insert =
                ' INSERT INTO customers (customerName,address, email, dateofBirth, gender, age,cardHolderName,expirytdate,cvv , timpStamp )  VALUES (?,?,?,?,?,?,?,?,?,?)';
              db.run(insert, [
              
                'Jems Watson',
                'No 324/A ra de Mel Road , kadawataha',
                '[email protected]',
                '2002.02.25',
                'male',
                '20',
                'J.watson',
                '425678588956',
                '12/2026',
                '245',
                '2022-12-31 23:59:59',
              ]);
            }
          }
        );
      }
    });


    mn request damme Insomnia eken mehema error ekak enawa . :sorry:

    6b49d8883ec8f892f5efa.jpg
    Yako Node js paththe POST dala uba Get kalama hari yayida
    Request eka POST dala arapan