### E-commerce Workflow Integration Example - TypeScript Source: https://context7.com/upstash/context7test/llms.txt Demonstrates a complete e-commerce workflow integration using UserService, AuthService, ProductService, and OrderService. This example covers user creation, authentication, product management, order creation, and status updates. It utilizes async/await for asynchronous operations. ```typescript import { UserService } from './src/user'; import { AuthService } from './src/auth'; import { ProductService } from './src/product'; import { OrderService } from './src/order'; async function main() { // Initialize services const userService = new UserService(); const authService = new AuthService(); const productService = new ProductService(); const orderService = new OrderService(); // Create a user and authenticate const user = await userService.createUser('jane_doe', 'jane@example.com'); const token = await authService.login('jane_doe', 'password123'); // Verify authentication if (await authService.verifyToken(token)) { // Create products const product1 = await productService.createProduct('Laptop Stand', 79.99); const product2 = await productService.createProduct('USB Hub', 24.99); // Update stock await productService.updateStock(product1.id, 50); await productService.updateStock(product2.id, 100); // Create an order const order = await orderService.createOrder(user.id, [ { productId: product1.id, quantity: 1, price: product1.price }, { productId: product2.id, quantity: 2, price: product2.price }, ]); // Process the order await orderService.updateStatus(order.id, 'processing'); await orderService.updateStatus(order.id, 'shipped'); console.log(`Order ${order.id} created with total: $${order.total}`); } } main().catch(console.error); ``` -------------------------------- ### Install Test Refresh Package Source: https://github.com/upstash/context7test/blob/default-context-test/README.md Installs the required test-refresh dependency via npm. This command is necessary to include the project services in your environment. ```bash npm install test-refresh ``` -------------------------------- ### Initialize and Use Project Services Source: https://github.com/upstash/context7test/blob/default-context-test/README.md Demonstrates how to import and instantiate the User, Auth, Product, and Order services. It shows a typical workflow of creating a user, a product, and placing an order. ```typescript import { UserService } from './src/user'; import { AuthService } from './src/auth'; import { ProductService } from './src/product'; import { OrderService } from './src/order'; const userService = new UserService(); const productService = new ProductService(); const orderService = new OrderService(); const user = await userService.createUser('john', 'john@example.com'); const product = await productService.createProduct('Widget', 9.99); const order = await orderService.createOrder(user.id, [{ productId: product.id, price: 9.99, quantity: 2 }]); ``` -------------------------------- ### Create Product - ProductService (TypeScript) Source: https://context7.com/upstash/context7test/llms.txt Creates a new product with a given name and price. It returns a Product object with a unique ID, provided details, and an initial stock of zero. This function is part of the ProductService. ```typescript import { ProductService, Product } from './src/product'; const productService = new ProductService(); // Create a new product const product: Product = await productService.createProduct('Wireless Mouse', 29.99); console.log(product); // Output: // { // id: 'prod_xyz789', // name: 'Wireless Mouse', // price: 29.99, // stock: 0 // } ``` -------------------------------- ### List Products - ProductService (TypeScript) Source: https://context7.com/upstash/context7test/llms.txt Retrieves all products from the catalog, returning an array of Product objects. It includes details like ID, name, price, and stock levels. This function is part of the ProductService. ```typescript import { ProductService, Product } from './src/product'; const productService = new ProductService(); // Get all products const products: Product[] = await productService.listProducts(); console.log(`Total products: ${products.length}`); products.forEach(product => { console.log(`${product.name}: $${product.price} (${product.stock} in stock)`); }); // Filter products by availability const inStockProducts = products.filter(p => p.stock > 0); ``` -------------------------------- ### Create User - UserService (TypeScript) Source: https://context7.com/upstash/context7test/llms.txt Creates a new user with the specified username and email. It returns a User object including a unique ID, credentials, and a creation timestamp. This function is part of the UserService. ```typescript import { UserService, User } from './src/user'; const userService = new UserService(); // Create a new user const user: User = await userService.createUser('john_doe', 'john@example.com'); console.log(user); // Output: // { // id: 'abc123xyz', // username: 'john_doe', // email: 'john@example.com', // createdAt: 2024-01-15T10:30:00.000Z // } ``` -------------------------------- ### Create Order with Items - TypeScript Source: https://context7.com/upstash/context7test/llms.txt Creates a new order for a user with specified items. It automatically calculates the total price based on product prices and quantities. The function returns an Order object with a 'pending' status. Dependencies include OrderService, Order, and OrderItem interfaces. ```typescript import { OrderService, Order, OrderItem } from './src/order'; const orderService = new OrderService(); // Define order items const items: OrderItem[] = [ { productId: 'prod_001', quantity: 2, price: 29.99 }, { productId: 'prod_002', quantity: 1, price: 49.99 }, ]; // Create the order const order: Order = await orderService.createOrder('user_abc123', items); console.log(order); // Output: // { // id: 'order_xyz789', // userId: 'user_abc123', // items: [ // { productId: 'prod_001', quantity: 2, price: 29.99 }, // { productId: 'prod_002', quantity: 1, price: 49.99 } // ], // total: 109.97, // status: 'pending', // createdAt: 2024-01-15T10:30:00.000Z // } ``` -------------------------------- ### Login User - AuthService (TypeScript) Source: https://context7.com/upstash/context7test/llms.txt Authenticates a user using username and password. It returns an authentication token string for subsequent API requests. This function is part of the AuthService. ```typescript import { AuthService } from './src/auth'; const authService = new AuthService(); // Authenticate user and get token const token: string = await authService.login('john_doe', 'securePassword123'); console.log(token); // Output: 'token-k7x9m2abc' // Use token in subsequent requests const headers = { 'Authorization': `Bearer ${token}` }; ``` -------------------------------- ### Update Product Stock - ProductService (TypeScript) Source: https://context7.com/upstash/context7test/llms.txt Updates the stock quantity for a specific product, useful for inventory management. It can also handle batch updates. This function is part of the ProductService. ```typescript import { ProductService } from './src/product'; const productService = new ProductService(); // Update product stock const productId = 'prod_xyz789'; await productService.updateStock(productId, 100); console.log(`Stock updated for product ${productId}`); // Batch stock update example const stockUpdates = [ { id: 'prod_001', quantity: 50 }, { id: 'prod_002', quantity: 75 }, { id: 'prod_003', quantity: 30 }, ]; for (const update of stockUpdates) { await productService.updateStock(update.id, update.quantity); } ``` -------------------------------- ### Retrieve User Order History - TypeScript Source: https://context7.com/upstash/context7test/llms.txt Fetches the complete order history for a given user ID. The orders are returned as an array of Order objects, sorted by their creation date. This is useful for displaying a user's purchase history and calculating total spending. It depends on OrderService and Order interface. ```typescript import { OrderService, Order } from './src/order'; const orderService = new OrderService(); // Get user's order history const userId = 'user_abc123'; const orders: Order[] = await orderService.getOrderHistory(userId); console.log(`User has ${orders.length} orders`); // Display order summary orders.forEach(order => { console.log(`Order ${order.id}: $${order.total} - ${order.status}`); }); // Calculate total spent by user const totalSpent = orders .filter(o => o.status !== 'cancelled') .reduce((sum, o) => sum + o.total, 0); console.log(`Total spent: $${totalSpent.toFixed(2)}`); ``` -------------------------------- ### Verify Token - AuthService (TypeScript) Source: https://context7.com/upstash/context7test/llms.txt Validates an authentication token. It returns true if the token is valid and false otherwise, used for protecting routes and validating sessions. This function is part of the AuthService. ```typescript import { AuthService } from './src/auth'; const authService = new AuthService(); // Verify a token const token = 'token-k7x9m2abc'; const isValid: boolean = await authService.verifyToken(token); if (isValid) { console.log('Token is valid, proceed with request'); } else { console.log('Invalid token, authentication required'); } // Example middleware usage async function authMiddleware(token: string): Promise { const authService = new AuthService(); return await authService.verifyToken(token); } ``` -------------------------------- ### Find User by ID - UserService (TypeScript) Source: https://context7.com/upstash/context7test/llms.txt Retrieves a user by their unique identifier. It returns the User object if found, otherwise null. This function is part of the UserService. ```typescript import { UserService, User } from './src/user'; const userService = new UserService(); // Look up a user by ID const user: User | null = await userService.findById('abc123xyz'); if (user) { console.log(`Found user: ${user.username}`); } else { console.log('User not found'); } ``` -------------------------------- ### Update Order Status - TypeScript Source: https://context7.com/upstash/context7test/llms.txt Updates the status of an existing order. This function supports lifecycle management for orders, allowing transitions through statuses like 'pending', 'processing', 'shipped', 'delivered', and 'cancelled'. It requires the OrderService and OrderStatus enum. ```typescript import { OrderService, OrderStatus } from './src/order'; const orderService = new OrderService(); // Update order status through lifecycle const orderId = 'order_xyz789'; await orderService.updateStatus(orderId, 'processing'); console.log('Order is being processed'); await orderService.updateStatus(orderId, 'shipped'); console.log('Order has been shipped'); await orderService.updateStatus(orderId, 'delivered'); console.log('Order delivered successfully'); // Handle cancellation async function cancelOrder(orderId: string): Promise { await orderService.updateStatus(orderId, 'cancelled'); console.log(`Order ${orderId} has been cancelled`); } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.