Share
Explore

Full stack node.js web ecommerce app: Peanut's Pet Emporium Your ONLINE Source for bespoke, tailor made costumes for dogs

image.png
Here are 10 warm-up drills to get started with building the business logic for "Peanut's Pet Emporium":

1. Create a Basic Product Object:


const product = {
id: 1,
name: 'Super Dog Cape',
price: 19.99,
description: 'A red cape for your super dog!',
inStock: true
};
console.log(product);

2. Loop through Product Properties:


for (let key in product) {
console.log(`${key}: ${product[key]}`);
}

3. Array of Products:

const products = [
{ id: 1, name: 'Super Dog Cape', price: 19.99 },
{ id: 2, name: 'Dog Wizard Hat', price: 9.99 },
{ id: 3, name: 'Puppy Pirate Eye Patch', price: 4.99 }
];

4. Function to Find Product by ID:


function findProductById(id) {
return products.find(product => product.id === id);
}
console.log(findProductById(2));

5. Method to Add a New Product:


function addProduct(newProduct) {
products.push(newProduct);
}
addProduct({ id: 4, name: 'Canine Knight Armor', price: 49.99 });
console.log(products);

6. Loop to Display All Product Names:


products.forEach(product => {
console.log(product.name);
});

7. Try-Catch to Handle Errors:

function getProductPrice(id) {
try {
const product = findProductById(id);
if (!product) throw new Error('Product not found!');
return product.price;
} catch (error) {
console.error(error.message);
}
}
console.log(getProductPrice(5)); // This will throw an error since product with ID 5 doesn't exist.

8. Data Structure for User Cart:


const userCart = {
userId: 'user123', // we really need this to be an Object Reference
// not possible in JavaScript: Now we need TypeScript
items: [
{ productId: 1, quantity: 2 },
{ productId: 3, quantity: 1 }
]
};


error

Let's extend the example using TypeScript's strong typing features.

First, we'll define interfaces for the user, cart, and cart items.
Then, we'll create a user object that compositionally connects to the shopping cart.

// Define the structure for a cart item
interface CartItem {
productId: number;
quantity: number;
}

// Define the structure for a user cart
interface UserCart {
userId: string;
items: CartItem[];
}

// Define the structure for a user
interface User {
id: string;
name: string;
email: string;
cart: UserCart;
}

// Create a user object that includes the cart
const user: User = {
id: 'user123',
name: 'John Doe',
email: 'john.doe@example.com',
cart: {
userId: 'user123',
items: [
{ productId: 1, quantity: 2 },
{ productId: 3, quantity: 1 }
]
}
};

console.log(user);

In this example:
We've defined interfaces for CartItem, UserCart, and User.
The User interface compositionally includes a UserCart.
We've created a user object that adheres to the User interface and includes the cart data.
This approach ensures that our data structures are strongly typed, making it easier to catch potential type-related issues at compile-time.

9. Function to Calculate Total Cart Value:


function calculateCartTotal(cart) {
return cart.items.reduce((total, item) => {
const product = findProductById(item.productId);
return total + (product.price * item.quantity);
}, 0);
}
console.log(calculateCartTotal(userCart));

10. Method to Add an Item to the Cart:


function addItemToCart(cart, productId, quantity) {
const existingItem = cart.items.find(item => item.productId === productId);
if (existingItem) {
existingItem.quantity += quantity;
} else {
cart.items.push({ productId, quantity });
}
}
addItemToCart(userCart, 2, 1);
console.log(userCart);


These drills progressively introduce various JavaScript and Node.js concepts, building towards the business logic for "Peanut's Pet Emporium".
They can serve as a foundation, and you can expand upon them to create more complex functionalities for the e-commerce app.

ok

Here's a CSV representation of 25 product records for "Peanut's Pet Emporium":


id,name,price,description,in_stock
1,Super Dog Cape,19.99,A red cape for your super dog!,true
2,Dog Wizard Hat,9.99,Magical hat for spell-casting pups!,true
3,Puppy Pirate Eye Patch,4.99,For the adventurous sea-faring pup!,true
4,Canine Knight Armor,49.99,Protective gear for brave dog knights!,true
5,Doggy Detective Hat,14.99,For pups with a keen sense of mystery!,true
6,Pup's Princess Tiara,12.99,For the royal doggo in your life!,true
7,Space Dog Helmet,29.99,For pups dreaming of the stars!,true
8,Dog Dino Tail,24.99,Turn your pup into a cute little dino!,true
9,Puppy Elf Ears,7.99,Perfect for the festive season!,true
10,Dog's Cowboy Hat,16.99,For the wild west pup!,true
11,Canine Chef Hat,8.99,For pups who love to cook!,true
12,Doggy Diver Goggles,17.99,For the underwater adventurer!,true
13,Pup's Pilot Cap,18.99,For high-flying dogs!,true
14,Dog's Dragon Wings,27.99,Turn your pup into a mythical creature!,true
15,Puppy Pumpkin Hat,10.99,Perfect for Halloween!,true
16,Dog's Disco Wig,11.99,For the party-loving pup!,true
17,Canine Clown Wig,9.99,For pups who love to entertain!,true
18,Dog's Superhero Mask,6.99,For your little hero!,true
19,Pup's Viking Helmet,21.99,For the brave and bold dog!,true
20,Doggy Ballerina Tutu,15.99,For the graceful dancer!,true
21,Canine Camper Hat,13.99,For the nature-loving pup!,true
22,Dog's Racing Jacket,31.99,For the speedy doggo!,true
23,Puppy's Police Cap,14.99,For the law-abiding pup!,true
24,Dog's Rockstar Jacket,34.99,For the pup with a rock-n-roll soul!,true
25,Canine Captain's Hat,19.99,For the pup who's in charge!,true

You can save this CSV data into a file (e.g., products.csv) and then use it to import into your SQL database.
Ensure that the table structure in your database matches the columns in the CSV for a successful import.
Typescript code to import this csv from a text file and populate a suitable data structure for subsequent transport into a sql database
Let's create a TypeScript solution to read the CSV file and populate a suitable data structure.

1. Setting up the TypeScript project:

First, initialize a new Node.js project and install the required packages:

mkdir ts-csv-importer
cd ts-csv-importer
npm init -y
npm install typescript @types/node csv-parser fs
npx tsc --init

2. TypeScript Code:

Create a file named importer.ts:

import * as fs from 'fs';
import * as csv from 'csv-parser';

interface Product {
id: number;
name: string;
price: number;
description: string;
in_stock: boolean;
}

const products: Product[] = [];

fs.createReadStream('products.csv')
.pipe(csv())
.on('data', (row) => {
const product: Product = {
id: Number(row.id),
name: row.name,
price: Number(row.price),
description: row.description,
in_stock: row.in_stock.toLowerCase() === 'true'
};
products.push(product);
})
.on('end', () => {
console.log(products);
// Here, you can transport the 'products' array into a SQL database.
});

Explanation:

We're using the csv-parser library to read and parse the CSV file.
The Product interface defines the structure of a product.
We read the CSV file line by line, convert each line into a Product object, and push it to the products array.
Once the reading is complete, you can transport the products array into a SQL database.
To run the code, compile the TypeScript file and then execute the generated JavaScript:
bashCopy code
npx tsc importer.ts
node importer.js

This will print the array of products parsed from the CSV. You can then integrate this data structure with a SQL database library or ORM to insert the products into your database.
Want to print your doc?
This is not the way.
Try clicking the ⋯ next to your doc name or using a keyboard shortcut (
CtrlP
) instead.