@warriorteam/redai-zalo-sdk
Version:
Comprehensive TypeScript/JavaScript SDK for Zalo APIs - Official Account v3.0, ZNS with Full Type Safety, Consultation Service, Broadcast Service, Group Messaging with List APIs, Social APIs, Enhanced Article Management, Promotion Service v3.0 with Multip
223 lines (181 loc) • 6.12 kB
Markdown
# Enhanced Article API - Get All Articles
## Tổng Quan
Đã nâng cấp `ArticleService` với 2 method mới để lấy **tất cả bài viết** một cách tự động, không cần xử lý pagination thủ công:
- ✅ `getAllArticles()` - Lấy tất cả bài viết theo loại (normal hoặc video)
- ✅ `getAllArticlesCombined()` - Lấy tất cả bài viết cả 2 loại kết hợp
## Tính Năng Nâng Cao
### 🚀 Tự Động Pagination
- Tự động gọi API nhiều lần để lấy hết dữ liệu
- Không cần xử lý `offset` và `limit` thủ công
- Tự động dừng khi hết dữ liệu
### 📊 Progress Tracking
- Callback `onProgress` để theo dõi tiến trình
- Hiển thị số batch hiện tại và tổng số đã lấy
- Biết được còn dữ liệu hay không
### ⚙️ Cấu Hình Linh Hoạt
- `batchSize`: Số bài viết mỗi lần gọi API (max 100)
- `maxArticles`: Giới hạn tổng số bài viết (0 = không giới hạn)
- `onProgress`: Callback theo dõi tiến trình
### 🛡️ An Toàn & Validation
- Validation đầu vào nghiêm ngặt
- Safety check tránh infinite loop
- Error handling toàn diện
- TypeScript support đầy đủ
## API Reference
### `getAllArticles()`
```typescript
async getAllArticles(
accessToken: string,
type: "normal" | "video" = "normal",
options: {
batchSize?: number; // Default: 50, Max: 100
maxArticles?: number; // Default: 1000, 0 = no limit
onProgress?: (progress: {
currentBatch: number;
totalFetched: number;
hasMore: boolean;
}) => void;
} = {}
): Promise<{
articles: ArticleListItem[];
totalFetched: number;
totalBatches: number;
hasMore: boolean;
}>
```
### `getAllArticlesCombined()`
```typescript
async getAllArticlesCombined(
accessToken: string,
options: {
batchSize?: number; // Default: 50, Max: 100
maxArticlesPerType?: number; // Default: 500, 0 = no limit
onProgress?: (progress: {
type: "normal" | "video";
currentBatch: number;
totalFetched: number;
hasMore: boolean;
}) => void;
} = {}
): Promise<{
articles: ArticleListItem[];
breakdown: {
normal: { articles: ArticleListItem[]; totalFetched: number; totalBatches: number; hasMore: boolean; };
video: { articles: ArticleListItem[]; totalFetched: number; totalBatches: number; hasMore: boolean; };
};
totalFetched: number;
totalBatches: number;
}>
```
## Ví Dụ Sử Dụng
### 1. Lấy Tất Cả Bài Viết Normal
```typescript
import { ArticleService } from "redai-zalo-sdk";
const result = await articleService.getAllArticles(accessToken, "normal", {
batchSize: 50,
maxArticles: 1000,
onProgress: (progress) => {
console.log(`Batch ${progress.currentBatch}: ${progress.totalFetched} articles`);
}
});
console.log(`Total: ${result.totalFetched} articles`);
result.articles.forEach(article => {
console.log(`- ${article.title} (${article.id})`);
});
```
### 2. Lấy Tất Cả Bài Viết Video
```typescript
const videoResult = await articleService.getAllArticles(accessToken, "video", {
batchSize: 30,
maxArticles: 500
});
console.log(`Found ${videoResult.totalFetched} video articles`);
```
### 3. Lấy Tất Cả Bài Viết (Normal + Video)
```typescript
const combinedResult = await articleService.getAllArticlesCombined(accessToken, {
batchSize: 50,
maxArticlesPerType: 500,
onProgress: (progress) => {
console.log(`${progress.type}: ${progress.totalFetched} articles`);
}
});
console.log(`Total: ${combinedResult.totalFetched} articles`);
console.log(`Normal: ${combinedResult.breakdown.normal.totalFetched}`);
console.log(`Video: ${combinedResult.breakdown.video.totalFetched}`);
```
### 4. Lấy Tất Cả Không Giới Hạn
```typescript
// ⚠️ Cẩn thận: Có thể lấy rất nhiều dữ liệu!
const unlimitedResult = await articleService.getAllArticles(accessToken, "normal", {
batchSize: 100,
maxArticles: 0, // 0 = không giới hạn
onProgress: (progress) => {
console.log(`Fetching... ${progress.totalFetched} articles so far`);
}
});
```
## So Sánh Với API Cũ
### Trước (API cũ)
```typescript
// Phải xử lý pagination thủ công
let offset = 0;
const limit = 50;
const allArticles = [];
while (true) {
const response = await articleService.getArticleList(accessToken, {
offset,
limit,
type: "normal"
});
if (!response.data?.medias || response.data.medias.length === 0) {
break;
}
allArticles.push(...response.data.medias);
offset += response.data.medias.length;
if (response.data.medias.length < limit) {
break;
}
}
```
### Sau (API mới)
```typescript
// Chỉ 1 dòng code!
const result = await articleService.getAllArticles(accessToken, "normal");
const allArticles = result.articles;
```
## Lưu Ý Quan Trọng
### ⚠️ Giới Hạn Rate Limit
- Zalo API có giới hạn số request/phút
- Sử dụng `batchSize` hợp lý (khuyến nghị: 50)
- Đặt `maxArticles` để tránh quá tải
### 🔒 Bảo Mật
- Luôn validate `accessToken`
- Không hardcode token trong code
- Sử dụng environment variables
### 📈 Performance
- `batchSize` lớn = ít request nhưng response lớn
- `batchSize` nhỏ = nhiều request nhưng response nhỏ
- Khuyến nghị: 50-100 articles/batch
### 🛡️ Error Handling
```typescript
try {
const result = await articleService.getAllArticles(accessToken, "normal");
// Xử lý thành công
} catch (error) {
if (error instanceof ZaloSDKError) {
console.error("Zalo API Error:", error.message);
} else {
console.error("Unknown Error:", error);
}
}
```
## Kết Luận
API mới giúp:
- ✅ Đơn giản hóa việc lấy tất cả bài viết
- ✅ Tự động xử lý pagination
- ✅ Theo dõi tiến trình real-time
- ✅ Type-safe với TypeScript
- ✅ Error handling tốt hơn
- ✅ Cấu hình linh hoạt
Sử dụng `getAllArticles()` cho 1 loại bài viết hoặc `getAllArticlesCombined()` cho cả 2 loại!