162 lines
2.1 KiB
JavaScript
162 lines
2.1 KiB
JavaScript
const db = require("../config/database");
|
|
|
|
|
|
class ProductRepository {
|
|
|
|
|
|
getAll() {
|
|
|
|
return db.prepare(`
|
|
|
|
SELECT
|
|
|
|
products.*,
|
|
|
|
categories.name AS category_name,
|
|
|
|
categories.icon AS category_icon
|
|
|
|
|
|
FROM products
|
|
|
|
|
|
LEFT JOIN categories
|
|
|
|
ON categories.id = products.category_id
|
|
|
|
|
|
ORDER BY products.name
|
|
|
|
`).all();
|
|
|
|
}
|
|
|
|
|
|
|
|
findById(id) {
|
|
|
|
return db.prepare(`
|
|
|
|
SELECT *
|
|
|
|
FROM products
|
|
|
|
WHERE id = ?
|
|
|
|
`).get(id);
|
|
|
|
}
|
|
|
|
|
|
|
|
create(data) {
|
|
|
|
|
|
return db.prepare(`
|
|
|
|
INSERT INTO products
|
|
|
|
(
|
|
name,
|
|
category_id,
|
|
barcode
|
|
)
|
|
|
|
VALUES (?, ?, ?)
|
|
|
|
`).run(
|
|
|
|
data.name,
|
|
|
|
data.category_id || null,
|
|
|
|
data.barcode || null
|
|
|
|
);
|
|
|
|
|
|
}
|
|
|
|
|
|
createMany(products) {
|
|
const insert = db.prepare(`
|
|
|
|
INSERT INTO products (name, category_id, barcode)
|
|
|
|
VALUES (?, ?, ?)
|
|
|
|
`);
|
|
|
|
const insertMany = db.transaction((items) => {
|
|
for (const product of items) {
|
|
insert.run(
|
|
product.name,
|
|
product.category_id || null,
|
|
product.barcode || null
|
|
);
|
|
}
|
|
});
|
|
|
|
insertMany(products);
|
|
return products.length;
|
|
}
|
|
|
|
|
|
update(id, data) {
|
|
|
|
return db.prepare(`
|
|
|
|
UPDATE products
|
|
|
|
SET name = ?, category_id = ?
|
|
|
|
WHERE id = ?
|
|
|
|
`).run(
|
|
|
|
data.name,
|
|
|
|
data.category_id || null,
|
|
|
|
id
|
|
|
|
);
|
|
|
|
}
|
|
|
|
|
|
hasListItems(id) {
|
|
|
|
return db.prepare(`
|
|
|
|
SELECT 1
|
|
|
|
FROM shopping_list_items
|
|
|
|
WHERE product_id = ?
|
|
|
|
LIMIT 1
|
|
|
|
`).get(id) !== undefined;
|
|
|
|
}
|
|
|
|
|
|
delete(id) {
|
|
|
|
return db.prepare(`
|
|
|
|
DELETE FROM products
|
|
|
|
WHERE id = ?
|
|
|
|
`).run(id);
|
|
|
|
}
|
|
|
|
|
|
|
|
}
|
|
|
|
|
|
module.exports = new ProductRepository(); |