@kethub/sdk
v1.0.1
Published
Official TypeScript SDK for Kethub API Gateway
Maintainers
Readme
Kethub SDK
The official TypeScript SDK for the Kethub API Gateway - your all-in-one solution for integrating email, social media, and storage functionality into your applications.
Installation
npm install @kethub/sdkQuick Start
import Kethub from '@kethub/sdk';
const client = new Kethub({
apiKey: 'ik_your_api_key_here',
// baseUrl: 'https://api.kethub.dev', // Optional: defaults to production
});
// Send an email
await client.email.send({
to: '[email protected]',
subject: 'Welcome!',
html: '<h1>Hello from Kethub!</h1>',
});
// Post a tweet
await client.twitter.postText('Hello from Kethub! 🚀');
// Upload a file
const file = new File(['Hello World'], 'hello.txt', { type: 'text/plain' });
const uploadResult = await client.storage.uploadFile(file);Configuration
const client = new Kethub({
apiKey: 'ik_your_api_key_here', // Required: Your Kethub API key
baseUrl: 'https://api.kethub.dev', // Optional: API base URL
timeout: 30000, // Optional: Request timeout in ms (default: 30000)
retries: 3, // Optional: Number of retries (default: 3)
});Email Module
Send emails with ease using various providers.
Send a single email
const result = await client.email.send({
to: '[email protected]',
from: '[email protected]', // Optional: uses default if not provided
subject: 'Hello from Kethub!',
html: '<h1>Welcome!</h1><p>Thanks for signing up.</p>',
// text: 'Welcome! Thanks for signing up.', // Optional: plain text version
// cc: ['[email protected]'], // Optional: CC recipients
// bcc: ['[email protected]'], // Optional: BCC recipients
});
console.log('Email sent:', result.messageId);Send batch emails
const emails = [
{
to: '[email protected]',
subject: 'Welcome User 1!',
html: '<h1>Hello User 1!</h1>',
},
{
to: '[email protected]',
subject: 'Welcome User 2!',
html: '<h1>Hello User 2!</h1>',
},
];
const batchResult = await client.email.sendBatch(emails);
console.log(`Sent ${batchResult.results.length} emails`);Email with attachments
await client.email.send({
to: '[email protected]',
subject: 'Document attached',
html: '<p>Please find the document attached.</p>',
attachments: [
{
filename: 'document.pdf',
content: 'base64-encoded-content-here',
contentType: 'application/pdf',
},
],
});Twitter Module
Manage your Twitter presence programmatically.
Post tweets
// Simple text tweet
const tweet = await client.twitter.postText('Hello from Kethub! 🚀');
console.log('Tweet posted:', tweet.id);
// Reply to a tweet
await client.twitter.reply('Thanks for sharing!', 'original_tweet_id');
// Quote tweet
await client.twitter.quote('This is interesting!', 'tweet_to_quote_id');Get user information
const profile = await client.twitter.getProfile('username');
console.log(`${profile.name} has ${profile.followers_count} followers`);Search tweets
const tweets = await client.twitter.searchSimple('Kethub', 10);
console.log(`Found ${tweets.length} tweets about Kethub`);Get user timeline
const recentTweets = await client.twitter.getRecentTweets('username', 5);
recentTweets.forEach(tweet => {
console.log(`${tweet.created_at}: ${tweet.text}`);
});Storage Module
Upload, manage, and serve files effortlessly.
Upload files
// From a File object (browser)
const file = new File(['Hello World'], 'hello.txt', { type: 'text/plain' });
const uploadResult = await client.storage.uploadFile(file, {
folder: 'documents',
public: true,
});
console.log('File uploaded:', uploadResult.url);
// From a Buffer (Node.js)
const buffer = Buffer.from('Hello World', 'utf8');
const result = await client.storage.uploadBuffer(
buffer,
'hello.txt',
'text/plain',
{ folder: 'documents' }
);Manage files
// Get file information
const fileInfo = await client.storage.getFile('file_id');
console.log('File size:', fileInfo.size);
// Download file
const { content, contentType, filename } = await client.storage.downloadFile('file_id');
// Delete file
await client.storage.deleteFile('file_id');List files
// List all files
const filesList = await client.storage.listFiles({
page: 1,
limit: 20,
});
// List files in a specific folder
const folderFiles = await client.storage.listFolder('documents');Health Checks
Check the status of modules and services:
// Check all modules
const healthStatus = await client.healthCheck();
console.log('Email module status:', healthStatus.email.status);
console.log('Twitter module status:', healthStatus.twitter.status);
console.log('Storage module status:', healthStatus.storage.status);
// Check individual module
const emailHealth = await client.email.health();
if (emailHealth.status === 'healthy') {
console.log('Email service is operational');
}Error Handling
The SDK provides specific error types for different scenarios:
import {
KethubError,
ValidationError,
RateLimitError,
AuthenticationError
} from '@kethub/sdk';
try {
await client.email.send(emailData);
} catch (error) {
if (error instanceof ValidationError) {
console.error('Validation failed:', error.message);
} else if (error instanceof RateLimitError) {
console.error('Rate limit exceeded, please try again later');
} else if (error instanceof AuthenticationError) {
console.error('Invalid API key');
} else if (error instanceof KethubError) {
console.error('Kethub API error:', error.message, error.statusCode);
} else {
console.error('Unexpected error:', error);
}
}TypeScript Support
The SDK is written in TypeScript and includes comprehensive type definitions:
import {
SendEmailRequest,
TweetResponse,
UploadFileResponse
} from '@kethub/sdk';
const emailData: SendEmailRequest = {
to: '[email protected]',
subject: 'Test',
html: '<p>Hello!</p>',
};
const tweet: TweetResponse = await client.twitter.postText('Hello!');
// TypeScript knows tweet has properties: id, text, created_at, etc.Configuration Updates
Update configuration at runtime:
// Update API key
client.updateApiKey('ik_new_api_key');
// Update base URL (useful for switching between environments)
client.updateBaseUrl('https://staging-api.kethub.dev');
// Get current configuration
const config = client.getConfig();
console.log('Current API key:', config.apiKey);Environment Variables
For security, store your API key in environment variables:
# .env
KETHUB_API_KEY=ik_your_api_key_hereconst client = new Kethub({
apiKey: process.env.KETHUB_API_KEY!,
});Rate Limiting
The SDK automatically handles rate limiting with exponential backoff. Different endpoints have different rate limits:
- Email sending: 50 requests/minute per endpoint
- Twitter posting: 25 requests/minute
- Storage uploads: 50 requests/minute
- General API calls: 1000 requests/minute
Support
License
MIT License. See LICENSE for details.
