FIrst commit
This commit is contained in:
83
Routes/computer.js
Normal file
83
Routes/computer.js
Normal file
@@ -0,0 +1,83 @@
|
||||
import express from 'express';
|
||||
import { Computer, Computers } from '../Classes/Computer';
|
||||
|
||||
const router = express.Router();
|
||||
|
||||
// GET all computers
|
||||
router.get('/', async (req, res) => {
|
||||
const computers = new Computers();
|
||||
await computers.getAll();
|
||||
try {
|
||||
|
||||
res.status(200).json(computers);
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Internal Server Error' });
|
||||
}
|
||||
});
|
||||
|
||||
// GET a computer by ID
|
||||
router.get('/:id', async (req, res) => {
|
||||
try {
|
||||
const computer = new Computer();
|
||||
await computer.get(req.params.id);
|
||||
if (computer.brand === null) {
|
||||
res.status(404).json({ error: 'Computer not found' });
|
||||
} else {
|
||||
res.status(200).json(computer);
|
||||
}
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Internal Server Error' });
|
||||
}
|
||||
});
|
||||
|
||||
// POST a new computer
|
||||
router.post('/', async (req, res) => {
|
||||
try {
|
||||
const { brand, model, state, status } = req.body;
|
||||
if (!brand || !model || !state || !status) {
|
||||
res.status(400).json({ error: 'Bad Request' });
|
||||
}
|
||||
const computer = new Computer(null, brand, model, state, status);
|
||||
await computer.create();
|
||||
res.status(201).json({ message: 'Computer created successfully' });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Internal Server Error' });
|
||||
}
|
||||
});
|
||||
|
||||
// PUT (update) a computer by ID
|
||||
router.put('/:id', async (req, res) => {
|
||||
try {
|
||||
const computer = new Computer();
|
||||
await computer.get(req.params.id);
|
||||
if (computer.brand === null) {
|
||||
res.status(404).json({ error: 'Computer not found' });
|
||||
}
|
||||
const { brand, model, state, status } = req.body;
|
||||
computer.brand = brand;
|
||||
computer.model = model;
|
||||
computer.state = state;
|
||||
computer.status = status;
|
||||
await computer.update();
|
||||
res.status(200).json({ message: 'Computer updated successfully' });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Internal Server Error' });
|
||||
}
|
||||
});
|
||||
|
||||
// DELETE a computer by ID
|
||||
router.delete('/:id', async (req, res) => {
|
||||
try {
|
||||
const computer = new Computer();
|
||||
await computer.get(req.params.id);
|
||||
if (computer.brand === null) {
|
||||
res.status(404).json({ error: 'Computer not found' });
|
||||
}
|
||||
await computer.delete();
|
||||
res.status(200).json({ message: 'Computer deleted successfully' });
|
||||
} catch (error) {
|
||||
res.status(500).json({ error: 'Internal Server Error' });
|
||||
}
|
||||
});
|
||||
|
||||
export default router;
|
||||
Reference in New Issue
Block a user