Files
inventory/Classes/Computer.js
2023-11-23 16:01:56 +01:00

110 lines
3.2 KiB
JavaScript

import { database } from './Database';
class Computer {
constructor(id, brand, model, state, status) {
this.id = id;
this.brand = brand;
this.model = model;
this.status = status;
this.state = state;
}
async get (id) {
try {
const rows = await database.execute('SELECT * FROM computers WHERE id = ?', [id]);
if (rows.length === 0) {
throw new Error('Computer not found');
} else {
this.id = rows[0].id;
this.brand = rows[0].brand;
this.model = rows[0].model;
this.status = rows[0].status;
this.state = rows[0].state;
}
} catch (error) {
console.error('Error getting computer:', error);
throw error;
}
}
async create() {
try {
const result = await database.execute(
'INSERT INTO computers (brand, model, state, status) VALUES (?, ?, ?, ?)',
[this.brand, this.model, this.state, this.status]
);
this.id = result.insertId;
} catch (error) {
console.error('Error creating computer:', error);
throw error;
}
}
async update() {
try {
await database.execute(
'UPDATE computers SET brand = ?, model = ?, state = ?, status = ? WHERE id = ?',
[this.brand, this.model, this.state, this.status, this.id]
);
} catch (error) {
console.error('Error updating computer:', error);
throw error;
}
}
async delete() {
try {
await database.execute('DELETE FROM computers WHERE id = ?', [this.id]);
} catch (error) {
console.error('Error deleting computer:', error);
throw error;
}
}
}
// Computer list class
class Computers extends Array {
async getAll() {
try {
const rows = await database.execute('SELECT * FROM computers');
this.length = 0; // Clear the existing array
rows.forEach(row => {
const computer = new Computer(row.id, row.brand, row.model, row.state, row.status);
this.push(computer);
});
} catch (error) {
console.error('Error getting computers:', error);
throw error;
}
}
async create(brand, model, state, status) {
try {
const computer = new Computer(null, brand, model, state, status);
await computer.create();
this.push(computer);
} catch (error) {
console.error('Error creating computer:', error);
throw error;
}
}
async delete(id) {
try {
const computerIndex = this.findIndex(computer => computer.id === id);
if (computerIndex === -1) {
throw new Error('Computer not found');
}
const computer = this[computerIndex];
await computer.delete();
this.splice(computerIndex, 1);
} catch (error) {
console.error('Error deleting computer:', error);
throw error;
}
}
}
export { Computer, Computers };