Section 5: Building a CRUD App - The Food Ingredients Database
This is the heart of the course. Here is the complete server.js. Read it top to bottom - I've commented the interesting bits.
// server.js - Ingredients CRUD API on IBM i
require('dotenv').config();
const path = require('path');
const express = require('express');
const db = require('./db');
const app = express();
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
const TABLE = 'FOODLIB.INGREDIENTS';
const COLUMNS = 'ID, NAME, CATEGORY, UNIT, QUANTITY, CALORIES, CREATED_AT, UPDATED_AT';
// ---------- helpers ----------
// Turn a DB row into clean JSON (DECIMAL comes back as a string from ODBC)
function toIngredient(row) {
return {
id: Number(row.ID),
name: row.NAME,
category: row.CATEGORY,
unit: row.UNIT,
quantity: Number(row.QUANTITY),
calories: Number(row.CALORIES),
createdAt: row.CREATED_AT,
updatedAt: row.UPDATED_AT,
};
}
// Validate a request body. Returns an array of error messages (empty = OK)
function validate(body) {
const errors = [];
if (!body || typeof body.name !== 'string' || body.name.trim() === '') {
errors.push('name is required');
} else if (body.name.length > 100) {
errors.push('name must be 100 characters or less');
}
if (body.category !== undefined && (typeof body.category !== 'string' || body.category.length > 50)) {
errors.push('category must be a string of 50 characters or less');
}
if (body.unit !== undefined && (typeof body.unit !== 'string' || body.unit.length > 20)) {
errors.push('unit must be a string of 20 characters or less');
}
if (body.quantity !== undefined && !(Number(body.quantity) >= 0)) {
errors.push('quantity must be a number >= 0');
}
if (body.calories !== undefined && !(Number.isInteger(Number(body.calories)) && Number(body.calories) >= 0)) {
errors.push('calories must be a whole number >= 0');
}
return errors;
}
function parseId(req) {
const id = Number(req.params.id);
return Number.isInteger(id) && id > 0 ? id : null;
}
// ---------- READ: list all (optional ?category= filter) ----------
app.get('/api/ingredients', async (req, res, next) => {
try {
let rows;
if (req.query.category) {
rows = await db.query(
`SELECT ${COLUMNS} FROM ${TABLE} WHERE CATEGORY = ? ORDER BY NAME`,
[req.query.category]
);
} else {
rows = await db.query(`SELECT ${COLUMNS} FROM ${TABLE} ORDER BY NAME`);
}
res.json(rows.map(toIngredient));
} catch (err) {
next(err);
}
});
// ---------- READ: one by id ----------
app.get('/api/ingredients/:id', async (req, res, next) => {
try {
const id = parseId(req);
if (!id) return res.status(400).json({ error: 'Invalid id' });
const rows = await db.query(`SELECT ${COLUMNS} FROM ${TABLE} WHERE ID = ?`, [id]);
if (rows.length === 0) return res.status(404).json({ error: 'Ingredient not found' });
res.json(toIngredient(rows[0]));
} catch (err) {
next(err);
}
});
// ---------- CREATE ----------
app.post('/api/ingredients', async (req, res, next) => {
try {
const errors = validate(req.body);
if (errors.length) return res.status(400).json({ errors });
const { name, category = 'Other', unit = 'g', quantity = 0, calories = 0 } = req.body;
// FINAL TABLE returns the generated identity in the same statement
const rows = await db.query(
`SELECT ${COLUMNS} FROM FINAL TABLE (
INSERT INTO ${TABLE} (NAME, CATEGORY, UNIT, QUANTITY, CALORIES)
VALUES (?, ?, ?, ?, ?)
)`,
[name.trim(), category, unit, Number(quantity), Number(calories)]
);
res.status(201).json(toIngredient(rows[0]));
} catch (err) {
next(err);
}
});
// ---------- UPDATE (full replace of editable fields) ----------
app.put('/api/ingredients/:id', async (req, res, next) => {
try {
const id = parseId(req);
if (!id) return res.status(400).json({ error: 'Invalid id' });
const errors = validate(req.body);
if (errors.length) return res.status(400).json({ errors });
const { name, category = 'Other', unit = 'g', quantity = 0, calories = 0 } = req.body;
const result = await db.query(
`UPDATE ${TABLE}
SET NAME = ?, CATEGORY = ?, UNIT = ?, QUANTITY = ?, CALORIES = ?,
UPDATED_AT = CURRENT_TIMESTAMP
WHERE ID = ?`,
[name.trim(), category, unit, Number(quantity), Number(calories), id]
);
if (result.count === 0) return res.status(404).json({ error: 'Ingredient not found' });
const rows = await db.query(`SELECT ${COLUMNS} FROM ${TABLE} WHERE ID = ?`, [id]);
res.json(toIngredient(rows[0]));
} catch (err) {
next(err);
}
});
// ---------- DELETE ----------
app.delete('/api/ingredients/:id', async (req, res, next) => {
try {
const id = parseId(req);
if (!id) return res.status(400).json({ error: 'Invalid id' });
const result = await db.query(`DELETE FROM ${TABLE} WHERE ID = ?`, [id]);
if (result.count === 0) return res.status(404).json({ error: 'Ingredient not found' });
res.status(204).end();
} catch (err) {
next(err);
}
});
// ---------- 404 for unknown API routes ----------
app.use('/api', (req, res) => res.status(404).json({ error: 'Not found' }));
// ---------- central error handler ----------
app.use((err, req, res, next) => {
console.error(err);
// Duplicate NAME violates the UNIQUE constraint: SQLSTATE 23505
const sqlState = err.odbcErrors && err.odbcErrors[0] && err.odbcErrors[0].state;
if (sqlState === '23505') {
return res.status(409).json({ error: 'An ingredient with that name already exists' });
}
if (sqlState === '23513') {
return res.status(400).json({ error: 'Value violates a check constraint' });
}
res.status(500).json({ error: 'Internal server error' });
});
// ---------- start / stop ----------
const PORT = Number(process.env.PORT) || 3000;
const server = app.listen(PORT, () => console.log(`Ingredients app listening on port ${PORT}`));
async function shutdown() {
console.log('Shutting down...');
server.close(async () => {
await db.close();
process.exit(0);
});
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
require('dotenv').config();
const path = require('path');
const express = require('express');
const db = require('./db');
const app = express();
app.use(express.json());
app.use(express.static(path.join(__dirname, 'public')));
const TABLE = 'FOODLIB.INGREDIENTS';
const COLUMNS = 'ID, NAME, CATEGORY, UNIT, QUANTITY, CALORIES, CREATED_AT, UPDATED_AT';
// ---------- helpers ----------
// Turn a DB row into clean JSON (DECIMAL comes back as a string from ODBC)
function toIngredient(row) {
return {
id: Number(row.ID),
name: row.NAME,
category: row.CATEGORY,
unit: row.UNIT,
quantity: Number(row.QUANTITY),
calories: Number(row.CALORIES),
createdAt: row.CREATED_AT,
updatedAt: row.UPDATED_AT,
};
}
// Validate a request body. Returns an array of error messages (empty = OK)
function validate(body) {
const errors = [];
if (!body || typeof body.name !== 'string' || body.name.trim() === '') {
errors.push('name is required');
} else if (body.name.length > 100) {
errors.push('name must be 100 characters or less');
}
if (body.category !== undefined && (typeof body.category !== 'string' || body.category.length > 50)) {
errors.push('category must be a string of 50 characters or less');
}
if (body.unit !== undefined && (typeof body.unit !== 'string' || body.unit.length > 20)) {
errors.push('unit must be a string of 20 characters or less');
}
if (body.quantity !== undefined && !(Number(body.quantity) >= 0)) {
errors.push('quantity must be a number >= 0');
}
if (body.calories !== undefined && !(Number.isInteger(Number(body.calories)) && Number(body.calories) >= 0)) {
errors.push('calories must be a whole number >= 0');
}
return errors;
}
function parseId(req) {
const id = Number(req.params.id);
return Number.isInteger(id) && id > 0 ? id : null;
}
// ---------- READ: list all (optional ?category= filter) ----------
app.get('/api/ingredients', async (req, res, next) => {
try {
let rows;
if (req.query.category) {
rows = await db.query(
`SELECT ${COLUMNS} FROM ${TABLE} WHERE CATEGORY = ? ORDER BY NAME`,
[req.query.category]
);
} else {
rows = await db.query(`SELECT ${COLUMNS} FROM ${TABLE} ORDER BY NAME`);
}
res.json(rows.map(toIngredient));
} catch (err) {
next(err);
}
});
// ---------- READ: one by id ----------
app.get('/api/ingredients/:id', async (req, res, next) => {
try {
const id = parseId(req);
if (!id) return res.status(400).json({ error: 'Invalid id' });
const rows = await db.query(`SELECT ${COLUMNS} FROM ${TABLE} WHERE ID = ?`, [id]);
if (rows.length === 0) return res.status(404).json({ error: 'Ingredient not found' });
res.json(toIngredient(rows[0]));
} catch (err) {
next(err);
}
});
// ---------- CREATE ----------
app.post('/api/ingredients', async (req, res, next) => {
try {
const errors = validate(req.body);
if (errors.length) return res.status(400).json({ errors });
const { name, category = 'Other', unit = 'g', quantity = 0, calories = 0 } = req.body;
// FINAL TABLE returns the generated identity in the same statement
const rows = await db.query(
`SELECT ${COLUMNS} FROM FINAL TABLE (
INSERT INTO ${TABLE} (NAME, CATEGORY, UNIT, QUANTITY, CALORIES)
VALUES (?, ?, ?, ?, ?)
)`,
[name.trim(), category, unit, Number(quantity), Number(calories)]
);
res.status(201).json(toIngredient(rows[0]));
} catch (err) {
next(err);
}
});
// ---------- UPDATE (full replace of editable fields) ----------
app.put('/api/ingredients/:id', async (req, res, next) => {
try {
const id = parseId(req);
if (!id) return res.status(400).json({ error: 'Invalid id' });
const errors = validate(req.body);
if (errors.length) return res.status(400).json({ errors });
const { name, category = 'Other', unit = 'g', quantity = 0, calories = 0 } = req.body;
const result = await db.query(
`UPDATE ${TABLE}
SET NAME = ?, CATEGORY = ?, UNIT = ?, QUANTITY = ?, CALORIES = ?,
UPDATED_AT = CURRENT_TIMESTAMP
WHERE ID = ?`,
[name.trim(), category, unit, Number(quantity), Number(calories), id]
);
if (result.count === 0) return res.status(404).json({ error: 'Ingredient not found' });
const rows = await db.query(`SELECT ${COLUMNS} FROM ${TABLE} WHERE ID = ?`, [id]);
res.json(toIngredient(rows[0]));
} catch (err) {
next(err);
}
});
// ---------- DELETE ----------
app.delete('/api/ingredients/:id', async (req, res, next) => {
try {
const id = parseId(req);
if (!id) return res.status(400).json({ error: 'Invalid id' });
const result = await db.query(`DELETE FROM ${TABLE} WHERE ID = ?`, [id]);
if (result.count === 0) return res.status(404).json({ error: 'Ingredient not found' });
res.status(204).end();
} catch (err) {
next(err);
}
});
// ---------- 404 for unknown API routes ----------
app.use('/api', (req, res) => res.status(404).json({ error: 'Not found' }));
// ---------- central error handler ----------
app.use((err, req, res, next) => {
console.error(err);
// Duplicate NAME violates the UNIQUE constraint: SQLSTATE 23505
const sqlState = err.odbcErrors && err.odbcErrors[0] && err.odbcErrors[0].state;
if (sqlState === '23505') {
return res.status(409).json({ error: 'An ingredient with that name already exists' });
}
if (sqlState === '23513') {
return res.status(400).json({ error: 'Value violates a check constraint' });
}
res.status(500).json({ error: 'Internal server error' });
});
// ---------- start / stop ----------
const PORT = Number(process.env.PORT) || 3000;
const server = app.listen(PORT, () => console.log(`Ingredients app listening on port ${PORT}`));
async function shutdown() {
console.log('Shutting down...');
server.close(async () => {
await db.close();
process.exit(0);
});
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
The API at a glance
| Operation | Method & URL | Body | Success |
|---|---|---|---|
| Create | POST /api/ingredients | JSON ingredient | 201 + new row |
| Read all | GET /api/ingredients[?category=Dairy] | - | 200 + array |
| Read one | GET /api/ingredients/:id | - | 200 + row |
| Update | PUT /api/ingredients/:id | JSON ingredient | 200 + updated row |
| Delete | DELETE /api/ingredients/:id | - | 204 |
Testing with curl
cd ~/ingredients-app && npm start
From a second session:
# Create
curl -i -X POST http://localhost:3000/api/ingredients \
-H 'Content-Type: application/json' \
-d '{"name":"Basil","category":"Herb","unit":"g","quantity":25,"calories":23}'
# Read all, then filter
curl http://localhost:3000/api/ingredients
curl 'http://localhost:3000/api/ingredients?category=Dairy'
# Read one
curl http://localhost:3000/api/ingredients/1
# Update
curl -i -X PUT http://localhost:3000/api/ingredients/1 \
-H 'Content-Type: application/json' \
-d '{"name":"Plain Flour","category":"Baking","unit":"g","quantity":750,"calories":364}'
# Delete
curl -i -X DELETE http://localhost:3000/api/ingredients/3
# Error cases
curl -i -X POST http://localhost:3000/api/ingredients -H 'Content-Type: application/json' -d '{}' # 400
curl -i -X POST http://localhost:3000/api/ingredients -H 'Content-Type: application/json' -d '{"name":"Basil"}' # 409
curl -i http://localhost:3000/api/ingredients/99999
curl -i -X POST http://localhost:3000/api/ingredients \
-H 'Content-Type: application/json' \
-d '{"name":"Basil","category":"Herb","unit":"g","quantity":25,"calories":23}'
# Read all, then filter
curl http://localhost:3000/api/ingredients
curl 'http://localhost:3000/api/ingredients?category=Dairy'
# Read one
curl http://localhost:3000/api/ingredients/1
# Update
curl -i -X PUT http://localhost:3000/api/ingredients/1 \
-H 'Content-Type: application/json' \
-d '{"name":"Plain Flour","category":"Baking","unit":"g","quantity":750,"calories":364}'
# Delete
curl -i -X DELETE http://localhost:3000/api/ingredients/3
# Error cases
curl -i -X POST http://localhost:3000/api/ingredients -H 'Content-Type: application/json' -d '{}' # 400
curl -i -X POST http://localhost:3000/api/ingredients -H 'Content-Type: application/json' -d '{"name":"Basil"}' # 409
curl -i http://localhost:3000/api/ingredients/99999
Then check in ACS: SELECT * FROM FOODLIB.INGREDIENTS - your changes are right there in Db2 for i.
