Commit 6bbb7984 authored by dangdoan's avatar dangdoan

fix test and clean code

parent 6bdf9455
......@@ -15,15 +15,15 @@ execute query in file mysql.sql
####
use the following api:
http://localhost:3000/api/v1.0/products : for list all products
http://localhost:3000/api/products : for list all products
http://localhost:3000/api/v1.0/products?currentPage=1&pageSize=2: for lis list all products with paging
http://localhost:3000/api/products?page=1&size=2: for lis list all products with paging
http://localhost:3000/api/v1.0/products: with post method for create product
http://localhost:3000/api/products: with post method for create product
http://localhost:3000/api/v1.0/products/{code}: with put method for update product
http://localhost:3000/api/products/{code}: with put method for update product
http://localhost:3000/api/v1.0/products/p003002: with delete method for delete product by code
http://localhost:3000/api/products/p003002: with delete method for delete product by code
http://localhost:3000/api/v1.0/products?sort={name}&dir={desc/asc}: for get all product with sorting
http://localhost:3000/api/products?sort={name}&dir={desc/asc}: for get all product with sorting
####
......@@ -6,6 +6,8 @@
"DB_USER": "root",
"DB_PASS": null,
"DB_HOST": "127.0.0.1",
"DB_PORT": 3306
"DB_PORT": 3306,
"DIALECT": "mysql",
"OPERATORSALIASESE": 0
}
}
\ No newline at end of file
const ProductProvider = require('../../provider/productProvider');
const { sendOK, sendError } = require('../../helper/response');
class product {
constructor() {
this.producProvider = new ProductProvider()
}
init(router) {
const self = this;
console.log("route")
router
.route("")
.get(async function (req, res, next) {
await self.getProducts(req, res, next);
});
router
.route("/:code")
.get(async function (req, res, next) {
await self.getByCode(req, res, next);
});
router
.route("")
.post(async function (req, res, next) {
await self.createProduct(req, res, next);
});
router
.route("/:code")
.put(async function (req, res, next) {
await self.updateProduct(req, res, next);
});
router
.route("/:code")
.delete(async function (req, res, next) {
await self.deleteProduct(req, res, next);
});
}
async getProducts(req, res, next) {
const self = this;
try {
const currentPage = parseInt(req.query.currentPage) || 1
const pageSize = parseInt(req.query.pageSize) || 10
// sort & dir
let sort = req.query.sort || "id"
let dir = req.query.dir || "asc"
const lstResult = await self.producProvider.getAll(currentPage, pageSize, sort, dir);
lstResult['totalPages'] = Math.ceil(lstResult['count'] / pageSize);
lstResult['currentPage'] = currentPage
return res.status(200).json(sendOK(lstResult));
} catch (error) {
console.log(error);
res.status(500).json(sendError(error.message))
}
}
async getByCode(req, res, next) {
const self = this;
try {
const result = await self.producProvider.getByCode(req.params);
return res.status(200).json(sendOK(result));
} catch (error) {
console.log(error);
res.status(500).json(sendError(error.message))
}
}
async createProduct(req, res, next) {
const self = this;
try {
let body = req.body;
body.createdAt = new Date;
const result = await self.producProvider.post(body);
return res.status(200).json(sendOK(result));
} catch (error) {
console.log(error);
res.status(500).json(sendError(error.message))
}
}
async updateProduct(req, res, next) {
const self = this;
try {
let body = req.body;
body.updatedAt = new Date;
const result = await self.producProvider.put(body, req.params.code);
return res.status(200).json(sendOK(result));
} catch (error) {
console.log(error);
res.status(500).json(sendError(error.message))
}
}
async deleteProduct(req, res, next) {
const self = this;
try {
const result = await self.producProvider.delete(req.params.code);
return res.status(200).json(sendOK(result));
} catch (error) {
console.log(error);
res.status(500).json(sendError(error.message))
}
}
}
module.exports = product;
\ No newline at end of file
......@@ -18,7 +18,8 @@ class productProvider {
}).then(res => {
return res;
}).catch(err => {
console.log(err)
throw err;
})
}
......@@ -37,7 +38,8 @@ class productProvider {
return res;
}).catch(err => {
console.log(err)
throw err;
})
}
......@@ -51,7 +53,8 @@ class productProvider {
return res;
})
.catch(err => {
console.log(err)
throw err;
})
}
......@@ -71,7 +74,8 @@ class productProvider {
return result;
})
.catch((err) => {
console.log(err)
throw err;
});
}
......@@ -87,6 +91,7 @@ class productProvider {
})
.catch(err => {
console.log(err)
throw err;
})
}
}
......
......@@ -2,9 +2,7 @@
const constant = require('./constant/constant.js');
const apiControllerPath = './controller';
var changeCase = require('change-case');
var express = require('express');
var requireDir = require('require-dir')
var fs = require('fs');
var path = require('path');
......@@ -12,17 +10,12 @@ var Routes = function (app) {
var prefix = constant.ROUTE_PREFIX;
// Configure API controller paths
fs.readdirSync(path.resolve(__dirname, apiControllerPath)).forEach(dir => {
var fullPath = path.join(apiControllerPath, dir);
var routes = requireDir(fullPath);
Object.keys(routes).forEach(function (routeName) {
fs.readdirSync(path.resolve(__dirname, apiControllerPath)).forEach(routeName => {
var router = express.Router();
var DynamicController = require("./" + path.join(fullPath, routeName));
var DynamicController = require("./" + path.join(apiControllerPath, routeName));
var controller = new DynamicController();
controller.init(router);
app.use('/' + prefix + '/' + dir + '/' + changeCase.paramCase(routeName), router);
});
app.use('/' + prefix + '/' + path.parse(routeName).name, router);
});
}
......
......@@ -6,8 +6,8 @@ const sequelize = new Sequelize(nconf.get("Database:DB_DATABASE"), nconf.get("Da
{
host: nconf.get("Database:DB_HOST"),
port: nconf.get("Database:DB_PORT"),
dialect: 'mysql',
operatorsAliases: 0
dialect: nconf.get("Database:DIALECT"),
operatorsAliases: nconf.get("Database:OPERATORSALIASESE")
});
const initExport = initModels(sequelize);
module.exports = initExport;
\ No newline at end of file
......@@ -6,7 +6,7 @@ nconf.argv()
const express = require('express')
var nconf = require('nconf');
var bodyParser = require('body-parser');
var port = 3000;
var port = nconf.get('Port');
var app = express();
app.use(bodyParser.json({ type: "application/json", limit: "50mb" }));
require('./app/route')(app);
......
......@@ -10,7 +10,7 @@
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js",
"start": "node index.js",
"start": "npm run gen-db && node index.js",
"gen-db": "sequelize-auto -o app/models -d inventory -h 127.0.0.1 -u root -p 3306 "
......@@ -18,12 +18,6 @@
"dependencies": {
"axios": "^0.26.1",
"body-parser": "^1.20.0",
"change-case": "^4.1.2",
"cors": "^2.8.5",
"dotenv": "^16.0.0",
......
const request = require('supertest');
const express = require('express');
const app =require('./index.js');
const app = require('./index.js');
describe('API Products Endpoints', () => {
it('should return listing with records', async () => {
......@@ -26,19 +23,35 @@ describe('API Products Endpoints', () => {
});
it('should create new product', async () => {
const res = await request(app).post('/api/products').send({
code: 'P101',
name: 'Tall Basket',
category: 'Home Decoration',
brand: null,
type: null,
description: 'The next super product of the year.',
it('should provide code when update product', async () => {
const res = await request(app).put('/api/products');
expect(res.status).toEqual(404);
});
expect(res.status);
it('should provide code when delete product', async () => {
const res = await request(app).delete('/api/products');
expect(res.status).toEqual(404);
});
it('update record wrong code', async () => {
const res = await request(app).delete('/api/products/P0991');
expect(res.status).toEqual(500);
});
it('record exist in database', async () => {
const res = await request(app).get('/api/products/P010');
expect(res.status).toEqual(200);
});
it('should return one records', async () => {
const res = await request(app).get('/api/products?page=1&size=1');
expect(res.body.responseData.rows).toHaveLength(1);
});
}
)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment