Skip to main content

Overview

File: src/tools/ProductsTool.ts Six tools demonstrating complete product management with the Products API.

Tools Included

Search

Find products by query

Get All

List with pagination

Create

Add new products

Update

Modify existing

Get By ID

Get specific product

Delete

Remove products

Example Tools

SearchProductsTool

import { LuaTool, Products } from 'lua-cli';
import { z } from 'zod';

export class SearchProductsTool implements LuaTool {
  name = "search_products";
  description = "Search products by name or description";
  
  inputSchema = z.object({
    query: z.string().describe("Search query")
  });

  async execute(input: z.infer<typeof this.inputSchema>) {
    const results = await Products.search(input.query);
    
    return {
      products: results.data.map(p => ({
        id: p.id,
        name: p.name,
        price: `$${p.price.toFixed(2)}`,
        inStock: p.inStock
      })),
      count: results.data.length
    };
  }
}

CreateProductTool

export class CreateProductTool implements LuaTool {
  name = "create_product";
  description = "Add a new product to the catalog";
  
  inputSchema = z.object({
    name: z.string(),
    price: z.number().positive(),
    category: z.string().optional(),
    sku: z.string().optional(),
    description: z.string().optional()
  });

  async execute(input: z.infer<typeof this.inputSchema>) {
    const result = await Products.create({
      ...input,
      id: generateId(),  // Generate unique ID
      inStock: true
    });
    
    return {
      success: true,
      productId: result.product.id,
      message: `Product "${input.name}" created`
    };
  }
}

UpdateProductTool

export class UpdateProductTool implements LuaTool {
  name = "update_product";
  description = "Update product information";
  
  inputSchema = z.object({
    id: z.string(),
    name: z.string().optional(),
    price: z.number().positive().optional(),
    inStock: z.boolean().optional()
  });

  async execute(input: z.infer<typeof this.inputSchema>) {
    const { id, ...updates } = input;
    
    await Products.update(updates, id);
    
    return {
      success: true,
      message: "Product updated successfully"
    };
  }
}

Use Cases

E-commerce Catalog

// Browse products (page 1, limit 20)
const products = await Products.get(1, 20);

// Search for specific items (default limit: 5)
const laptops = await Products.search('laptop');

// Search with custom limit
const moreLaptops = await Products.search('laptop', 10);

// Get product details
const product = await Products.getById(laptops.data[0].id);

Inventory Management

// Update stock status
await Products.update({ inStock: false }, productId);

// Update price
await Products.update({ price: 899.99 }, productId);

// Bulk update (page 1, limit 100)
const products = await Products.get(1, 100);
for (const product of products.data) {
  if (product.category === 'Electronics') {
    await Products.update({ onSale: true }, product.id);
  }
}

Admin Dashboard

// Get all products (page 1, limit 1000)
const all = await Products.get(1, 1000);

// Statistics
const totalValue = all.data.reduce((sum, p) => sum + p.price, 0);
const inStock = all.data.filter(p => p.inStock).length;
const categories = [...new Set(all.data.map(p => p.category))];

Using save() Method (New!)

// Get product and modify multiple fields
const product = await Products.getById('product_123');

// Modify properties directly
product.price = 899.99;
product.inStock = true;
product.category = 'Electronics - Sale';
product.description = 'Updated description';

// Save all changes at once
await product.save();

// Much cleaner than calling update()!

Practical Example: Bulk Price Update

export class BulkDiscountTool implements LuaTool {
  name = "apply_discount";
  description = "Apply discount to products";
  
  inputSchema = z.object({
    category: z.string(),
    discountPercent: z.number()
  });

  async execute(input: z.infer<typeof this.inputSchema>) {
    const products = await Products.get(1, 1000);
    
    for (const product of products.data) {
      if (product.category === input.category) {
        // Modify and save
        product.price = product.price * (1 - input.discountPercent / 100);
        await product.save();
      }
    }
    
    return { message: `Discount applied to ${input.category} products` };
  }
}

What You’ll Learn

CRUD Operations

Create, Read, Update, Delete

Pagination

Handle large datasets

Search

Query product catalog

Data Formatting

Transform API responses

Next Steps