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 ...@@ -15,15 +15,15 @@ execute query in file mysql.sql
#### ####
use the following api: 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 @@ ...@@ -6,6 +6,8 @@
"DB_USER": "root", "DB_USER": "root",
"DB_PASS": null, "DB_PASS": null,
"DB_HOST": "127.0.0.1", "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 { ...@@ -18,7 +18,8 @@ class productProvider {
}).then(res => { }).then(res => {
return res; return res;
}).catch(err => { }).catch(err => {
console.log(err)
throw err;
}) })
} }
...@@ -37,7 +38,8 @@ class productProvider { ...@@ -37,7 +38,8 @@ class productProvider {
return res; return res;
}).catch(err => { }).catch(err => {
console.log(err)
throw err;
}) })
} }
...@@ -51,7 +53,8 @@ class productProvider { ...@@ -51,7 +53,8 @@ class productProvider {
return res; return res;
}) })
.catch(err => { .catch(err => {
console.log(err)
throw err;
}) })
} }
...@@ -71,7 +74,8 @@ class productProvider { ...@@ -71,7 +74,8 @@ class productProvider {
return result; return result;
}) })
.catch((err) => { .catch((err) => {
console.log(err)
throw err;
}); });
} }
...@@ -87,6 +91,7 @@ class productProvider { ...@@ -87,6 +91,7 @@ class productProvider {
}) })
.catch(err => { .catch(err => {
console.log(err) console.log(err)
throw err;
}) })
} }
} }
......
...@@ -2,9 +2,7 @@ ...@@ -2,9 +2,7 @@
const constant = require('./constant/constant.js'); const constant = require('./constant/constant.js');
const apiControllerPath = './controller'; const apiControllerPath = './controller';
var changeCase = require('change-case');
var express = require('express'); var express = require('express');
var requireDir = require('require-dir')
var fs = require('fs'); var fs = require('fs');
var path = require('path'); var path = require('path');
...@@ -12,17 +10,12 @@ var Routes = function (app) { ...@@ -12,17 +10,12 @@ var Routes = function (app) {
var prefix = constant.ROUTE_PREFIX; var prefix = constant.ROUTE_PREFIX;
// Configure API controller paths // Configure API controller paths
fs.readdirSync(path.resolve(__dirname, apiControllerPath)).forEach(dir => { fs.readdirSync(path.resolve(__dirname, apiControllerPath)).forEach(routeName => {
var fullPath = path.join(apiControllerPath, dir); var router = express.Router();
var routes = requireDir(fullPath); var DynamicController = require("./" + path.join(apiControllerPath, routeName));
var controller = new DynamicController();
Object.keys(routes).forEach(function (routeName) { controller.init(router);
var router = express.Router(); app.use('/' + prefix + '/' + path.parse(routeName).name, router);
var DynamicController = require("./" + path.join(fullPath, routeName));
var controller = new DynamicController();
controller.init(router);
app.use('/' + prefix + '/' + dir + '/' + changeCase.paramCase(routeName), router);
});
}); });
} }
......
...@@ -6,8 +6,8 @@ const sequelize = new Sequelize(nconf.get("Database:DB_DATABASE"), nconf.get("Da ...@@ -6,8 +6,8 @@ const sequelize = new Sequelize(nconf.get("Database:DB_DATABASE"), nconf.get("Da
{ {
host: nconf.get("Database:DB_HOST"), host: nconf.get("Database:DB_HOST"),
port: nconf.get("Database:DB_PORT"), port: nconf.get("Database:DB_PORT"),
dialect: 'mysql', dialect: nconf.get("Database:DIALECT"),
operatorsAliases: 0 operatorsAliases: nconf.get("Database:OPERATORSALIASESE")
}); });
const initExport = initModels(sequelize); const initExport = initModels(sequelize);
module.exports = initExport; module.exports = initExport;
\ No newline at end of file
...@@ -6,7 +6,7 @@ nconf.argv() ...@@ -6,7 +6,7 @@ nconf.argv()
const express = require('express') const express = require('express')
var nconf = require('nconf'); var nconf = require('nconf');
var bodyParser = require('body-parser'); var bodyParser = require('body-parser');
var port = 3000; var port = nconf.get('Port');
var app = express(); var app = express();
app.use(bodyParser.json({ type: "application/json", limit: "50mb" })); app.use(bodyParser.json({ type: "application/json", limit: "50mb" }));
require('./app/route')(app); require('./app/route')(app);
......
...@@ -10,7 +10,7 @@ ...@@ -10,7 +10,7 @@
"test": "node --experimental-vm-modules node_modules/jest/bin/jest.js", "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 " "gen-db": "sequelize-auto -o app/models -d inventory -h 127.0.0.1 -u root -p 3306 "
...@@ -18,12 +18,6 @@ ...@@ -18,12 +18,6 @@
"dependencies": { "dependencies": {
"axios": "^0.26.1",
"body-parser": "^1.20.0",
"change-case": "^4.1.2",
"cors": "^2.8.5", "cors": "^2.8.5",
"dotenv": "^16.0.0", "dotenv": "^16.0.0",
......
const request = require('supertest'); const request = require('supertest');
const express = require('express'); const app = require('./index.js');
const app =require('./index.js');
describe('API Products Endpoints', () => { describe('API Products Endpoints', () => {
it('should return listing with records', async () => { it('should return listing with records', async () => {
const res = await request(app).get('/api/products'); const res = await request(app).get('/api/products');
expect(200) expect(200)
}); });
it('should delete existing product', async () => { it('should delete existing product', async () => {
const res = await request(app).delete('/api/products/P005'); const res = await request(app).delete('/api/products/P005');
expect(res.status); expect(res.status);
}); });
it('should update existing product', async () => { it('should update existing product', async () => {
const res = await request(app).put('/api/products/P003') const res = await request(app).put('/api/products/P003')
.send({ .send({
description: '*NULL*', description: '*NULL*',
}); });
expect(res.status); expect(res.status);
}); });
it('should create new product', async () => { it('should provide code when update product', async () => {
const res = await request(app).post('/api/products').send({ const res = await request(app).put('/api/products');
code: 'P101', expect(res.status).toEqual(404);
name: 'Tall Basket',
category: 'Home Decoration', });
brand: null,
type: null, it('should provide code when delete product', async () => {
description: 'The next super product of the year.', const res = await request(app).delete('/api/products');
}); expect(res.status).toEqual(404);
expect(res.status);
});
});
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