@titamedia/delectable-sdk
v1.2.2
Published
SDK oficial para los servicios del chatbot Delectable
Downloads
7
Maintainers
Readme
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.
📋 Table of Contents
- 🚀 Installation
- 📖 Basic Usage
- 🔧 Configuration
- 🔐 Authentication
- 🍽️ Meal Plans
- 🍲 Recipes (New in v1.1.0)
- 👤 User Management
- 🛠️ Advanced Usage
- 🌐 Multi-Environment Usage
- 📚 API Reference
- 🔄 Changelog
🚀 Installation
npm install @titamedia/delectable-sdk📖 Basic Usage
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: '[email protected]',
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
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
# 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
const authResult = await sdk.auth.loginAnonymous();
console.log('Token:', authResult.access_token);Credential Login
try {
const authResult = await sdk.login('username', 'password');
console.log('Authenticated user:', authResult);
} catch (error) {
console.error('Login error:', error.message);
}Set Token Manually
sdk.setAccessToken('your-access-token');🍽️ Meal Plans
Get Meal Plans
const mealPlans = await sdk.mealPlans.fetchMealPlans({
username: '[email protected]',
skip: 0,
limit: 10
});
console.log('Plans found:', mealPlans.data.items);Create Meal Plan
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: '[email protected]'
});Generate Plan Automatically
const generatedPlan = await sdk.mealPlans.generateMealPlan({
name: 'Vegetarian Plan',
dietType: 'vegetarian',
servings: 4,
mealTypes: ['breakfast', 'lunch', 'dinner'],
username: '[email protected]'
});Delete Meal Plan
await sdk.mealPlans.deleteMealPlan('meal-plan-id');🍲 Recipes
Get User Recipes
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
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
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
// 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
// Static function to extract recipe with highest similarity_score
const bestRecipe = sdk.recipes.constructor.extractBestRecipe(mealRecipeResponse);👤 User Management
Get User Profile
const userProfile = await sdk.users.getUserProfile('[email protected]');
if (userProfile) {
console.log('Profile:', userProfile.UserObj);
}Update Profile
await sdk.users.updateUserProfile({
id: '[email protected]',
name: 'New Name',
homeRegionCity: 'Madrid',
primaryLanguage: 'es'
});Create Basic User
const result = await sdk.users.createBasicUser('[email protected]');
console.log('User created:', result.success);VTEX Integration
// Get VTEX profile
const vtexProfile = await sdk.users.getVtexProfile('[email protected]');
// Create user from VTEX
if (vtexProfile.success) {
const userResult = await sdk.users.createUserFromVtex(vtexProfile.vtex_profile);
}🛠️ Advanced Usage
Error Handling
import {
DelectableSDK,
AuthenticationError,
ValidationError,
NetworkError
} from '@titamedia/delectable-sdk';
try {
await sdk.mealPlans.fetchMealPlans({ username: '[email protected]' });
} 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
// 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
const status = sdk.getStatus();
console.log('SDK Status:', {
isAuthenticated: status.isAuthenticated,
currentUser: status.currentUser,
baseURL: status.baseURL
});Individual Module Usage
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
// CommonJS
const { DelectableSDK } = require('@titamedia/delectable-sdk');
// ES Modules
import { DelectableSDK } from '@titamedia/delectable-sdk';Browser
<!-- 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
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: '[email protected]'
});
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 SDKlogin(username, password)- Login with credentialslogout()- Close sessionsetAccessToken(token)- Set tokensetUser(user)- Set current usersetDebug(enabled)- Configure debuggetStatus()- Get SDK status
Properties
auth- Authentication modulemealPlans- Meal plans moduleusers- Users modulerecipes- Recipes module (new in v1.1.0)isAuthenticated- Authentication statuscurrentUser- Current useraccessToken- Access token
🤝 Contributing
- Fork the repository
- Create a feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
📄 License
This project is licensed under the MIT License. See the LICENSE file for details.
🆘 Support
- 📧 Email: [email protected]
- 🐛 Issues: GitHub Issues
- 📖 Documentation: Docs
🔄 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
