75 lines
1.8 KiB
JavaScript
75 lines
1.8 KiB
JavaScript
const fs = require("fs");
|
|
const path = require("path");
|
|
|
|
class ControllerBuilder {
|
|
static build() {
|
|
const config = require("./configuration.json");
|
|
const controllerDir = path.join(__dirname, "release/controllers");
|
|
|
|
// Create release/controllers directory
|
|
if (!fs.existsSync(controllerDir))
|
|
fs.mkdirSync(controllerDir, { recursive: true });
|
|
|
|
config.model.forEach((model) => {
|
|
const controllerCode = `const express = require('express');
|
|
const router = express.Router();
|
|
const model = require('../models/${model.name}.model.js');
|
|
|
|
// CREATE
|
|
router.post('/', async (req, res) => {
|
|
try {
|
|
const data = await model.create(req.body);
|
|
res.status(201).json(data);
|
|
} catch (error) {
|
|
res.status(400).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// READ ALL
|
|
router.get('/', async (req, res) => {
|
|
try {
|
|
const data = await model.findAll();
|
|
res.json(data);
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// UPDATE
|
|
router.put('/:id', async (req, res) => {
|
|
try {
|
|
const updated = await model.update(req.body, {
|
|
where: { id: req.params.id }
|
|
});
|
|
if (updated[0] === 0) return res.status(404).json({ error: 'Not found' });
|
|
res.json(await model.findByPk(req.params.id));
|
|
} catch (error) {
|
|
res.status(400).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
// DELETE
|
|
router.delete('/:id', async (req, res) => {
|
|
try {
|
|
const deleted = await model.destroy({
|
|
where: { id: req.params.id }
|
|
});
|
|
if (!deleted) return res.status(404).json({ error: 'Not found' });
|
|
res.status(204).send();
|
|
} catch (error) {
|
|
res.status(500).json({ error: error.message });
|
|
}
|
|
});
|
|
|
|
module.exports = router;`;
|
|
|
|
fs.writeFileSync(
|
|
path.join(controllerDir, `${model.name}.controller.js`),
|
|
controllerCode
|
|
);
|
|
});
|
|
}
|
|
}
|
|
|
|
module.exports = ControllerBuilder;
|