init webseite ts and claude
This commit is contained in:
113
webseite-ts-claude/backend/model/ProductModel.js
Normal file
113
webseite-ts-claude/backend/model/ProductModel.js
Normal file
@@ -0,0 +1,113 @@
|
||||
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;
|
||||
Reference in New Issue
Block a user