Files
inventory/Routes/computer.js

84 lines
2.7 KiB
JavaScript

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 || brand == "") || (!model || model == "" ) || (!state || state == "" ) || (!status || status == "" )) {
res.status(400).json({ error: 'Bad Request' });
}
const dateOfEntry = req.body.dateOfEntry || null;
const computer = new Computer(null, brand, model, state, dateOfEntry, 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, dateOfEntry, status } = req.body;
computer.brand = brand;
computer.model = model;
computer.state = state;
computer.dateOfEntry = dateOfEntry;
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;