feat(backend): Prisma schema, Express routes, audit middleware, error handling
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
const router = require('express').Router();
|
||||
const { body, query } = require('express-validator');
|
||||
const prisma = require('../lib/prisma');
|
||||
const auditMiddleware = require('../middleware/auditMiddleware');
|
||||
const { validateRequest } = require('../middleware/errorHandler');
|
||||
|
||||
const animalValidation = [
|
||||
body('experiment_id').notEmpty().withMessage('experiment_id is required').isUUID().withMessage('experiment_id must be a valid UUID'),
|
||||
body('animal_id_string').trim().notEmpty().withMessage('animal_id_string is required'),
|
||||
body('animal_name').trim().notEmpty().withMessage('animal_name is required'),
|
||||
];
|
||||
|
||||
const animalUpdateValidation = [
|
||||
body('animal_id_string').optional().trim().notEmpty().withMessage('animal_id_string cannot be empty'),
|
||||
body('animal_name').optional().trim().notEmpty().withMessage('animal_name cannot be empty'),
|
||||
];
|
||||
|
||||
// GET /api/animals?experimentId=<uuid> — list for experiment
|
||||
router.get(
|
||||
'/',
|
||||
[query('experimentId').optional().isUUID().withMessage('experimentId must be a valid UUID')],
|
||||
validateRequest,
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const where = req.query.experimentId ? { experiment_id: req.query.experimentId } : {};
|
||||
const animals = await prisma.animal.findMany({
|
||||
where,
|
||||
orderBy: { animal_name: 'asc' },
|
||||
include: { _count: { select: { daily_statuses: true } } },
|
||||
});
|
||||
res.json(animals);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// GET /api/animals/:id — get one with daily statuses
|
||||
router.get('/:id', async (req, res, next) => {
|
||||
try {
|
||||
const animal = await prisma.animal.findUnique({
|
||||
where: { id: req.params.id },
|
||||
include: { daily_statuses: { orderBy: { date: 'desc' } } },
|
||||
});
|
||||
if (!animal) return res.status(404).json({ error: 'Animal not found' });
|
||||
res.json(animal);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/animals — create
|
||||
router.post('/', animalValidation, validateRequest, async (req, res, next) => {
|
||||
try {
|
||||
const { experiment_id, animal_id_string, animal_name } = req.body;
|
||||
const animal = await prisma.animal.create({
|
||||
data: { experiment_id, animal_id_string, animal_name },
|
||||
});
|
||||
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
table_name: 'animals',
|
||||
record_id: animal.id,
|
||||
action: 'CREATE',
|
||||
changes: { before: null, after: animal },
|
||||
},
|
||||
});
|
||||
|
||||
res.status(201).json(animal);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// PUT /api/animals/:id — update
|
||||
router.put(
|
||||
'/:id',
|
||||
auditMiddleware('animals', prisma.animal),
|
||||
animalUpdateValidation,
|
||||
validateRequest,
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const { animal_id_string, animal_name } = req.body;
|
||||
const data = {};
|
||||
if (animal_id_string !== undefined) data.animal_id_string = animal_id_string;
|
||||
if (animal_name !== undefined) data.animal_name = animal_name;
|
||||
|
||||
const animal = await prisma.animal.update({
|
||||
where: { id: req.params.id },
|
||||
data,
|
||||
});
|
||||
res.json(animal);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// DELETE /api/animals/:id — delete
|
||||
router.delete(
|
||||
'/:id',
|
||||
auditMiddleware('animals', prisma.animal),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
await prisma.animal.delete({ where: { id: req.params.id } });
|
||||
res.status(204).send();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,54 @@
|
||||
const router = require('express').Router();
|
||||
const { query } = require('express-validator');
|
||||
const prisma = require('../lib/prisma');
|
||||
const { validateRequest } = require('../middleware/errorHandler');
|
||||
|
||||
// GET /api/audit-logs?tableName=&recordId=&limit=&offset= — query logs
|
||||
router.get(
|
||||
'/',
|
||||
[
|
||||
query('tableName').optional().isString(),
|
||||
query('recordId').optional().isUUID().withMessage('recordId must be a valid UUID'),
|
||||
query('limit').optional().isInt({ min: 1, max: 200 }).withMessage('limit must be 1–200').toInt(),
|
||||
query('offset').optional().isInt({ min: 0 }).withMessage('offset must be ≥0').toInt(),
|
||||
],
|
||||
validateRequest,
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const { tableName, recordId } = req.query;
|
||||
const limit = req.query.limit || 50;
|
||||
const offset = req.query.offset || 0;
|
||||
|
||||
const where = {};
|
||||
if (tableName) where.table_name = tableName;
|
||||
if (recordId) where.record_id = recordId;
|
||||
|
||||
const [logs, total] = await Promise.all([
|
||||
prisma.auditLog.findMany({
|
||||
where,
|
||||
orderBy: { timestamp: 'desc' },
|
||||
take: limit,
|
||||
skip: offset,
|
||||
}),
|
||||
prisma.auditLog.count({ where }),
|
||||
]);
|
||||
|
||||
res.json({ logs, total, limit, offset });
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// GET /api/audit-logs/:id — single log entry
|
||||
router.get('/:id', async (req, res, next) => {
|
||||
try {
|
||||
const log = await prisma.auditLog.findUnique({ where: { id: req.params.id } });
|
||||
if (!log) return res.status(404).json({ error: 'Audit log not found' });
|
||||
res.json(log);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,129 @@
|
||||
const router = require('express').Router();
|
||||
const { body, query } = require('express-validator');
|
||||
const prisma = require('../lib/prisma');
|
||||
const auditMiddleware = require('../middleware/auditMiddleware');
|
||||
const { validateRequest } = require('../middleware/errorHandler');
|
||||
|
||||
const statusValidation = [
|
||||
body('animal_id').notEmpty().withMessage('animal_id is required').isUUID().withMessage('animal_id must be a valid UUID'),
|
||||
body('date').notEmpty().withMessage('date is required').isISO8601().withMessage('date must be a valid ISO 8601 date (YYYY-MM-DD)'),
|
||||
body('experiment_description').optional().isString(),
|
||||
body('vitals').optional().isString(),
|
||||
body('treatment').optional().isString(),
|
||||
body('notes').optional().isString(),
|
||||
];
|
||||
|
||||
const statusUpdateValidation = [
|
||||
body('date').optional().isISO8601().withMessage('date must be a valid ISO 8601 date'),
|
||||
body('experiment_description').optional().isString(),
|
||||
body('vitals').optional().isString(),
|
||||
body('treatment').optional().isString(),
|
||||
body('notes').optional().isString(),
|
||||
];
|
||||
|
||||
// GET /api/daily-statuses?animalId=<uuid> — list for animal
|
||||
router.get(
|
||||
'/',
|
||||
[query('animalId').optional().isUUID().withMessage('animalId must be a valid UUID')],
|
||||
validateRequest,
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const where = req.query.animalId ? { animal_id: req.query.animalId } : {};
|
||||
const statuses = await prisma.dailyStatus.findMany({
|
||||
where,
|
||||
orderBy: { date: 'desc' },
|
||||
include: { animal: { select: { animal_name: true, animal_id_string: true } } },
|
||||
});
|
||||
res.json(statuses);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// GET /api/daily-statuses/:id — get one
|
||||
router.get('/:id', async (req, res, next) => {
|
||||
try {
|
||||
const status = await prisma.dailyStatus.findUnique({
|
||||
where: { id: req.params.id },
|
||||
include: { animal: true },
|
||||
});
|
||||
if (!status) return res.status(404).json({ error: 'Daily status not found' });
|
||||
res.json(status);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/daily-statuses — create
|
||||
router.post('/', statusValidation, validateRequest, async (req, res, next) => {
|
||||
try {
|
||||
const { animal_id, date, experiment_description, vitals, treatment, notes } = req.body;
|
||||
const status = await prisma.dailyStatus.create({
|
||||
data: {
|
||||
animal_id,
|
||||
date: new Date(date),
|
||||
experiment_description,
|
||||
vitals,
|
||||
treatment,
|
||||
notes,
|
||||
},
|
||||
});
|
||||
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
table_name: 'daily_statuses',
|
||||
record_id: status.id,
|
||||
action: 'CREATE',
|
||||
changes: { before: null, after: status },
|
||||
},
|
||||
});
|
||||
|
||||
res.status(201).json(status);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// PUT /api/daily-statuses/:id — update
|
||||
router.put(
|
||||
'/:id',
|
||||
auditMiddleware('daily_statuses', prisma.dailyStatus),
|
||||
statusUpdateValidation,
|
||||
validateRequest,
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const { date, experiment_description, vitals, treatment, notes } = req.body;
|
||||
const data = {};
|
||||
if (date !== undefined) data.date = new Date(date);
|
||||
if (experiment_description !== undefined) data.experiment_description = experiment_description;
|
||||
if (vitals !== undefined) data.vitals = vitals;
|
||||
if (treatment !== undefined) data.treatment = treatment;
|
||||
if (notes !== undefined) data.notes = notes;
|
||||
|
||||
const status = await prisma.dailyStatus.update({
|
||||
where: { id: req.params.id },
|
||||
data,
|
||||
});
|
||||
res.json(status);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// DELETE /api/daily-statuses/:id — delete
|
||||
router.delete(
|
||||
'/:id',
|
||||
auditMiddleware('daily_statuses', prisma.dailyStatus),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
await prisma.dailyStatus.delete({ where: { id: req.params.id } });
|
||||
res.status(204).send();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
@@ -0,0 +1,94 @@
|
||||
const router = require('express').Router();
|
||||
const { body } = require('express-validator');
|
||||
const prisma = require('../lib/prisma');
|
||||
const auditMiddleware = require('../middleware/auditMiddleware');
|
||||
const { validateRequest } = require('../middleware/errorHandler');
|
||||
|
||||
const experimentValidation = [
|
||||
body('title').trim().notEmpty().withMessage('Title is required').isLength({ max: 255 }).withMessage('Title must be ≤255 characters'),
|
||||
];
|
||||
|
||||
// GET /api/experiments — list all
|
||||
router.get('/', async (req, res, next) => {
|
||||
try {
|
||||
const experiments = await prisma.experiment.findMany({
|
||||
orderBy: { created_at: 'desc' },
|
||||
include: { _count: { select: { animals: true } } },
|
||||
});
|
||||
res.json(experiments);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// GET /api/experiments/:id — get one with animals
|
||||
router.get('/:id', async (req, res, next) => {
|
||||
try {
|
||||
const experiment = await prisma.experiment.findUnique({
|
||||
where: { id: req.params.id },
|
||||
include: { animals: true },
|
||||
});
|
||||
if (!experiment) return res.status(404).json({ error: 'Experiment not found' });
|
||||
res.json(experiment);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// POST /api/experiments — create
|
||||
router.post('/', experimentValidation, validateRequest, async (req, res, next) => {
|
||||
try {
|
||||
const { title } = req.body;
|
||||
const experiment = await prisma.experiment.create({ data: { title } });
|
||||
|
||||
// Write CREATE audit log
|
||||
await prisma.auditLog.create({
|
||||
data: {
|
||||
table_name: 'experiments',
|
||||
record_id: experiment.id,
|
||||
action: 'CREATE',
|
||||
changes: { before: null, after: experiment },
|
||||
},
|
||||
});
|
||||
|
||||
res.status(201).json(experiment);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
});
|
||||
|
||||
// PUT /api/experiments/:id — update
|
||||
router.put(
|
||||
'/:id',
|
||||
auditMiddleware('experiments', prisma.experiment),
|
||||
experimentValidation,
|
||||
validateRequest,
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
const { title } = req.body;
|
||||
const experiment = await prisma.experiment.update({
|
||||
where: { id: req.params.id },
|
||||
data: { title },
|
||||
});
|
||||
res.json(experiment);
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
// DELETE /api/experiments/:id — delete
|
||||
router.delete(
|
||||
'/:id',
|
||||
auditMiddleware('experiments', prisma.experiment),
|
||||
async (req, res, next) => {
|
||||
try {
|
||||
await prisma.experiment.delete({ where: { id: req.params.id } });
|
||||
res.status(204).send();
|
||||
} catch (err) {
|
||||
next(err);
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
module.exports = router;
|
||||
Reference in New Issue
Block a user