@sadesoftware/services-sdk
v1.0.0
Published
Official TypeScript SDK for Sade Services Platform - Email, WhatsApp, Drive, and more
Downloads
2
Maintainers
Readme
@sadesoftware/services-sdk
Official TypeScript SDK for Sade Services Platform - Email, WhatsApp, Drive, and more.
🚀 Features
- ✅ TypeScript First - Full type safety with TypeScript
- ✅ Tree-Shakeable - Import only what you need
- ✅ Retry Logic - Automatic retry with exponential backoff
- ✅ Circuit Breaker - Fail-fast when service is down
- ✅ Telemetry - Built-in logging and monitoring
- ✅ Zero Dependencies - Only
zodfor validation - ✅ ESM + CJS - Works in all environments
- ✅ Promise-Based - Modern async/await API
📦 Installation
npm install @sadesoftware/services-sdk🔑 Quick Start
Minimal Setup (Recommended)
1. Install the package:
npm install @sadesoftware/services-sdk2. Create .env file:
SADE_API_KEY=sk_live_your_api_key_here
# Domain:
# - If API key has domain restriction (domain: "myapp.com") → use that domain
# - If API key allows all domains (domain: "*") → use any value (e.g., "*" or "myapp.com")
SADE_DOMAIN=myapp.com
# Optional: Custom API URL (defaults to https://api.sade.works)
# SADE_API_URL=http://localhost:80003. Create SDK instance (once):
// lib/sdk.ts or services/sade.ts
import { ServicesSDK } from '@sadesoftware/services-sdk';
export const sdk = new ServicesSDK({
apiKey: process.env.SADE_API_KEY!,
domain: process.env.SADE_DOMAIN || '*', // Any value if API key allows all domains
// baseURL is optional - uses https://api.sade.works by default
baseURL: process.env.SADE_API_URL,
});4. Use anywhere in your app:
import { sdk } from './lib/sdk';
// Send OTP via Email
async function sendOTP(email: string) {
const code = Math.floor(100000 + Math.random() * 900000).toString();
await sdk.email.send({
to: [email],
subject: 'Your Login Code',
content: `Your verification code is: ${code}`,
});
return code;
}
// Send WhatsApp notification
async function notifyUser(phone: string, message: string) {
await sdk.whatsApp.sendText({
number: phone, // ⚠️ Without + symbol! (e.g., 905551234567)
text: message,
});
}Basic Example
import { ServicesSDK } from '@sadesoftware/services-sdk';
const sdk = new ServicesSDK({
apiKey: 'sk_live_xxxxxxxxxxxx',
domain: 'example.com'
});
// Send email
await sdk.email.send({
to: ['[email protected]'],
subject: 'Hello!',
content: '<h1>Welcome</h1>'
});
// Send WhatsApp
await sdk.whatsApp.sendText({
number: '905551234567', // ⚠️ Without + symbol!
text: 'Hello from SDK!'
});
// Upload to Drive
await sdk.drive.upload(file, {
targetPath: '/invoices'
});📚 Services
Email Service
const result = await sdk.email.send({
to: ['[email protected]', '[email protected]'],
subject: 'Order Confirmation',
content: '<h1>Your order #1234</h1>',
content_type: 'html',
sender_name: 'My Store'
});
console.log(`Used ${result.credits_used} credits`);WhatsApp Service
// Text message
await sdk.whatsApp.sendText({
number: '905551234567', // ⚠️ Without + symbol!
text: 'Hello World!'
});
// Media message
await sdk.whatsApp.sendMedia({
number: '905551234567', // ⚠️ Without + symbol!
media_type: 'image',
mimetype: 'image/jpeg',
media: 'https://example.com/photo.jpg',
caption: 'Check this out!'
});
// Button message
await sdk.whatsApp.sendButtons({
number: '905551234567', // ⚠️ Without + symbol!
title: 'Select Option',
description: 'Choose one:',
buttons: [
{ type: 'reply', displayText: 'Yes', id: 'yes' },
{ type: 'reply', displayText: 'No', id: 'no' }
]
});Drive Service
// Upload file
const result = await sdk.drive.upload(file, {
filename: 'invoice.pdf',
targetPath: '/invoices/2024',
customerSlug: 'acme-corp',
onDuplicate: 'autoRename' // or 'replace', 'skip'
});
// List files
const files = await sdk.drive.listFiles({
page: 1,
limit: 20
});
// Get preview URL
const previewURL = sdk.drive.getPreviewURL(fileId, true); // thumbnailAccount Service
// Get balance
const balance = await sdk.account.getBalance();
console.log(`Credits: ${balance.data.credit_balance}`);
// Get usage stats
const usage = await sdk.account.getUsage();
console.log(`Total calls: ${usage.data.total_usage}`);⚙️ Advanced Configuration
const sdk = new ServicesSDK({
apiKey: 'sk_live_xxx',
domain: 'example.com',
// Global timeout
timeout: 30000,
// Retry configuration
retry: {
maxRetries: 3,
backoff: 'exponential', // 'linear', 'fixed'
initialDelay: 1000,
maxDelay: 30000
},
// Circuit breaker
circuitBreaker: {
threshold: 5,
timeout: 60000,
windowSize: 10000
},
// Telemetry
telemetry: {
enabled: true,
logLevel: 'info', // 'debug', 'info', 'warn', 'error'
logger: customLogger // optional custom logger
},
// Service-specific configs
services: {
email: {
timeout: 60000,
configId: 'custom-config-id'
},
whatsapp: {
timeout: 45000
},
drive: {
timeout: 120000
}
}
});🔧 Per-Call Overrides
// Override timeout for specific call
await sdk.email.send(
{ to: ['[email protected]'], subject: 'Test' },
{ timeout: 90000 }
);
// Use specific config
await sdk.whatsApp.sendText(
{ number: '905551234567', text: 'Hi' }, // ⚠️ Without + symbol!
{ configId: 'custom-config', instanceName: 'production' }
);🚨 Error Handling
import {
InsufficientCreditsError,
RateLimitError,
ConfigNotFoundError,
AuthenticationError
} from '@sadesoftware/services-sdk';
try {
await sdk.email.send({ ... });
} catch (error) {
if (error instanceof InsufficientCreditsError) {
console.log(`Need ${error.creditsRequired} credits`);
console.log(`Have ${error.creditsRemaining} credits`);
// Redirect to billing
} else if (error instanceof RateLimitError) {
console.log(`Retry after ${error.retryAfter} seconds`);
// Wait and retry
} else if (error instanceof AuthenticationError) {
console.log('Invalid API key');
// Check credentials
} else if (error instanceof ConfigNotFoundError) {
console.log('Service not configured');
// Contact support
}
}🌲 Tree-Shakeable Imports
// Import only what you need
import { EmailClient } from '@sadesoftware/services-sdk/email';
import { WhatsAppClient } from '@sadesoftware/services-sdk/whatsapp';🧪 Testing
The SDK includes built-in testing utilities:
// Health check
const isHealthy = await sdk.healthCheck();📖 API Documentation
For complete API documentation, visit: https://docs.sade.works
🔗 Links
📄 License
MIT © Sade Platform
🤝 Support
- Email: [email protected]
- Issues: https://github.com/sadeuckun/services-system/issues
