UNPKG

@titamedia/delectable-sdk

Version:

SDK oficial para los servicios del chatbot Delectable

513 lines (403 loc) โ€ข 12.7 kB
# Delectable SDK Official SDK for integrating Delectable chatbot services into your applications. Includes complete modules for authentication, meal plans, user management, and **recipes** (new in v1.1.0). Reverted to original service URL in v1.2.1. [![npm version](https://badge.fury.io/js/@titamedia%2Fdelectable-sdk.svg)](https://badge.fury.io/js/@titamedia%2Fdelectable-sdk) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) ## ๐Ÿ“‹ Table of Contents - [๐Ÿš€ Installation](#-installation) - [๐Ÿ“– Basic Usage](#-basic-usage) - [๐Ÿ”ง Configuration](#-configuration) - [๐Ÿ” Authentication](#-authentication) - [๐Ÿฝ๏ธ Meal Plans](#๏ธ-meal-plans) - [๐Ÿฒ Recipes](#-recipes) **(New in v1.1.0)** - [๐Ÿ‘ค User Management](#-user-management) - [๐Ÿ› ๏ธ Advanced Usage](#๏ธ-advanced-usage) - [๐ŸŒ Multi-Environment Usage](#-multi-environment-usage) - [๐Ÿ“š API Reference](#-api-reference) - [๐Ÿ”„ Changelog](#-changelog) ## ๐Ÿš€ Installation ```bash npm install @titamedia/delectable-sdk ``` ## ๐Ÿ“– Basic Usage ```javascript import { DelectableSDK } from '@titamedia/delectable-sdk'; // Create SDK instance const sdk = new DelectableSDK({ apiKey: 'your-api-key', baseURL: 'https://api.delectable.com', // Optional debug: true // Optional }); // Initialize SDK await sdk.initialize(); // Use services const mealPlans = await sdk.mealPlans.fetchMealPlans({ username: 'user@example.com', limit: 10 }); // New in v1.1.0: Recipes module const recipes = await sdk.recipes.fetchUserRecipes(accessToken, username); console.log('Meal plans:', mealPlans); console.log('Available recipes:', recipes.length); ``` ## ๐Ÿ”ง Configuration ### Constructor Options ```javascript const sdk = new DelectableSDK({ // Basic configuration apiKey: 'your-api-key', // Required baseURL: 'https://api.delectable.com', // Optional debug: false, // Optional timeout: 30000, // Optional (ms) // VTEX configuration vtex: { appKey: 'vtex-app-key', appToken: 'vtex-app-token', domain: 'your-store.myvtex.com' }, // Cache configuration cache: { enabled: true, ttl: 300000 // 5 minutes } }); ``` ### Environment Variables ```bash # API Configuration DELECTABLE_API_KEY=your-api-key DELECTABLE_BASE_URL=https://api.delectable.com # VTEX Configuration VTEX_APP_KEY=vtex-app-key VTEX_APP_TOKEN=vtex-app-token ``` ## ๐Ÿ” Authentication ### Anonymous Login ```javascript const authResult = await sdk.auth.loginAnonymous(); console.log('Token:', authResult.access_token); ``` ### Credential Login ```javascript try { const authResult = await sdk.login('username', 'password'); console.log('Authenticated user:', authResult); } catch (error) { console.error('Login error:', error.message); } ``` ### Set Token Manually ```javascript sdk.setAccessToken('your-access-token'); ``` ## ๐Ÿฝ๏ธ Meal Plans ### Get Meal Plans ```javascript const mealPlans = await sdk.mealPlans.fetchMealPlans({ username: 'user@example.com', skip: 0, limit: 10 }); console.log('Plans found:', mealPlans.data.items); ``` ### Create Meal Plan ```javascript const newMealPlan = await sdk.mealPlans.createMealPlan({ name: 'Weekly Plan', description: 'Weekly meal plan', start_date: '2024-01-01', end_date: '2024-01-07', days: [ { date: '2024-01-01', meals: [ { type: 'breakfast', name: 'Oatmeal with fruits', ingredients: ['Oats', 'Milk', 'Fruits'] } ] } ], created_by: 'user@example.com' }); ``` ### Generate Plan Automatically ```javascript const generatedPlan = await sdk.mealPlans.generateMealPlan({ name: 'Vegetarian Plan', dietType: 'vegetarian', servings: 4, mealTypes: ['breakfast', 'lunch', 'dinner'], username: 'user@example.com' }); ``` ### Delete Meal Plan ```javascript await sdk.mealPlans.deleteMealPlan('meal-plan-id'); ``` ## ๐Ÿฒ Recipes ### Get User Recipes ```javascript const userRecipes = await sdk.recipes.fetchUserRecipes( accessToken, username, "*", // search query (optional, default: "*") 100, // number of suggestions (optional, default: 100) true // include sponsored (optional, default: true) ); console.log(`Found ${userRecipes.length} recipes`); userRecipes.forEach(recipe => { console.log(`- ${recipe.name} (ID: ${recipe.id})`); }); ``` ### Get Recipe by ID ```javascript const recipeDetails = await sdk.recipes.fetchRecipeById( accessToken, username, 'chicken-caesar-salad' ); console.log('Recipe details:', { name: recipeDetails.name, ingredients: recipeDetails.ingredientNames?.length || 0, instructions: recipeDetails.instructions?.length || 0, prepTime: recipeDetails.prepTimeMinutes, servings: recipeDetails.servings }); ``` ### Select Recipe for Meal Plan ```javascript const mealRecipeResult = await sdk.recipes.selectRecipeForMeal( accessToken, username, 'meal1-uuid-1234', // meal ID ['low-carb', 'fish-free'], // user preferences 5, // rating (optional, default: 5) true // generate if not found (optional, default: true) ); console.log('Candidates received:', { meal: mealRecipeResult.meal_name, candidates: mealRecipeResult.existing_recipes_from_database?.length || 0 }); // Extract best recipe based on similarity_score const bestRecipe = sdk.recipes.constructor.extractBestRecipe(mealRecipeResult); if (bestRecipe) { console.log(`Best option: "${bestRecipe.name}" (score: ${bestRecipe.similarity_score})`); } ``` ### Convenience Method: Complete Recipe for Meal ```javascript // Combines selectRecipeForMeal + fetchRecipeById in a single method const completeResult = await sdk.recipes.getCompleteRecipeForMeal( accessToken, username, 'meal1-uuid-1234', ['low-carb', 'budget-conscious'] ); console.log('Complete flow:', { bestCandidate: completeResult.bestCandidate.name, similarityScore: completeResult.bestCandidate.similarity_score, completeRecipe: { name: completeResult.completeRecipe.name, ingredients: completeResult.completeRecipe.ingredientNames?.length || 0, instructions: completeResult.completeRecipe.instructions?.length || 0 } }); ``` ### Helper to Extract Best Recipe ```javascript // Static function to extract recipe with highest similarity_score const bestRecipe = sdk.recipes.constructor.extractBestRecipe(mealRecipeResponse); ``` ## ๐Ÿ‘ค User Management ### Get User Profile ```javascript const userProfile = await sdk.users.getUserProfile('user@example.com'); if (userProfile) { console.log('Profile:', userProfile.UserObj); } ``` ### Update Profile ```javascript await sdk.users.updateUserProfile({ id: 'user@example.com', name: 'New Name', homeRegionCity: 'Madrid', primaryLanguage: 'es' }); ``` ### Create Basic User ```javascript const result = await sdk.users.createBasicUser('newuser@example.com'); console.log('User created:', result.success); ``` ### VTEX Integration ```javascript // Get VTEX profile const vtexProfile = await sdk.users.getVtexProfile('user@example.com'); // Create user from VTEX if (vtexProfile.success) { const userResult = await sdk.users.createUserFromVtex(vtexProfile.vtex_profile); } ``` ## ๐Ÿ› ๏ธ Advanced Usage ### Error Handling ```javascript import { DelectableSDK, AuthenticationError, ValidationError, NetworkError } from '@titamedia/delectable-sdk'; try { await sdk.mealPlans.fetchMealPlans({ username: 'user@example.com' }); } catch (error) { if (error instanceof AuthenticationError) { console.error('Authentication error:', error.message); // Redirect to login } else if (error instanceof ValidationError) { console.error('Invalid data:', error.message); } else if (error instanceof NetworkError) { console.error('Network error:', error.message); } else { console.error('Unknown error:', error.message); } } ``` ### Logging and Debug ```javascript // Enable debug logs sdk.setDebug(true); // Configure specific categories import { Logger } from '@titamedia/delectable-sdk'; Logger.enableCategory('API_CALLS'); Logger.enableCategory('USER_DATA'); // View log configuration Logger.showConfig(); ``` ### SDK Status ```javascript const status = sdk.getStatus(); console.log('SDK Status:', { isAuthenticated: status.isAuthenticated, currentUser: status.currentUser, baseURL: status.baseURL }); ``` ### Individual Module Usage ```javascript import { AuthModule, HttpClient, Config } from '@titamedia/delectable-sdk'; const config = new Config({ apiKey: 'your-key' }); const http = new HttpClient(config); const auth = new AuthModule(http, config); const result = await auth.loginAnonymous(); ``` ## ๐ŸŒ Multi-Environment Usage ### Node.js ```javascript // CommonJS const { DelectableSDK } = require('@titamedia/delectable-sdk'); // ES Modules import { DelectableSDK } from '@titamedia/delectable-sdk'; ``` ### Browser ```html <!-- UMD Build --> <script src="https://unpkg.com/@titamedia/delectable-sdk/dist/delectable-sdk.umd.js"></script> <script> const sdk = new DelectableSDK({ apiKey: 'your-api-key' }); </script> <!-- ES Modules --> <script type="module"> import { DelectableSDK } from 'https://unpkg.com/@titamedia/delectable-sdk/dist/delectable-sdk.esm.js'; const sdk = new DelectableSDK({ apiKey: 'your-api-key' }); </script> ``` ### React ```jsx import React, { useEffect, useState } from 'react'; import { DelectableSDK } from '@titamedia/delectable-sdk'; function MealPlans() { const [sdk] = useState(() => new DelectableSDK({ apiKey: process.env.REACT_APP_DELECTABLE_API_KEY })); const [mealPlans, setMealPlans] = useState([]); useEffect(() => { async function loadMealPlans() { await sdk.initialize(); const plans = await sdk.mealPlans.fetchMealPlans({ username: 'user@example.com' }); setMealPlans(plans.data.items); } loadMealPlans(); }, [sdk]); return ( <div> {mealPlans.map(plan => ( <div key={plan.id}>{plan.name}</div> ))} </div> ); } ``` ## ๐Ÿ“š API Reference ### DelectableSDK #### Constructor - `new DelectableSDK(options)` - Create SDK instance #### Methods - `initialize(options)` - Initialize SDK - `login(username, password)` - Login with credentials - `logout()` - Close session - `setAccessToken(token)` - Set token - `setUser(user)` - Set current user - `setDebug(enabled)` - Configure debug - `getStatus()` - Get SDK status #### Properties - `auth` - Authentication module - `mealPlans` - Meal plans module - `users` - Users module - `recipes` - Recipes module (new in v1.1.0) - `isAuthenticated` - Authentication status - `currentUser` - Current user - `accessToken` - Access token ## ๐Ÿค Contributing 1. Fork the repository 2. Create a feature branch (`git checkout -b feature/amazing-feature`) 3. Commit your changes (`git commit -m 'Add amazing feature'`) 4. Push to the branch (`git push origin feature/amazing-feature`) 5. Open a Pull Request ## ๐Ÿ“„ License This project is licensed under the MIT License. See the [LICENSE](LICENSE) file for details. ## ๐Ÿ†˜ Support - ๐Ÿ“ง Email: support@delectable.com - ๐Ÿ› Issues: [GitHub Issues](https://github.com/delectable/sdk/issues) - ๐Ÿ“– Documentation: [Docs](https://docs.delectable.com/sdk) ## ๐Ÿ”„ Changelog ### v1.1.1 (Latest) - ๐ŸŒ **Complete English Documentation** - Full SDK documentation translated to English - ๐Ÿ“š Enhanced international accessibility for developers worldwide - ๐Ÿ”ง Professional documentation standards for open-source SDK - ๐Ÿ“– All examples, guides, and API references now in English for global reach ### v1.1.0 - ๐Ÿฒ **NEW: RecipesModule** - Complete recipes management module - โœจ `fetchUserRecipes()` - Get all user recipes with filters - โœจ `fetchRecipeById()` - Get specific recipe by ID - โœจ `selectRecipeForMeal()` - Select recipe for meal plan with similarity scoring - โœจ `getCompleteRecipeForMeal()` - Convenience method for 2-step flow - โœจ `extractBestRecipe()` - Helper function to extract best recipe by score - ๐Ÿ”ง Complete integration with direct REST APIs - ๐Ÿ“š Complete documentation with examples for all methods - ๐Ÿงช Executable example in `examples/recipes-example.js` ### v1.0.0 - โœจ Initial SDK release - ๐Ÿ” Support for anonymous and credential authentication - ๐Ÿฝ๏ธ Complete API for meal plans - ๐Ÿ‘ค User management and VTEX profiles - ๐Ÿ› ๏ธ Configurable logging system - ๐Ÿ“ฆ Builds for ES Modules, CommonJS and UMD