33 lines
912 B
TypeScript
33 lines
912 B
TypeScript
import fs from 'node:fs';
|
|
import { v4 as id } from 'uuid';
|
|
|
|
const PRODUCTS_PATH = '../data/products.json';
|
|
|
|
/** Ein vollständiges Produkt, so wie es in products.json steht. */
|
|
interface Product {
|
|
_id: string;
|
|
position: number;
|
|
name: string;
|
|
price: number;
|
|
}
|
|
|
|
/** Produkt aus der Datei - _id und position können noch fehlen. */
|
|
type ProductInput = Omit<Product, '_id' | 'position'> & Partial<Pick<Product, '_id' | 'position'>>;
|
|
|
|
console.log(id()); // 97412ca6-c7a8-4868-a49b-3cf4c2258dd8
|
|
|
|
try {
|
|
const data = JSON.parse(fs.readFileSync(PRODUCTS_PATH, 'utf-8')) as ProductInput[];
|
|
|
|
const products: Product[] = data.map((product, index) => {
|
|
return { _id: product._id || id(), position: index + 1, ...product };
|
|
});
|
|
|
|
console.log(products);
|
|
|
|
fs.writeFileSync(PRODUCTS_PATH, JSON.stringify(products, null, 2), 'utf-8');
|
|
console.log('File modified');
|
|
} catch (error) {
|
|
console.log(error);
|
|
}
|