mocky-vton
v1.0.0
Published
React Native SDK for Mocky Virtual Try-On API integration
Downloads
3
Maintainers
Readme
Mocky-VTON SDK
React Native SDK for Mocky Virtual Try-On API integration. This SDK provides a simple and efficient way to integrate AI-powered virtual try-on capabilities into your React Native applications.
Features
- 🚀 Easy integration with React Native applications
- 📱 iOS and Android support
- 🔄 Automatic status polling with EventEmitter pattern
- 🎯 TypeScript support with full type definitions
- 🔐 Automatic bundle ID detection
- ⚡ Production-ready with comprehensive error handling
- 📊 Debug logging capabilities
- 🧹 Memory-efficient with automatic cleanup
Installation
npm install mocky-vton
# or
yarn add mocky-vtonQuick Start
import { MockyVTON, GarmentCategory } from 'mocky-vton';
// Initialize SDK
MockyVTON.initialize('YOUR_API_KEY');
// Start virtual try-on
const tryOn = MockyVTON.startTryOn(
'https://example.com/model.jpg',
'https://example.com/garment.jpg',
GarmentCategory.TOPS
);
// Listen to events
tryOn.on('processing', () => {
console.log('Processing your try-on...');
});
tryOn.on('completed', (result) => {
console.log('Try-on completed!');
console.log('Result images:', result.images);
});
tryOn.on('failed', (failure) => {
console.error('Try-on failed:', failure.error.message);
});
tryOn.on('error', (error) => {
console.error('Error occurred:', error.message);
});API Reference
Initialization
MockyVTON.initialize(apiKey, applicationId?, debug?)
Initializes the SDK with your API credentials.
Parameters:
apiKey(string, required): Your Mocky API keyapplicationId(string, optional): Application bundle ID (auto-detected if not provided)debug(boolean, optional): Enable debug logging (default: false)
Example:
// Basic initialization
MockyVTON.initialize('your-api-key');
// With custom bundle ID
MockyVTON.initialize('your-api-key', 'com.example.app');
// With debug mode
MockyVTON.initialize('your-api-key', undefined, true);Starting Try-On
MockyVTON.startTryOn(modelImage, garmentImage, category?)
Starts a virtual try-on request and returns an EventEmitter for tracking progress.
Parameters:
modelImage(string, required): Model image URL or base64 stringgarmentImage(string, required): Garment image URL or base64 stringcategory(GarmentCategory, optional): Garment category (default: AUTO)
Returns: TryOnEmitter - EventEmitter instance for tracking progress
Example:
import { MockyVTON, GarmentCategory } from 'mocky-vton';
const tryOn = MockyVTON.startTryOn(
'https://example.com/model.jpg',
'https://example.com/dress.jpg',
GarmentCategory.ONE_PIECES
);Events
The TryOnEmitter emits the following events:
processing
Emitted when the request is being processed.
tryOn.on('processing', () => {
console.log('Processing...');
});completed
Emitted when processing completes successfully.
tryOn.on('completed', (result: TryOnResult) => {
console.log('Request ID:', result.id);
console.log('Images:', result.images);
});failed
Emitted when processing fails.
tryOn.on('failed', (failure: TryOnFailure) => {
console.log('Request ID:', failure.id);
console.log('Error:', failure.error.message);
});error
Emitted when an error occurs during the process.
tryOn.on('error', (error: Error) => {
console.error('Error:', error.message);
});Enums
GarmentCategory
enum GarmentCategory {
AUTO = 'auto', // Automatically detect category
TOPS = 'tops', // Upper body garments
BOTTOMS = 'bottoms', // Lower body garments
ONE_PIECES = 'one-pieces' // Full body garments
}EventType
enum EventType {
PROCESSING = 'processing',
COMPLETED = 'completed',
FAILED = 'failed',
ERROR = 'error'
}Cleanup
MockyVTON.cleanup()
Cleans up all active polling. Should be called when component unmounts.
import { useEffect } from 'react';
import { MockyVTON } from 'mocky-vton';
function MyComponent() {
useEffect(() => {
return () => {
MockyVTON.cleanup();
};
}, []);
// Component code...
}Complete Example
import React, { useState, useEffect } from 'react';
import { View, Image, Button, Text, ActivityIndicator } from 'react-native';
import { MockyVTON, GarmentCategory } from 'mocky-vton';
function VirtualTryOnScreen() {
const [loading, setLoading] = useState(false);
const [resultImages, setResultImages] = useState<string[]>([]);
const [error, setError] = useState<string | null>(null);
useEffect(() => {
// Initialize SDK
MockyVTON.initialize('YOUR_API_KEY', undefined, true);
// Cleanup on unmount
return () => {
MockyVTON.cleanup();
};
}, []);
const handleTryOn = () => {
setLoading(true);
setError(null);
setResultImages([]);
const tryOn = MockyVTON.startTryOn(
'https://example.com/model.jpg',
'https://example.com/garment.jpg',
GarmentCategory.TOPS
);
tryOn.on('processing', () => {
console.log('Processing...');
});
tryOn.on('completed', (result) => {
setLoading(false);
setResultImages(result.images);
console.log('Try-on completed!');
});
tryOn.on('failed', (failure) => {
setLoading(false);
setError(failure.error.message);
});
tryOn.on('error', (err) => {
setLoading(false);
setError(err.message);
});
};
return (
<View>
<Button title="Start Try-On" onPress={handleTryOn} disabled={loading} />
{loading && (
<View>
<ActivityIndicator size="large" />
<Text>Processing your try-on...</Text>
</View>
)}
{error && <Text style={{ color: 'red' }}>{error}</Text>}
{resultImages.map((imageUrl, index) => (
<Image
key={index}
source={{ uri: imageUrl }}
style={{ width: 300, height: 400 }}
/>
))}
</View>
);
}
export default VirtualTryOnScreen;Error Handling
The SDK provides specific error classes for different scenarios:
import {
InvalidApiKeyError,
RateLimitError,
TimeoutError,
NetworkError,
InvalidImageError,
NotInitializedError
} from 'mocky-vton';
tryOn.on('error', (error) => {
if (error instanceof InvalidApiKeyError) {
console.error('Invalid API key');
} else if (error instanceof RateLimitError) {
console.error('Rate limit exceeded');
} else if (error instanceof TimeoutError) {
console.error('Request timeout');
} else if (error instanceof NetworkError) {
console.error('Network error');
}
});Image Requirements
Model Image
- Format: JPEG, PNG, WebP
- Content: Single person, clear visibility, front-facing preferred
- File Size: Maximum 10MB
Garment Image
- Format: JPEG, PNG, WebP
- Content: Clear garment visibility, minimal background preferred
- File Size: Maximum 10MB
Configuration
Polling Configuration
- Interval: 5 seconds between status checks
- Timeout: 3 minutes maximum processing time
- Max Attempts: 36 attempts (3 minutes / 5 seconds)
TypeScript Support
The SDK is written in TypeScript and provides full type definitions:
import {
MockyVTON,
TryOnEmitter,
TryOnResult,
TryOnFailure,
GarmentCategory,
EventType
} from 'mocky-vton';
// All types are fully typed
const tryOn: TryOnEmitter = MockyVTON.startTryOn(
modelImage,
garmentImage,
GarmentCategory.TOPS
);Utilities
Bundle ID Detection
import { getBundleId, isValidBundleId } from 'mocky-vton';
// Get current app bundle ID
const bundleId = getBundleId();
console.log(bundleId); // "com.example.app"
// Validate bundle ID format
const isValid = isValidBundleId('com.example.app'); // trueDebug Mode
Enable debug mode to see detailed logs:
MockyVTON.initialize('YOUR_API_KEY', undefined, true);
// You'll see logs like:
// [MockyVTON] SDK initialized successfully
// [MockyVTON] POST https://tryon.mocky.ai/api/tryon/generate
// [MockyVTON] Request created: f47ac10b-58cc-4372-a567-0e02b2c3d479
// [MockyVTON] Status: processingBest Practices
- Initialize Once: Initialize the SDK once when your app starts
- Cleanup: Always call
cleanup()when component unmounts - Error Handling: Always handle all event types (processing, completed, failed, error)
- Image Validation: Validate images before sending to API
- User Feedback: Show loading states and progress to users
- Memory Management: Don't keep references to completed emitters
License
MIT
Support
For issues and questions:
- GitHub Issues: https://github.com/mocky-ai/vton-sdk/issues
- Email: [email protected]
Changelog
1.0.0
- Initial release
- Virtual try-on API integration
- EventEmitter pattern for status updates
- Automatic bundle ID detection
- TypeScript support
- Comprehensive error handling
