انتقل إلى المحتوى الرئيسي

التقسيم إلى صفحات

تستخدم واجهة TakeTheme البرمجية التقسيم القائم على الصفحات للتنقل بكفاءة في المجموعات الكبيرة. ويوفّر هذا الأسلوب تنقلًا بسيطًا ومتوقّعًا في مجموعات النتائج.

كيف يعمل

عندما تطلب عنوانًا يعيد قائمة، تُعيد الواجهة:

  • دفعة من النتائج (الافتراضي: 25 عنصرًا)
  • بيانات وصفية للتقسيم تتضمن معلومات الصفحة

صيغة الاستجابة

{
"success": true,
"data": [
{ "id": "507f1f77bcf86cd799439011", "name": "Category 1" },
{ "id": "507f191e810c19729de860ea", "name": "Category 2" },
{ "id": "507f1f77bcf86cd799439012", "name": "Category 3" }
],
"pagination": {
"results": [],
"totalResults": 150,
"currentPage": 1,
"page": 1,
"limit": 25,
"lastPage": 6
}
}

التقسيم إلى صفحات Parameters

المعاملالنوعالافتراضيالوصف
pageعدد صحيح1رقم الصفحة المطلوبة
limitعدد صحيح25عدد العناصر في الصفحة
sortByنصيختلفالحقل الذي يُرتَّب به (مثل createdAt)
sortDirectionنصdescاتجاه الترتيب: asc أو desc

جلب الصفحات

الصفحة الأولى

للحصول على الصفحة الأولى، أرسل طلبًا دون تحديد رقم صفحة:

curl -X GET "https://api.taketheme.com/api/v1/category?limit=25" \
-H "tt-api-key: YOUR_API_KEY"

صفحة محددة

استخدم المعامل page للحصول على صفحة محددة:

curl -X GET "https://api.taketheme.com/api/v1/category?page=2&limit=25" \
-H "tt-api-key: YOUR_API_KEY"

الصفحة الأخيرة

احسب الصفحة الأخيرة من الحقل lastPage في استجابة التقسيم:

curl -X GET "https://api.taketheme.com/api/v1/category?page=6&limit=25" \
-H "tt-api-key: YOUR_API_KEY"

أمثلة الشيفرة

cURL

# Get first page
curl -X GET "https://api.taketheme.com/api/v1/category?limit=10" \
-H "tt-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json"

# Get page 2
curl -X GET "https://api.taketheme.com/api/v1/category?page=2&limit=10" \
-H "tt-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json"

# With sorting
curl -X GET "https://api.taketheme.com/api/v1/category?page=1&limit=10&sortBy=name&sortDirection=asc" \
-H "tt-api-key: YOUR_API_KEY" \
-H "Content-Type: application/json"

JavaScript (axios)

import axios from "axios";

const apiClient = axios.create({
baseURL: "https://api.taketheme.com/api/v1",
headers: {
tt-api-key: ` ${process.env.TAKETHEME_API_KEY}`,
"Content-Type": "application/json",
},
});

async function getAllCategories() {
const categories = [];
let currentPage = 1;
let lastPage = 1;

do {
const response = await apiClient.get("/category", {
params: {
page: currentPage,
limit: 100,
},
});

categories.push(...response.data.data);
lastPage = response.data.pagination.lastPage;
currentPage++;
} while (currentPage <= lastPage);

return categories;
}

// Usage
getAllCategories().then((categories) => {
console.log(`Retrieved ${categories.length} total categories`);
});

JavaScript (fetch)

const API_KEY = process.env.TAKETHEME_API_KEY;
const BASE_URL = "https://api.taketheme.com/api/v1";

async function getAllCategories() {
const categories = [];
let currentPage = 1;
let lastPage = 1;

do {
const url = new URL(`${BASE_URL}/category`);
url.searchParams.set("page", currentPage);
url.searchParams.set("limit", "100");

const response = await fetch(url, {
headers: {
tt-api-key: ` ${API_KEY}`,
"Content-Type": "application/json",
},
});

const result = await response.json();
categories.push(...result.data);

lastPage = result.pagination.lastPage;
currentPage++;
} while (currentPage <= lastPage);

return categories;
}

Python

import requests
import os

API_KEY = os.environ['TAKETHEME_API_KEY']
BASE_URL = 'https://api.taketheme.com/api/v1'

def get_all_categories():
categories = []
current_page = 1
last_page = 1

while current_page <= last_page:
response = requests.get(
f'{BASE_URL}/category',
headers={'tt-api-key': f'{API_KEY}'},
params={
'page': current_page,
'limit': 100
}
)

result = response.json()
categories.extend(result['data'])

last_page = result['pagination']['lastPage']
current_page += 1

return categories

# Usage
categories = get_all_categories()
print(f'Retrieved {len(categories)} total categories')

PHP

<?php

$apiKey = getenv('TAKETHEME_API_KEY');
$baseUrl = 'https://api.taketheme.com/api/v1';

function getAllCategories($apiKey, $baseUrl) {
$categories = [];
$currentPage = 1;
$lastPage = 1;

do {
$url = $baseUrl . '/category?' . http_build_query([
'page' => $currentPage,
'limit' => 100
]);

$ch = curl_init($url);
curl_setopt_array($ch, [
CURLOPT_RETURNTRANSFER => true,
CURLOPT_HTTPHEADER => [
'tt-api-key: ' . $apiKey,
'Content-Type: application/json'
]
]);

$response = curl_exec($ch);
curl_close($ch);

$result = json_decode($response, true);
$categories = array_merge($categories, $result['data']);

$lastPage = $result['pagination']['lastPage'];
$currentPage++;
} while ($currentPage <= $lastPage);

return $categories;
}

$categories = getAllCategories($apiKey, $baseUrl);
echo "Retrieved " . count($categories) . " total categories\n";

‏.NET (C#)

using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Threading.Tasks;
using System.Collections.Generic;
using Newtonsoft.Json.Linq;

public class TakeThemeClient
{
private readonly HttpClient _httpClient;
private const string BaseUrl = "https://api.taketheme.com/api/v1";

public TakeThemeClient(string apiKey)
{
_httpClient = new HttpClient();
_httpClient.DefaultRequestHeaders.Authorization =
new AuthenticationHeaderValue("Bearer", apiKey);
_httpClient.DefaultRequestHeaders.Accept.Add(
new MediaTypeWithQualityHeaderValue("application/json"));
}

public async Task<List<JObject>> GetAllCategoriesAsync()
{
var categories = new List<JObject>();
int currentPage = 1;
int lastPage = 1;

do
{
var url = $"{BaseUrl}/category?page={currentPage}&limit=100";
var response = await _httpClient.GetAsync(url);
response.EnsureSuccessStatusCode();

var content = await response.Content.ReadAsStringAsync();
var result = JObject.Parse(content);

var data = result["data"] as JArray;
foreach (var item in data)
{
categories.Add(item as JObject);
}

lastPage = result["pagination"]["lastPage"].Value<int>();
currentPage++;
} while (currentPage <= lastPage);

return categories;
}
}

// Usage
var apiKey = Environment.GetEnvironmentVariable("TAKETHEME_API_KEY");
var client = new TakeThemeClient(apiKey);
var categories = await client.GetAllCategoriesAsync();
Console.WriteLine($"Retrieved {categories.Count} total categories");

أفضل الممارسات

استخدم أحجام صفحات مناسبة

// ✓ Good: Reasonable page size for UI
const uiResponse = await fetch("/api/v1/category?limit=25");

// ✓ Good: Larger batches for background processing
const syncResponse = await fetch("/api/v1/category?limit=100");

// ✗ Avoid: Very small pages (too many requests)
const response = await fetch("/api/v1/category?limit=5");

تعامل مع النتائج الفارغة

const result = await fetchCategories(page);

if (result.data.length === 0) {
console.log("No more categories to process");
return;
}

// Process categories...

طبّق معالجة حدود المعدل

async function fetchWithRetry(url, options, maxRetries = 3) {
for (let attempt = 0; attempt < maxRetries; attempt++) {
const response = await fetch(url, options);

if (response.status === 429) {
const retryAfter = response.headers.get("Retry-After") || 1;
await sleep(retryAfter * 1000);
continue;
}

return response;
}

throw new Error("Max retries exceeded");
}

تتبّع التقدم في العمليات الطويلة

async function syncAllCategories() {
let currentPage = 1;
let lastPage = 1;
let totalProcessed = 0;

do {
const result = await fetchCategories(currentPage);

// Process batch
await processBatch(result.data);
totalProcessed += result.data.length;

console.log(
`Processed page ${currentPage}/${result.pagination.lastPage} ` +
`(${totalProcessed}/${result.pagination.totalResults} items)`
);

lastPage = result.pagination.lastPage;
currentPage++;
} while (currentPage <= lastPage);

console.log(`Sync complete! Processed ${totalProcessed} categories`);
}

الترتيب والتصفية

يعمل التقسيم مع الترتيب والتصفية:

# Paginate through filtered results
curl -X GET "https://api.taketheme.com/api/v1/category?q=electronics&page=1&limit=25" \
-H "tt-api-key: YOUR_API_KEY"

# Paginate with custom sort order
curl -X GET "https://api.taketheme.com/api/v1/category?sortBy=name&sortDirection=asc&page=1&limit=25" \
-H "tt-api-key: YOUR_API_KEY"

التقسيم إلى صفحات Metadata

الحقلالنوعالوصف
totalResultsعدد صحيحإجمالي عدد العناصر المتاحة
currentPageعدد صحيحرقم الصفحة الحالية
pageعدد صحيحرقم الصفحة الحالية (مكرر)
limitعدد صحيحعدد العناصر في الصفحة
lastPageعدد صحيحرقم الصفحة الأخيرة

اقرأ أيضًا