Skip to content

Commit

Permalink
cleanup, add deptname and apis
Browse files Browse the repository at this point in the history
  • Loading branch information
benoitclerget committed Jul 2, 2021
1 parent d39c930 commit f9e8eda
Show file tree
Hide file tree
Showing 12 changed files with 258 additions and 120 deletions.
2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "db2-samplejs",
"version": "1.0.0",
"version": "1.0.2",
"description": "Sample web application used to demo IBM DB2 connection",
"engines": {
"node": "14.16.0"
Expand Down
18 changes: 17 additions & 1 deletion server/controllers/data.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -58,6 +58,22 @@ class DataCtl {
return { err: (e.name?e.name:`unknown`), message: (e.message?e.message:`unknown`) }
}
}
}

/**
* deleteEmployee
*
*/
async deleteEmployee(empno) {
log.trace(`[db2Ctl.deleteEmployee] started...`)
try {
const result = await this.service.deleteEmployee(empno)
log.trace(`[deleteEmployee] completed`)
return result
} catch (e) {
log.error(`Error : ${e.name} ${e.message}`)
return { err: (e.name?e.name:`unknown`), message: (e.message?e.message:`unknown`) }
}
}

}
module.exports = DataCtl
15 changes: 15 additions & 0 deletions server/routers/apis.js
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,21 @@ module.exports = function(app) {
}
})

// delete employee entry
router.delete('/api/employee/:empno', async function(req, res) {
//console.log(req.body); // employee_level json
const dataCtl = new DataController()
let result = await dataCtl.deleteEmployee(req.params.empno)
if(result.err && result.err != 'NOTEXIST_OR_NOTAUTH') {
res.status(httpStatus.BAD_REQUEST).json(result).end()
} else {
res
.status(httpStatus.OK)
.json(result)
.end()
}
})

app.use('/', express.static("./dist"))
app.use(router)
}
Expand Down
71 changes: 63 additions & 8 deletions server/services/data.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,10 @@ COMM SYSIBM DECIMAL 9 2 Y
return { err: 'DB_ERROR', message: 'Cannot connect to the Database!!!' }
}
try {
let sql_query = `select * from DB2INST1.EMPLOYEE order by empno`
let sql_query = `select e.*,d.deptname
from DB2INST1.EMPLOYEE e, DB2INST1.DEPARTMENT d
where d.deptno=e.workdept
order by e.empno`
let data = await db2conn.query(sql_query)
db2conn.closeSync();
log.trace(`[db2.service.getEmployees] db2 connection closed`)
Expand Down Expand Up @@ -85,7 +88,9 @@ COMM SYSIBM DECIMAL 9 2 Y
empno: '1376',
firstnme: 'Benoit',
lastname: 'Clerget',
edlevel: 3
department: 'A00',
edlevel: 3,
salary: 42000
}
*/
// Check input params
Expand All @@ -95,6 +100,12 @@ COMM SYSIBM DECIMAL 9 2 Y
err.name = `insertEmployee.invalidInputData`
throw err
}
if(isNaN(parseInt(employee_def.salary))) {
// if salary not a number, throw err
let err = new Error('Input argument salary must be a valid integer number !!!')
err.name = `insertEmployee.invalidInputData`
throw err
}
// open db2 connection
let db2conn
try {
Expand All @@ -118,10 +129,11 @@ COMM SYSIBM DECIMAL 9 2 Y
return { err: 'EXIST_OR_NOTAUTH', message: `employee ${employee_def.empno} already exists` }
}
sql_flow_step = 'insert employee'
sql_query = `insert into DB2INST1.EMPLOYEE (empno,firstnme,lastname,edlevel)
values('${employee_def.empno}','${employee_def.firstnme}','${employee_def.lastname}',${parseInt(employee_def.edlevel)})
sql_query = `insert into DB2INST1.EMPLOYEE (empno,firstnme,lastname,workdept,edlevel,salary)
select '${employee_def.empno}','${employee_def.firstnme}','${employee_def.lastname}','${employee_def.department}',${parseInt(employee_def.edlevel)},${parseInt(employee_def.salary)}
from ( values (1) )
where not exists (select * from DB2INST1.EMPLOYEE where empno = '${employee_def.empno}')`
data = await db2conn.query(sql_query)
data = await db2conn.query(sql_query)
db2conn.closeSync();
log.trace(`[db2.service.insertEmployee] db2 connection closed`)
return { err: null, message: `empoyee ${employee_def.empno} (${employee_def.firstnme} ${employee_def.lastname}) successfully added in database`}
Expand All @@ -132,9 +144,15 @@ COMM SYSIBM DECIMAL 9 2 Y
}
}


// this method is used to update the dlevel of an existing employee
async updateEmployeeLevel(employee_level) {
//console.log(employee_level)
/*
{
empno: '1376',
new_level: 5
}
*/
// Check input params
if(isNaN(parseInt(employee_level.new_level))) {
// if new_level not a number, throw err
Expand Down Expand Up @@ -162,11 +180,11 @@ COMM SYSIBM DECIMAL 9 2 Y
if(data.length < 1) {
db2conn.closeSync();
console.error(`[db2.service.updateEmployeeLevel] employee ${employee_level.empno} does not exist`)
return { err: 'NOT_EXIST_OR_NOTAUTH', message: `employee ${employee_level.empno} does not exist` }
return { err: 'NOTEXIST_OR_NOTAUTH', message: `employee ${employee_level.empno} does not exist` }
}
sql_flow_step = 'update employee with new edlevel'
sql_query = `update DB2INST1.EMPLOYEE set edlevel=${parseInt(employee_level.new_level)}
where empno='${empno}'`
where empno='${employee_level.empno}'`
data = await db2conn.query(sql_query)
db2conn.closeSync();
log.trace(`[db2.service.updateEmployeeLevel] db2 connection closed`)
Expand All @@ -178,6 +196,43 @@ COMM SYSIBM DECIMAL 9 2 Y
}
}

// this method is used to delete an employee record
async deleteEmployee(empno) {
// open db2 connection
let db2conn
try {
log.trace(`[db2.service.deleteEmployee] try to connect to db2...`)
db2conn = await ibmdb.open(db2ConnStr)
} catch(err) {
console.error('[db2.service.deleteEmployee] ', JSON.stringify(err))
return { err: 'DB_ERROR', message: 'Cannot connect to the Database!!!' }
}
let sql_flow_step = ''
try {
sql_flow_step = 'sql verif'
// check that empno exists
// the ibm_db currently does not raise an sql error if empno does not exists TODO to be confirmed
// so we need to add a first query to check if it does exist, then we can run the update
let sql_query = `select empno from DB2INST1.EMPLOYEE where empno='${empno}'`
let data = await db2conn.query(sql_query)
if(data.length < 1) {
db2conn.closeSync();
console.error(`[db2.service.deleteEmployee] employee ${empno} does not exist`)
return { err: 'NOTEXIST_OR_NOTAUTH', message: `employee ${empno} does not exist` }
}
sql_flow_step = 'delete employee'
sql_query = `delete from DB2INST1.EMPLOYEE where empno='${empno}'`
data = await db2conn.query(sql_query)
db2conn.closeSync();
log.trace(`[db2.service.deleteEmployee] db2 connection closed`)
return { err: null, message: `employee ${empno} successfully deleted from Employee table`}
} catch(err) {
db2conn.closeSync();
console.error('[db2.service.deleteEmployee] ' + sql_flow_step, JSON.stringify(err))
return { err: 'DB_ERROR', message: 'Error deleting employee Step: ' + sql_flow_step }
}
}

////// END DB2 //////


Expand Down
87 changes: 75 additions & 12 deletions src/app_funcs.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,23 +6,38 @@
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
////// ibmdotcom carbon components
//import '@carbon/ibmdotcom-web-components/es/components/image/image.js';
//import '@carbon/ibmdotcom-web-components/es/components/horizontal-rule/horizontal-rule.js';

////// carbon components
//import { Loading } from 'carbon-components';
//import { InlineLoading } from 'carbon-components';

//import _ from 'lodash'; // javascript utilities https://lodash.com/

//const util = require('util')
// toaster
import { Notification } from 'carbon-components';
//const toastInstanceInfo = Notification.create(document.getElementById('toast_info'));
//toastInstanceInfo.remove()
//toastInstanceInfo.release()


// request web app info api
async function getWebAppInfos() {
if (window.fetch) {
try{
let response = await fetch('/health')
if(response.ok) {
let myJson = await response.json()
return {err: false, web_infos: myJson}
} else {
console.error('response error: ' + response.ok);
return {err: true, message: 'Error retreiving web app infos response'}
}

} catch(error) {
console.error('Error with fetch operation: ' + error);
return {err: true, message: 'Error retreiving web app infos response'}
}
} else {
console.error('fetch not supported');
return {err: true, message: 'fetch not supported'}
}
}

// request employees api
async function getEmployees(resolve,reject) {
if (window.fetch) {
Expand Down Expand Up @@ -54,6 +69,16 @@ async function getEmployees(resolve,reject) {
// insert new employee
async function insertEmployee(employee_def,resolve,reject) {
//console.log(JSON.stringify(employee_def))
/*
{
empno: '1376',
firstnme: 'Benoit',
lastname: 'Clerget',
department: 'A00',
edlevel: 3,
salary: 42000
}
*/
if (window.fetch) {
let myHeaders = new Headers()
myHeaders.append("Content-Type", "application/json")
Expand Down Expand Up @@ -88,7 +113,13 @@ async function insertEmployee(employee_def,resolve,reject) {

// update employee level
async function updateEmployeeLevel(emp_level,resolve,reject) {
if (window.fetch) {
/*
{
empno: '1376',
new_level: 5
}
*/
if (window.fetch) {
let myHeaders = new Headers()
myHeaders.append("Content-Type", "application/json")
fetch(`/api/employee_level`,{
Expand All @@ -98,7 +129,7 @@ async function updateEmployeeLevel(emp_level,resolve,reject) {
}).then(function(response) {
if(response.ok) {
response.json().then(function(myJson) {
if (myJson.err && myJson.err != 'NOT_EXIST_OR_NOTAUTH') {
if (myJson.err && myJson.err != 'NOTEXIST_OR_NOTAUTH') {
console.error('API error: ' + myJson.message);
reject({err: true, message: myJson.message})
} else {
Expand All @@ -120,6 +151,38 @@ async function updateEmployeeLevel(emp_level,resolve,reject) {
}
}

// delete employee record
async function deleteEmployee(empno,resolve,reject) {
if (window.fetch) {
let myHeaders = new Headers()
myHeaders.append("Content-Type", "application/json")
fetch(`/api/employee/${empno}`,{
method: 'DELETE',
headers: myHeaders,
}).then(function(response) {
if(response.ok) {
response.json().then(function(myJson) {
if(myJson.err && myJson.err != 'NOTEXIST_OR_NOTAUTH') {
console.error('API error: ' + myJson.message);
reject({err: true, message: myJson.message})
} else {
resolve(myJson)
}
});
} else {
console.error('response error: ' + response.ok);
reject({err: true, message: `Error deleting employee ${empno}`})
}
})
.catch(function(error) {
console.error('Error with post operation: ' + error);
reject({err: true, message: 'unknownerror'})
});
} else {
console.error('fetch not supported');
reject({err: true, message: 'fetch not supported'})
}
}


function addToasterNotification(notif_type, notif_obj, duration=8) {
Expand Down Expand Up @@ -156,4 +219,4 @@ function addToasterNotification(notif_type, notif_obj, duration=8) {
})
}

export {getEmployees, insertEmployee, updateEmployeeLevel, addToasterNotification}
export {getWebAppInfos, getEmployees, insertEmployee, updateEmployeeLevel, deleteEmployee, addToasterNotification}
Loading

0 comments on commit f9e8eda

Please sign in to comment.