UNPKG

@simpleapps-com/augur-api

Version:

TypeScript client library for Augur microservices API endpoints

352 lines (275 loc) • 11.7 kB
# Experience the Magic: Zero to Production in 30 Seconds Transform enterprise API complexity into pure business intent with intelligent discovery and context-aware client generation. ## The Magic Revealed Watch enterprise API chaos become elegant business logic: ```typescript import { AugurAPI } from '@simpleapps-com/augur-api'; // Instead of this enterprise nightmare (35+ lines) const userJwt = await getToken({ req: request }); if (!userJwt?.jwtToken) { throw new Error('Authentication failed'); } const apiConfig = { siteId: context.siteId, bearerToken: userJwt.jwtToken, timeout: 30000, retries: 3, headers: { 'x-site-id': context.siteId } }; const api = new AugurAPI(apiConfig); // Pure business intent ✨ const api = AugurAPI.fromContext(context); // Ask for anything - the system finds it const userOps = await api.findEndpoint('user management'); const inventory = await api.findEndpoint('stock levels'); const pricing = await api.findEndpoint('product pricing'); // Code that reads like business requirements const users = await api.joomla.users.list({ limit: 10, edgeCache: 2 }); const availability = await api.vmi.invProfileHdr.checkAvailability(warehouse); const price = await api.pricing.getPrice({ customerId, itemId, quantity }); ``` ## Installation - One Command ```bash npm install @simpleapps-com/augur-api ``` ## First Contact: The 30-Second Demo ### Instant Context Recognition ```typescript // Your context object (middleware, tool handlers, etc.) const context = { siteId: 'my-site-123', jwt: 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...', userId: 456 }; // Magic happens here - zero configuration const api = AugurAPI.fromContext(context); // Verify the magic worked const services = await api.discover(); console.log(`šŸš€ Connected to ${services.length} business services`); console.log('Available capabilities:'); services.forEach(s => console.log(` ${s.serviceName}: ${s.endpointCount} operations`)); ``` **Expected output:** ``` šŸš€ Connected to 26 active business services Available capabilities: joomla: 24 operations commerce: 18 operations pricing: 12 operations vmi: 31 operations ... ``` ### Natural Language Discovery ```typescript // Never memorize endpoints again const userStuff = await api.findEndpoint('user management'); console.log('User operations found:'); userStuff.forEach(result => { console.log(` ${result.endpoint.fullPath} (${result.score.toFixed(2)})`); }); // Find inventory operations const inventoryOps = await api.findEndpoint('stock management'); console.log('Inventory operations found:'); inventoryOps.forEach(result => { console.log(` ${result.endpoint.fullPath} - ${result.matchReason}`); }); ``` ## Business Domain Intelligence The platform understands your business context and connects related operations: ### E-commerce Workflow Discovery ```typescript // Search by business process, not technical implementation const ecommerce = await api.findEndpoint('customer shopping experience'); // Platform suggests complete workflow: // 1. Product discovery: api.opensearch.itemSearch.search() // 2. Pricing calculation: api.pricing.getPrice() // 3. Cart management: api.commerce.cartHeaders.lookup() // 4. Checkout process: api.commerce.checkout.get() // 5. Payment processing: api.payments.unified.transactionSetup() // Execute the workflow const products = await api.opensearch.itemSearch.search({ q: 'electrical wire 12 AWG', searchType: 'query', size: 20, edgeCache: 4 // Intelligent caching }); const pricing = await api.pricing.getPrice({ customerId: 12345, itemId: products.data.items[0].item_id, quantity: 100, edgeCache: 3 // Business-aware TTL }); ``` ### Inventory Management Intelligence ```typescript // Natural language reveals complex operations const inventory = await api.findEndpoint('warehouse stock management'); // Platform maps the complete inventory ecosystem: const warehouses = await api.vmi.warehouses.list({ customerId: 12345, edgeCache: 4 // Reference data cached longer }); const availability = await api.vmi.invProfileHdr.checkAvailability(warehouses.data[0].warehouse_uid, { q: 'electrical' // Smart search within inventory }); // Context-aware replenishment await api.vmi.invProfileHdr.replenish(warehouse.warehouse_uid, { distributor_uid: 789, restock_items: [ { inv_mast_uid: 456, qty_to_order: 100.0 } ] }); ``` ## Context Patterns That Just Work ### Framework Integration Magic ```typescript // Express.js middleware app.use((req, res, next) => { req.api = AugurAPI.fromContext({ siteId: req.headers['x-site-id'], jwt: req.headers.authorization?.replace('Bearer ', ''), userId: req.user?.id }); next(); }); // Next.js API routes export default async function handler(req, res) { const api = AugurAPI.fromContext({ siteId: process.env.NEXT_PUBLIC_SITE_ID, jwt: req.session.accessToken }); const users = await api.joomla.users.list(); res.json(users); } // React components with hooks function useAugurAPI() { const { session } = useAuth(); return useMemo(() => AugurAPI.fromContext({ siteId: process.env.REACT_APP_SITE_ID, jwt: session?.token }), [session]); } ``` ### Dual Access Pattern Innovation Every endpoint provides two access patterns for maximum developer productivity: ```typescript // Metadata-rich response (when you need context) const response = await api.joomla.users.list({ limit: 10 }); console.log(`Found ${response.data.length} of ${response.totalResults} users`); console.log(`Request status: ${response.message}`); console.log(`Response metadata:`, response.params); // Pure data access (when you just want the data) const users = await api.joomla.users.listData({ limit: 10 }); console.log(users); // Direct array - no wrapper object // Both methods support the same parameters and caching const cachedUsers = await api.joomla.users.listData({ limit: 10, edgeCache: 2 // Cache for 2 hours }); ``` ## Business Capability Explorer The platform connects you to comprehensive business operations across 26 active microservices: | Business Domain | Platform Services | Intelligence Level | |-----------------|-------------------|-------------------| | **User & Identity** | `joomla.users`, `customers.customer` | Cross-service user correlation | | **E-commerce** | `commerce.cartHeaders`, `opensearch.itemSearch`, `pricing.getPrice` | Complete shopping workflows | | **Inventory** | `vmi.warehouses`, `vmi.invProfileHdr`, `items.products` | Supply chain intelligence | | **Orders & Fulfillment** | `orders.orders`, `payments.unified`, `nexus.binTransfers` | End-to-end order processing | | **Content & AI** | `agrSite.settings`, `p21Pim.items.suggestWebDescription` | AI-enhanced content management | ## Intelligent Caching Architecture Business-aware caching that understands data volatility: ```typescript // Reference data - cache aggressively (8 hours) const categories = await api.items.categories.list({ edgeCache: 8 }); const distributors = await api.vmi.distributors.list({ edgeCache: 8 }); // Operational data - moderate caching (2-4 hours) const users = await api.joomla.users.list({ limit: 50, edgeCache: 2 }); const warehouses = await api.vmi.warehouses.list({ customerId: 12345, edgeCache: 4 }); // Transactional data - short caching (1 hour) const cart = await api.commerce.cartHeaders.list({ userId: 123, edgeCache: 1 }); const pricing = await api.pricing.getPrice({ customerId, itemId, quantity, edgeCache: 1 }); // Real-time operations - never cached const auth = await api.joomla.users.verifyPassword({ username, password }); const checkout = await api.commerce.checkout.get(checkoutUid); ``` ## Pattern Recognition & Workflows ### Business Process Discovery ```typescript // The platform understands business processes const customerJourney = await api.findEndpoint('customer lifecycle management'); // Suggests: user creation → customer profile → order history → payment setup const inventoryWorkflow = await api.findEndpoint('inventory optimization'); // Suggests: availability check → replenishment calculation → distributor ordering const contentWorkflow = await api.findEndpoint('AI content generation'); // Suggests: content analysis → AI enhancement → search optimization ``` ### Advanced Search Intelligence ```typescript // Multi-criteria business search const results = await api.findEndpoint('customer service operations', { domain: 'customer-management', // Business domain filter readOnly: true, // Only query operations minScore: 0.3, // High relevance threshold maxResults: 5 // Focused results }); // Each result includes business context results.forEach(result => { console.log(`Operation: ${result.endpoint.fullPath}`); console.log(`Business value: ${result.endpoint.description}`); console.log(`Workflow stage: ${result.endpoint.domain}`); console.log(`Related ops: ${result.endpoint.relatedEndpoints.join(', ')}`); }); ``` ## Next Steps: Explore the Platform - **[Complete Platform Guide](./README.md)** - Discover all advanced capabilities - **[AI Discovery System](./API-DISCOVERY.md)** - Master natural language API navigation - **[Integration Patterns](./README.md#platform-integration)** - React, Next.js, Node.js examples - **[Performance Optimization](./README.md#performance--caching)** - Advanced caching strategies ## You're Now Ready for Production You've experienced the magic: - āœ… Context-aware client creation eliminates boilerplate - āœ… Natural language discovery replaces documentation hunting - āœ… Business-aware caching optimizes performance automatically - āœ… Cross-service intelligence reveals complete workflows - āœ… Dual access patterns maximize developer productivity The platform transforms enterprise API complexity into elegant business logic. Start building! ## Error Handling Wrap your API calls in try/catch: ```typescript try { const users = await api.joomla.users.list(); console.log('Got users:', users.data.length); } catch (error) { if (error.message.includes('401')) { console.error('Authentication failed - check your token'); } else if (error.message.includes('404')) { console.error('Endpoint not found - check your URL'); } else { console.error('Something else went wrong:', error.message); } } ``` ## Troubleshooting **"Authentication failed"** - Check your `bearerToken` is correct and not expired - Verify your `siteId` matches your environment **"Cannot find endpoint"** - Try a health check first: `api.joomla.getHealthCheck()` - Verify you're using the right service name **"Network error"** - Check your internet connection - Verify the API endpoints are accessible from your network **"Validation error"** - Check the parameter names and types match the examples - Look at the error message for specific field issues ## Next Steps 1. **Read the main [README](./README.md)** for comprehensive documentation 2. **Explore the [API Discovery Guide](./API-DISCOVERY.md)** to find functionality 3. **Check the Integration Guides** in the README for React, Node.js, etc. 4. **Look at Error Handling** section for production-ready error management ## Need Help? - Check the comprehensive [README](./README.md) for detailed examples - Use `api.discover()` to explore available functionality - Look at the error messages - they usually tell you what's wrong - Ask your team lead or system administrator for credentials You're ready to build! Start with simple calls like listing users or checking health, then gradually explore more functionality as you need it.