Snippets

litmis Node.js CRUD controller

Created by Aaron Bartell last modified Andrei Tyuhai
diff --git a/examples/expressjs_customer/app.js b/examples/expressjs_customer/app.js
index 497d064..a0a3f1e 100644
--- a/examples/expressjs_customer/app.js
+++ b/examples/expressjs_customer/app.js
@@ -1,25 +1,69 @@
 var express = require('express')
 var app = express()
+var util = require( "util" )
+var body_parser = require('body-parser')
+
 var db = require('/QOpenSys/QIBM/ProdData/Node/os400/db2i/lib/db2')
 db.init()
 db.conn("*LOCAL")
+db.exec("SET SCHEMA MYLIB")

 app.set('views', __dirname + '/views')
 app.set('view engine', 'jade')

+app.use(body_parser.urlencoded({ extended: true }))
+
 app.get('/', function (req, res) {
   res.render('index', { title: 'Hey', message: 'Hello there!'})
 })
+
 app.get('/customers', function (req, res) {
-  db.exec("SELECT LSTNAM, CUSNUM FROM QIWS.QCUSTCDT", function(results) {
-    res.render('customers', { title: 'Customers', results: results})
+  db.exec("SELECT LSTNAM, CUSNUM FROM QCUSTCDT order by CUSNUM ASC", function(results) {
+    res.render('customers/index', { title: 'Customers', results: results})
+  })
+})
+
+app.get('/customers/new', function (req, res) {
+  res.render('customers/new', {result: {}, form_action: '/customers/create'})
+})
+
+app.post('/customers/create', function (req, res) {
+  var sql = util.format("INSERT INTO QCUSTCDT (CUSNUM,LSTNAM,INIT,STREET) VALUES ('%s', '%s', '%s', '%s')",
+                        req.body.CUSNUM, req.body.LSTNAM, req.body.INIT, req.body.STREET)
+  db.exec(sql)
+  res.redirect('/customers')
+})
+
+app.get('/customers/:id', function (req, res) {
+  var sql = "SELECT * FROM QCUSTCDT WHERE CUSNUM=" + req.params.id
+  db.exec(sql, function(result) {
+    res.render('customers/show', { title: 'Customer', result: result[0]})
   })
 })
-app.get('/customer/:id', function (req, res) {
-  var sql = "SELECT * FROM QIWS.QCUSTCDT WHERE CUSNUM=" + req.params.id
+
+app.get('/customers/:id/edit', function (req, res) {
+  var sql = util.format("SELECT * FROM QCUSTCDT WHERE CUSNUM=%s", req.params.id)
   db.exec(sql, function(result) {
-    res.render('customer', { title: 'Customer', result: result[0]})
+    res.render('customers/edit',
+      { title: 'Customer',
+        result: result[0],
+        form_action: util.format('/customers/%s/update', req.params.id)
+      })
   })
 })

+app.post('/customers/:id/update', function (req, res) {
+  var sql = util.format("UPDATE QCUSTCDT SET CUSNUM='%s',LSTNAM='%s',INIT='%s',STREET='%s' WHERE CUSNUM='%s'",
+                        req.body.CUSNUM, req.body.LSTNAM, req.body.INIT, req.body.STREET, req.body.CUSNUM)
+  db.exec(sql)
+  res.redirect('/customers')
+})
+
+app.get('/customers/:id/delete', function (req, res) {
+  var sql = util.format("DELETE FROM QCUSTCDT WHERE CUSNUM='%s'", req.params.id)
+  db.exec(sql)
+  res.redirect('/customers')
+})
+
 app.listen(8001)

Comments (0)