@e-techsolutions/e-baas-sdk
Version:
Official E-BaaS TypeScript SDK - Backend as a Service client library
348 lines (272 loc) • 8.57 kB
Markdown
# E-BaaS SDK
The official TypeScript SDK for E-BaaS (Enterprise Backend as a Service) - A comprehensive backend-as-a-service platform similar to Supabase.
## Installation
```bash
npm install @e-techsolutions/e-baas-sdk
# or
yarn add @e-techsolutions/e-baas-sdk
```
## Quick Start
```typescript
import { createClient } from '@e-techsolutions/e-baas-sdk';
const ebaas = createClient('https://your-project.e-baas.apiservices.app.br', 'your-anon-key');
```
## Features
- **Authentication** - Email/password and OAuth providers (Google, GitHub, Facebook)
- **Database** - PostgreSQL with real-time subscriptions and RPC support
- **Storage** - File uploads with CDN integration and image transformations
- **Realtime** - WebSocket subscriptions for live data updates
- **Edge Functions** - Serverless functions with dual runtime (Node.js VM + Deno) and native SDK integration
- **TypeScript** - Full type safety and IntelliSense support
## Usage Examples
### Authentication
```typescript
// Sign up with email/password
const { user, session, error } = await ebaas.auth.signUp({
email: 'user@example.com',
password: 'secure-password',
name: 'John Doe'
});
// Sign in
const { user, session, error } = await ebaas.auth.signIn({
email: 'user@example.com',
password: 'secure-password'
});
// Get current user
const user = await ebaas.auth.getUser();
// Sign out
await ebaas.auth.signOut();
```
### Database Operations
```typescript
// Select data
const { data, error } = await ebaas
.from('users')
.select('id, name, email')
.eq('status', 'active')
.order('created_at', { ascending: false })
.limit(10)
.execute();
// Insert data
const { data, error } = await ebaas
.from('users')
.insert([
{ name: 'John Doe', email: 'john@example.com' },
{ name: 'Jane Smith', email: 'jane@example.com' }
]);
// Update data
const { data, error } = await ebaas
.from('users')
.update({ status: 'inactive' })
.eq('id', 123);
// Delete data
const { data, error } = await ebaas
.from('users')
.delete()
.eq('status', 'inactive');
// RPC (stored procedures)
const { data, error } = await ebaas.rpc('get_user_stats', {
user_id: 123
});
```
### Storage
```typescript
// Upload file
const { data, error } = await ebaas.storage
.from('avatars')
.upload('user-123.jpg', file, {
cacheControl: '3600',
upsert: true
});
// Download file
const { data, error } = await ebaas.storage
.from('avatars')
.download('user-123.jpg');
// Get public URL
const { data } = ebaas.storage
.from('avatars')
.getPublicUrl('user-123.jpg');
// Get signed URL (for private files)
const { data, error } = await ebaas.storage
.from('private-docs')
.createSignedUrl('document.pdf', 60); // 60 seconds
// List files
const { data, error } = await ebaas.storage
.from('avatars')
.list('', {
limit: 100,
offset: 0,
sortBy: { column: 'name', order: 'asc' }
});
```
### Realtime Subscriptions
```typescript
// Subscribe to database changes
const channel = ebaas.channel('realtime:users');
channel.onPostgresChanges({
event: '*', // INSERT, UPDATE, DELETE, or *
schema: 'public',
table: 'users'
}, (payload) => {
console.log('Change received!', payload);
});
channel.subscribe();
// Broadcast messages
channel.send({
type: 'broadcast',
event: 'message',
payload: { text: 'Hello World!' }
});
// Presence tracking
channel.track({ user_id: 123, status: 'online' });
// Unsubscribe
channel.unsubscribe();
```
### Edge Functions
#### Client-side Function Invocation
```typescript
// Invoke function from client
const { data, error } = await ebaas.functions.invoke('hello-world', {
body: { name: 'John' },
headers: { 'Content-Type': 'application/json' }
});
// List functions
const { data, error } = await ebaas.functions.list();
// Get function details
const { data, error } = await ebaas.functions.get('hello-world');
```
#### Native SDK Integration in Edge Functions
**NEW in v1.0.1+**: The SDK is now natively available within Edge Functions:
```typescript
// Edge Function example with native SDK access
const { method, url } = req;
if (method === 'POST') {
const body = await req.json();
// Native database access - no imports needed!
const users = await from('users').select('*').limit(10);
// Native storage access
const bucket = bucket('uploads');
await bucket.upload('file.jpg', body.fileData);
// Native realtime notifications
await channel('notifications').send('user_created', {
user: body.userData
});
// Call other edge functions
const result = await invoke('send-email', {
body: { email: body.email }
});
return createResponse({ success: true, users, result });
}
```
#### Available Globals in Edge Functions
- `from(table)` - Database table access
- `rpc(function, args)` - RPC calls
- `bucket(name)` - Storage bucket access
- `channel(name)` - Realtime channel access
- `invoke(functionName, options)` - Function orchestration
- `ebaas.*` - Full SDK object access
- `env.*` - Environment variables
- `context.*` - Function execution context
## Advanced Configuration
```typescript
const ebaas = createClient('https://your-project.e-baas.io', 'your-anon-key', {
auth: {
autoRefreshToken: true,
persistSession: true,
detectSessionInUrl: true
},
realtime: {
params: {
eventsPerSecond: 10
}
},
global: {
headers: {
'x-custom-header': 'custom-value'
}
}
});
```
## Error Handling
```typescript
import { EBaaSError } from '@e-techsolutions/e-baas-sdk';
try {
const { data } = await ebaas.from('users').select('*').execute();
} catch (error) {
if (error instanceof EBaaSError) {
console.error('E-BaaS Error:', error.message);
console.error('Status:', error.status);
console.error('Details:', error.details);
}
}
```
## TypeScript Support
The SDK is built with TypeScript and provides full type safety:
```typescript
interface User {
id: number;
name: string;
email: string;
created_at: string;
}
const { data, error } = await ebaas
.from<User>('users')
.select('*')
.execute();
// data is now typed as User[] | null
```
## Edge Functions Runtime Support
**NEW in v1.0.1+**: Enhanced Edge Functions with dual runtime support:
### Runtime Options
- **Node.js VM** (Default) - Docker/K3s friendly, isolated-vm execution
- **Deno** (Optional) - TypeScript-first runtime with Web APIs
### Features
- **Native SDK Integration** - Full platform access within functions
- **Auto-detected Runtime** - Automatically chooses Node.js in Docker environments
- **Secure Execution** - Isolated VM with memory and timeout limits
- **Function Orchestration** - Functions can call other functions
- **Supabase-compatible API** - Same developer experience as Supabase Edge Functions
### Example Edge Function
```typescript
// my-function.ts
const { method, url } = req;
// CORS handling
if (method === 'OPTIONS') {
return corsResponse(createResponse(null, { status: 200 }));
}
try {
// Database operations
const users = await from('users').select('name, email').limit(5);
// Storage operations
const files = await bucket('uploads').list('public/');
// Realtime notifications
await channel('notifications').send('function_executed', {
timestamp: new Date().toISOString(),
userCount: users.data?.length || 0
});
// Function orchestration
const emailResult = await invoke('send-notification', {
body: { message: 'Function executed successfully' }
});
return createResponse({
success: true,
users: users.data,
files: files.data,
emailSent: emailResult.data
});
} catch (error) {
console.error('Function error:', error);
return createResponse({ error: error.message }, { status: 500 });
}
```
## Changelog
### v1.0.1 (2024-06-24)
- 🚀 **NEW**: Native SDK integration in Edge Functions
- 🚀 **NEW**: Dual runtime support (Node.js VM + Deno)
- 🚀 **NEW**: Auto-runtime detection for Docker environments
- 🚀 **NEW**: Global SDK methods in Edge Functions
- 🚀 **NEW**: Function orchestration capabilities
- 🔧 Enhanced security with isolated VM execution
- 🔧 Improved Docker/K3s compatibility
## License
MIT