Files
JS/webseite-gulp-ts/backend/model/ProductModel.js
Philippe Torrel 44428b0495 added prototype
2026-08-03 14:46:13 +02:00

114 lines
2.2 KiB
JavaScript

import fs from 'node:fs';
import { v4 as id } from 'uuid';
// Factoryfunction
const ProductModel = () => {
let products = [];
const load = () => {
try {
products = JSON.parse(fs.readFileSync('./data/products.json', 'utf-8'));
} catch (error) {
console.log('Something went wrong: ', error);
products = [];
}
};
const reset = () => {
try {
products = JSON.parse(fs.readFileSync('./data/products.bakup.json', 'utf-8'));
} catch (error) {
console.log('Something went wrong: ', error);
products = [];
}
};
const save = () => {
try {
fs.writeFileSync('./data/products.json', JSON.stringify(products, null, 2), 'utf-8');
} catch (error) {
console.log('Something went wrong:', error);
}
};
const getAll = () => {
return products;
};
const get = (id) => {
const product = products.find((product) => {
return product._id === id;
});
// Guard
if (!product) return null;
return product;
};
const add = (product) => {
const { name, price } = product;
if (!hasAllProps(product)) return false;
products.push({
_id: id(),
name,
price: Number(price.toFixed(2)),
position: products.length + 1,
});
return true;
};
const update = (product) => {
const foundIdx = products.findIndex((obj) => {
return obj._id === product._id;
});
// Guard
if (foundIdx === -1 || !hasAllProps(product)) return false;
products[foundIdx] = product;
return true;
};
const remove = (id) => {
const foundIdx = products.findIndex((obj) => {
return obj._id === id;
});
// Guard
if (foundIdx === -1) return false;
products.splice(foundIdx, 1);
return true;
};
/**
* hasAllProps - Überprüfung ob Product "name" und "price"
* @return boolean
**/
const hasAllProps = (product) => {
// return Object.hasOwn(product, 'name') && Object.hasOwn(product, 'price');
const keys = Object.keys(product); // => ['name', 'price']
return keys.includes('name') && keys.includes('price');
};
return {
// load: load
load,
save,
add,
getAll,
get,
update,
delete: remove,
reset,
};
};
export default ProductModel;