@mindmakr/gs-websdk
Version:
Web SDK for Guru SaaS System - Complete JavaScript/TypeScript SDK for building applications with dynamic schema management
508 lines (416 loc) โข 12.7 kB
Markdown
# ๐จโ๐ป Developer Guide
Complete guide for developers using the Guru SaaS Web SDK.
## ๐ Table of Contents
- [Installation & Setup](#installation--setup)
- [Configuration](#configuration)
- [Authentication](#authentication)
- [Core Services](#core-services)
- [Error Handling](#error-handling)
- [TypeScript Support](#typescript-support)
- [Testing](#testing)
- [Best Practices](#best-practices)
- [Troubleshooting](#troubleshooting)
## ๐ Installation & Setup
### Prerequisites
- Node.js 16+ or modern browser
- TypeScript 4.5+ (recommended)
### Installation
```bash
npm install @mindmakr/gs-websdk
```
### Basic Setup
```typescript
import { GuruSaaS } from '@mindmakr/gs-websdk';
const client = new GuruSaaS({
baseUrl: 'https://your-api-domain.com',
debug: true // Enable debug mode for development
});
```
## โ๏ธ Configuration
The SDK supports two configuration approaches depending on your deployment:
### Option 1: Single Base URL (Production with Reverse Proxy)
**Use when:** All services are behind a reverse proxy, load balancer, or API gateway.
```typescript
const client = new GuruSaaS({
baseUrl: 'https://api.example.com',
timeout: 30000,
debug: false
});
```
**Benefits:**
- Simplified configuration
- Single SSL certificate
- Centralized routing
- Better for production deployments
### Option 2: Multi-Service URLs (Development/Direct Access)
**Use when:** Accessing services directly (development) or services are on different domains/ports.
```typescript
const client = new GuruSaaS({
// Individual service URLs (matches your backend configuration)
authUrl: 'http://localhost:4000', // Auth Service
globalDataUrl: 'http://localhost:5010', // Global Data Service
aiServiceUrl: 'http://localhost:4001', // AI Service
notificationUrl: 'http://localhost:5020', // Notification Service
// Request settings
timeout: 30000,
debug: true
});
```
**Benefits:**
- Direct service access
- Perfect for development
- Service-specific configuration
- Matches your backend architecture
**Note:** Your backend services run on these exact ports, so this configuration is required for development.
### Advanced Configuration
```typescript
const config = {
// Production: Single base URL with reverse proxy
baseUrl: 'https://api.example.com',
// OR Development: Individual service URLs
authUrl: 'http://localhost:4000',
globalDataUrl: 'http://localhost:5010',
aiServiceUrl: 'http://localhost:4001',
notificationUrl: 'http://localhost:5020',
// Request settings
timeout: 30000,
retries: 3,
// Development
debug: process.env.NODE_ENV === 'development'
};
const client = new GuruSaaS(config);
```
### Environment-Specific Configuration
```typescript
// Development (Direct service access)
const devClient = new GuruSaaS({
authUrl: 'http://localhost:4000',
globalDataUrl: 'http://localhost:5010',
aiServiceUrl: 'http://localhost:4001',
notificationUrl: 'http://localhost:5020',
debug: true,
timeout: 60000
});
// Production (Reverse proxy)
const prodClient = new GuruSaaS({
baseUrl: process.env.REACT_APP_API_URL,
debug: false,
timeout: 15000,
retryAttempts: 3
});
```
## ๐ Authentication
### Login
```typescript
try {
const { user, tokens } = await client.login('user@example.com', 'password');
console.log(`Welcome ${user.name}!`);
// Tokens are automatically stored and managed
console.log('Access token:', tokens.access_token);
} catch (error) {
console.error('Login failed:', error.message);
}
```
### Token Management
```typescript
// Check if user is authenticated
if (client.isAuthenticated()) {
console.log('User is logged in');
}
// Get current user info
const userInfo = await client.getUserInfo();
// Logout
await client.logout();
```
### Automatic Token Refresh
The SDK automatically handles token refresh. You can also manually refresh:
```typescript
try {
await client.refreshToken();
} catch (error) {
// Redirect to login if refresh fails
window.location.href = '/login';
}
```
## ๐๏ธ Core Services
### Authentication Service
```typescript
// User management
const users = await client.auth.getUsers({ page: 1, limit: 10 });
const newUser = await client.auth.createUser({
email: 'new@example.com',
password: 'secure123',
name: 'New User'
});
// Role management
const roles = await client.auth.getRoles();
await client.auth.addRoleToUser(newUser.id, roleId);
// Permission checking
const canCreate = await client.auth.checkPermission('users', 'create');
```
### Schema Service
```typescript
// Template management
const templates = await client.schema.getSchemaTemplates({
is_active: true,
category: 'customer_management'
});
const template = await client.schema.createSchemaTemplate({
name: 'Customer Profile',
code: 'customer_profile',
category: 'customer_management',
schema_definition: {
type: 'object',
properties: {
firstName: { type: 'string', title: 'First Name' },
email: { type: 'string', format: 'email', title: 'Email' }
},
required: ['firstName', 'email']
}
});
// Instance management
const instance = await client.schema.createSchemaInstance({
template_id: template.id,
data: {
firstName: 'John',
email: 'john@example.com'
}
});
```
### AI Service
```typescript
// Field suggestions
const suggestions = await client.ai.getFieldNameSuggestions({
context: 'customer management',
existing_fields: ['firstName', 'lastName']
});
// Schema generation
const schema = await client.ai.generateSchema({
description: 'Customer contact information form',
business_domain: 'e-commerce'
});
// Field enhancement
const enhancement = await client.ai.enhanceField({
fieldName: 'email',
fieldType: 'email',
businessContext: 'customer registration',
enhancementType: 'validation'
});
```
### Notification Service
```typescript
// Send email (only implemented functionality)
const result = await client.notification.sendEmail({
to: 'user@example.com',
subject: 'Welcome!',
html: '<h1>Welcome to our platform!</h1>',
text: 'Welcome! Thank you for joining our platform.' // Optional plain text
});
console.log(result.message); // "Email sent successfully"
```
**โ ๏ธ Note**: Only basic email sending is implemented. Template management, bulk sending, analytics, and other advanced features are not available in the current backend.
## ๐ง Error Handling
### Error Types
```typescript
import {
SDKError,
AuthenticationError,
NetworkError,
ValidationError
} from '@mindmakr/gs-websdk';
try {
await client.auth.getUsers();
} catch (error) {
if (error instanceof AuthenticationError) {
// Handle authentication errors
console.log('Authentication failed:', error.message);
// Redirect to login
} else if (error instanceof NetworkError) {
// Handle network errors
console.log('Network error:', error.message);
// Show retry option
} else if (error instanceof ValidationError) {
// Handle validation errors
console.log('Validation error:', error.message);
console.log('Field errors:', error.fieldErrors);
} else if (error instanceof SDKError) {
// Handle other SDK errors
console.log('SDK error:', error.message);
}
}
```
### Global Error Handling
```typescript
// Set up global error handler
client.on('error', (error) => {
console.error('SDK Error:', error);
if (error instanceof AuthenticationError) {
// Redirect to login
window.location.href = '/login';
}
});
```
## ๐ท TypeScript Support
### Type Definitions
The SDK provides comprehensive TypeScript definitions:
```typescript
import {
GuruSaaS,
User,
SchemaTemplate,
SchemaInstance,
EmailTemplate,
PaginatedResponse
} from '@mindmakr/gs-websdk';
// Typed responses
const users: PaginatedResponse<User> = await client.auth.getUsers();
const template: SchemaTemplate = await client.schema.getSchemaTemplate(id);
```
### Custom Types
```typescript
interface CustomUserData {
firstName: string;
lastName: string;
email: string;
}
// Type-safe instance creation
const instance = await client.schema.createSchemaInstance<CustomUserData>({
template_id: templateId,
data: {
firstName: 'John',
lastName: 'Doe',
email: 'john@example.com'
}
});
```
## ๐งช Testing
### Unit Testing
```typescript
import { GuruSaaS } from '@mindmakr/gs-websdk';
describe('SDK Tests', () => {
let client: GuruSaaS;
beforeEach(() => {
client = new GuruSaaS({
baseUrl: 'http://localhost:4000',
debug: true
});
});
test('should authenticate user', async () => {
const result = await client.login('test@example.com', 'password');
expect(result.user).toBeDefined();
expect(result.tokens).toBeDefined();
});
});
```
### Integration Testing
```bash
# Run integration tests (requires backend services)
npm run test:integration
# Run specific service tests
npm run test:integration:auth
npm run test:integration:schema
npm run test:integration:ai
npm run test:integration:notification
```
## ๐ก Best Practices
### 1. Error Handling
Always wrap SDK calls in try-catch blocks:
```typescript
try {
const result = await client.auth.getUsers();
// Handle success
} catch (error) {
// Handle error appropriately
}
```
### 2. Authentication State
Check authentication state before making API calls:
```typescript
if (!client.isAuthenticated()) {
// Redirect to login or show login form
return;
}
const users = await client.auth.getUsers();
```
### 3. Configuration Management
Use environment variables for configuration:
```typescript
// Production configuration
const client = new GuruSaaS({
baseUrl: process.env.REACT_APP_API_URL,
debug: process.env.NODE_ENV === 'development'
});
// Development configuration
const devClient = new GuruSaaS({
authUrl: process.env.REACT_APP_AUTH_URL || 'http://localhost:4000',
globalDataUrl: process.env.REACT_APP_GLOBAL_DATA_URL || 'http://localhost:5010',
aiServiceUrl: process.env.REACT_APP_AI_SERVICE_URL || 'http://localhost:4001',
notificationUrl: process.env.REACT_APP_NOTIFICATION_URL || 'http://localhost:5020',
debug: process.env.NODE_ENV === 'development'
});
```
#### Environment Variables Setup
Create a `.env` file in your project:
```bash
# Production (with reverse proxy)
REACT_APP_API_URL=https://api.yourdomain.com
# OR Development (direct service access)
REACT_APP_AUTH_URL=http://localhost:4000
REACT_APP_GLOBAL_DATA_URL=http://localhost:5010
REACT_APP_AI_SERVICE_URL=http://localhost:4001
REACT_APP_NOTIFICATION_URL=http://localhost:5020
```
### 4. Resource Cleanup
Clean up resources when component unmounts:
```typescript
useEffect(() => {
return () => {
client.removeAllListeners();
};
}, []);
```
## ๐ง Troubleshooting
### Common Issues
#### 1. Authentication Errors
```typescript
// Check if credentials are correct
// Verify backend services are running
// Check network connectivity
```
#### 2. Network Timeouts
```typescript
// Increase timeout for slow networks
const client = new GuruSaaS({
baseUrl: 'https://api.example.com',
timeout: 60000 // 60 seconds
});
```
#### 3. CORS Issues
```typescript
// Ensure backend CORS is configured correctly
// Check if baseUrl is correct
// Verify SSL certificates in production
```
### Debug Mode
Enable debug mode for detailed logging:
```typescript
const client = new GuruSaaS({
baseUrl: 'https://api.example.com',
debug: true
});
```
### Health Checks
```typescript
// Check service health
const authHealth = await client.auth.getHealth();
const schemaHealth = await client.schema.getHealth();
const aiHealth = await client.ai.getHealthStatus();
const notificationHealth = await client.notification.getHealth();
```
## ๐ Next Steps
- Check out [API Reference](./API_REFERENCE.md) for detailed API documentation
- See [Examples](./EXAMPLES.md) for real-world usage patterns
- Review [DevOps Guide](./DEVOPS_GUIDE.md) for deployment information
## ๐ Support
- [GitHub Issues](https://github.com/mindmakr/guru-saas/issues) - Bug reports and feature requests
- [GitHub Discussions](https://github.com/mindmakr/guru-saas/discussions) - Questions and community support