@warriorteam/redai-api-sdk
Version:
TypeScript SDK for RedAI Backend API
291 lines (232 loc) • 7.62 kB
Markdown
# @redai/api-sdk
TypeScript SDK for RedAI Backend API
## Installation
```bash
npm install @redai/api-sdk
# or
yarn add @redai/api-sdk
# or
pnpm add @redai/api-sdk
```
## Quick Start
```typescript
import { RedAiSdk } from '@redai/api-sdk';
// Create SDK instance
const sdk = new RedAiSdk({
baseUrl: 'https://api.example.com',
timeout: 30000, // optional, default 30s
});
// Set authentication token
sdk.setAuthToken('your-jwt-token');
// Use the SDK
const apis = await sdk.dashboardGeneric.api.findAll({ page: 1, limit: 10 });
console.log(apis.result.items);
```
## Modules
### Dashboard Generic Module
The dashboard-generic module provides services for:
- **ApiService**: Manage API configurations
- **PageTemplateService**: Manage page templates
- **ExecuteApiService**: Execute dashboard APIs and resources
- **AiPageGeneratorService**: AI-powered page generation
#### API Service
```typescript
// Get all APIs with pagination
const apis = await sdk.dashboardGeneric.api.findAll({
page: 1,
limit: 10,
method: 'GET',
status: 'active',
});
// Get API by ID
const api = await sdk.dashboardGeneric.api.findOne('uuid');
// Get API by code
const api = await sdk.dashboardGeneric.api.findByCode('getUser');
// Update API
const updated = await sdk.dashboardGeneric.api.update('uuid', {
status: 'inactive',
timeoutMs: 60000,
});
// Delete API
await sdk.dashboardGeneric.api.remove('uuid');
// Get dashboard modules
const modules = await sdk.dashboardGeneric.api.getModules();
// Get API statistics
const stats = await sdk.dashboardGeneric.api.getStatistics();
```
#### Page Template Service
```typescript
// Create page template
const template = await sdk.dashboardGeneric.pageTemplate.create({
name: 'Customer Dashboard',
code: 'export default function Page({ apis }) { return <div>Hello</div>; }',
description: 'Dashboard for customer analytics',
tags: ['customer', 'dashboard'],
apiIds: ['uuid-1', 'uuid-2'],
});
// Get all templates
const templates = await sdk.dashboardGeneric.pageTemplate.findAll({
page: 1,
limit: 10,
status: 'active',
type: 'USER',
});
// Get template by ID
const template = await sdk.dashboardGeneric.pageTemplate.findOne('uuid');
// Update template
const updated = await sdk.dashboardGeneric.pageTemplate.update('uuid', {
name: 'Updated Dashboard',
code: 'export default function Page({ apis }) { return <div>Updated</div>; }',
});
// Rename template
const renamed = await sdk.dashboardGeneric.pageTemplate.rename('uuid', 'New Name');
// Delete template
await sdk.dashboardGeneric.pageTemplate.remove('uuid');
// Associate APIs
await sdk.dashboardGeneric.pageTemplate.associateApis('uuid', ['api-uuid-1', 'api-uuid-2']);
// Create from system template
const newTemplate = await sdk.dashboardGeneric.pageTemplate.createFromTemplate(
'system-template-uuid',
{ name: 'My Custom Dashboard' }
);
// Create with template data
const template = await sdk.dashboardGeneric.pageTemplate.createWithTemplateData({
templateData: {
name: 'Customer Dashboard',
code: 'export default function Page({ apis }) { return <div>Dashboard</div>; }',
},
apiIds: ['uuid-1'],
userCustomToolIds: ['tool-uuid-1'],
});
```
#### Execute API Service
```typescript
// Execute dashboard APIs
const result = await sdk.dashboardGeneric.execute.execute({
apis: [
{
module: 'BUSINESS',
code: 'BUSINESS_REVENUE_OVERVIEW',
type: 'overview',
begin: 1704067200000,
end: 1735689600000,
},
],
});
// Execute resource with unified resourceId
const result = await sdk.dashboardGeneric.execute.executeResource({
resourceId: 'api:uuid',
parameters: {
query_param: { filter: 'recent' },
body: { name: 'Test' },
},
});
// Batch execution
const result = await sdk.dashboardGeneric.execute.executeResource({
resources: [
{ resourceId: 'pta:uuid-1', parameters: { query_param: { page: 1 } } },
{ resourceId: 'api:uuid-2', parameters: { query_param: { limit: 20 } } },
{ resourceId: 'tool:uuid-3', integrationId: 'integration-uuid', parameters: {} },
],
});
// Helper methods
await sdk.dashboardGeneric.execute.executeApi('api-uuid', { query_param: { page: 1 } });
await sdk.dashboardGeneric.execute.executePageTemplateApi('pta-uuid', { body: { name: 'Test' } });
await sdk.dashboardGeneric.execute.executeCustomTool('tool-uuid', 'integration-uuid', { body: {} });
```
#### AI Page Generator Service
```typescript
// Generate page from AI
const result = await sdk.dashboardGeneric.aiPageGenerator.generate({
apiIds: ['uuid-1', 'uuid-2'],
prompt: 'Tạo dashboard với line chart hiển thị doanh thu theo thời gian',
pattern: 'self-contained',
isSave: 'FALSE',
});
// Generate from existing template
const result = await sdk.dashboardGeneric.aiPageGenerator.generate({
pageTemplateId: 'template-uuid',
prompt: 'Thêm biểu đồ pie chart cho phân bố doanh thu',
isSave: 'FALSE',
});
// Generate and save
const result = await sdk.dashboardGeneric.aiPageGenerator.generate({
apiIds: ['uuid-1'],
prompt: 'Tạo trang quản lý khách hàng',
isSave: 'TRUE',
name: 'Quản Lý Khách Hàng',
description: 'Trang quản lý danh sách khách hàng',
});
// Generate dashboard with dynamic components
const result = await sdk.dashboardGeneric.aiPageGenerator.generateDashboard({
apiIds: ['uuid-1'],
userCustomToolIds: ['tool-uuid-1'],
prompt: 'Tạo dashboard kết hợp APIs và Custom Tools',
isSave: 'FALSE',
});
// Helper methods
await sdk.dashboardGeneric.aiPageGenerator.generateSelfContained(['api-uuid'], 'Create dashboard');
await sdk.dashboardGeneric.aiPageGenerator.generatePropsDriven(['api-uuid'], 'Create dashboard');
await sdk.dashboardGeneric.aiPageGenerator.generateAllInOne(['api-uuid'], 'Create dashboard');
```
## Types
All types are exported and can be imported directly:
```typescript
import {
// Common types
I18nLabel,
SortDirection,
QueryParams,
HttpMethod,
ApiStatus,
PageTemplateType,
DashboardModule,
DashboardChartType,
// API types
ApiConfigResponse,
CreateApiRequest,
UpdateApiRequest,
QueryApiRequest,
ApiStatisticsResponse,
// Page Template types
PageTemplateResponse,
CreatePageTemplateRequest,
UpdatePageTemplateRequest,
QueryPageTemplateRequest,
// Execute API types
ExecuteApiRequest,
ExecuteApiResponse,
ExecuteResourceRequest,
ResourceExecutionResult,
// AI Page Generator types
GeneratePageFromAiRequest,
GeneratePageFromAiResponse,
} from '@redai/api-sdk';
```
## Module Import
You can also import the dashboard-generic module directly:
```typescript
import { createDashboardGenericModule } from '@redai/api-sdk/dashboard-generic';
const dashboardModule = createDashboardGenericModule({
baseUrl: 'https://api.example.com',
});
dashboardModule.setAuthToken('your-jwt-token');
const apis = await dashboardModule.api.findAll();
```
## Error Handling
```typescript
try {
const result = await sdk.dashboardGeneric.api.findOne('invalid-uuid');
} catch (error) {
if (error.response) {
// API error response
console.error('API Error:', error.response.data);
console.error('Status:', error.response.status);
} else {
// Network or other error
console.error('Error:', error.message);
}
}
```
## License
MIT