multy-stub/server/routers/kfu-m-24-1/eng-it-lean/units/index.js

63 lines
1.6 KiB
JavaScript
Raw Normal View History

const fs = require('fs');
const path = require('path');
const router = require('express').Router();
module.exports = router;
const data = require('./data/units.json');
router.get('/', (req, res) => {
res.send(data);
});
router.put('/', (req, res) => {
2025-01-30 12:41:00 +03:00
const newUnit = req.body;
2025-01-30 12:41:00 +03:00
if (!newUnit) {
return res.status(400).send('No new unit to be added');
}
if (!data) {
return res.status(500).send('No data to be updated');
}
2025-01-30 12:41:00 +03:00
const newId = data.length + 1;
const fileName = newUnit.name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase();
fs.writeFileSync(path.join(__dirname, 'data', `${fileName}.md`), newUnit.content);
2025-01-30 12:41:00 +03:00
data.push({ id: newId, fileName: fileName, name: newUnit.name });
2025-01-30 12:41:00 +03:00
fs.writeFileSync(path.join(__dirname, 'data', 'units.json'), JSON.stringify(data));
res.status(200).send(data);
});
router.delete('/:id', (req, res) => {
2025-01-30 12:41:00 +03:00
const id = parseInt(req.params.id);
const index = data.findIndex((unit) => unit.id === id);
2025-01-30 12:41:00 +03:00
if (index < 0) {
return res.status(404).send('Not found');
}
2025-01-30 12:41:00 +03:00
data.splice(index, 1);
fs.writeFileSync(path.join(__dirname, 'data', 'units.json'), JSON.stringify(data));
res.send({ message: `Unit with ID ${id} deleted` });
});
router.get('/:id', (req, res) => {
const id = parseInt(req.params.id);
const unit = data.find((unit) => unit.id === id);
if (!unit) {
return res.status(404).send('Not found');
}
const unitFilepath = path.join(__dirname, 'data', `${unit.filename}.md`);
const unitContent = fs.readFileSync(unitFilepath, 'utf-8');
if (!unitContent) {
return res.status(404).send('Not found');
}
res.send({ ...unit, content: unitContent });
});