Section 5: Building a CRUD App - The Food Ingredients Database

Now let's create the Node.js project in the IFS.

Folder structure

Project setup and the database module FOLDER STRUCTURE

Create it

mkdir -p ~/ingredients-app/public && cd ~/ingredients-app
npm init -y
npm install express odbc dotenv

Edit package.json so it looks like this (versions may be newer on your system - that's fine):

{
 "name": "ingredients-app",
 "version": "1.0.0",
 "description": "Food ingredients CRUD app - Node.js on IBM i",
 "main": "server.js",
 "scripts": {
 "start": "node server.js"
 },
 "dependencies": {
   "dotenv": "^16.4.5",
   "express": "^4.19.2",
   "odbc": "^2.4.9"
 }
}

Configuration: .env

# .env
DB_USER=NICK
DB_PASS=changeme
DB_DSN=*LOCAL
PORT=3000

Lock it down so only you can read it:

chmod 600 .env

The database module: db.js

// db.js - one shared ODBC connection pool for the whole app
require('dotenv').config();
const odbc = require('odbc');

let pool;

async function getPool() {
if (!pool) {
pool = await odbc.pool({
connectionString:
`DSN=${process.env.DB_DSN};UID=${process.env.DB_USER};PWD=${process.env.DB_PASS};` +
'CMT=0;', // CMT=0 = autocommit, so no journal/commit gymnastics per statement
initialSize: 2,
maxSize: 10,
});
}
return pool;
}

// Run a parameterized statement. Use ? markers - NEVER build SQL from strings!
async function query(sql, params = []) {
const p = await getPool();
return p.query(sql, params);
}

async function close() {
if (pool) await pool.close();
}

module.exports = { query, close };

Two important points:

  1. Parameter markers (?) - user input is never glued into SQL. This prevents SQL injection, the IT equivalent of leaving your car keys in the ignition.
  2. One pool, created once - opening a connection per request is slow; the pool hands out ready-made connections.
{"email":"Email address invalid","url":"Website address invalid","required":"Required field missing"}
>