Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 09b7240

Browse files
committed
[docs]: adding api folder under ./ru to keep english and ru in sync
1 parent 5f22681 commit 09b7240

File tree

5 files changed

+1232
-0
lines changed

5 files changed

+1232
-0
lines changed

docs/ru/dev/api/get-started_ru.md

Lines changed: 251 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,251 @@
1+
# Начало работы
2+
3+
# Документация по API Bastyon Pocketnet Proxy
4+
5+
## Обзор
6+
API Bastyon Pocketnet Proxy предоставляет разработчикам инструменты для создания и интеграции приложений в экосистему Bastyon. Это руководство объясняет, как безопасно и эффективно использовать наши RPC методы с поддержкой TypeScript.
7+
8+
Инструкции по настройке предполагают, что у вас есть фронтенд, который будет вызывать бэкенд-контроллеры, определенные ниже.
9+
10+
Высокоуровневая диаграмма типичного приложения выглядит следующим образом:
11+
12+
<div style="text-align: center;">
13+
<img src="../assets/images/mini-app-flow.png" alt="mini-app-flow">
14+
</div>
15+
16+
## Настройка и инициализация
17+
18+
До тех пор, пока API прокси не будет доступен через npm, мы рекомендуем использовать наш шаблонный проект: [Bastyon Mini-App Express.js Template][template-link].
19+
20+
Следующие инструкции предполагают, что вы установили папку /lib, содержащую SDK pocketnet-proxy-api.
21+
22+
Что это означает: Сначала вам нужно будет клонировать наш шаблонный репозиторий, так как он содержит все необходимые файлы и конфигурации для быстрого начала работы.
23+
24+
[template-link]: https://github.com/DaniilKimlb/bastyon-miniapp-expressjs-template
25+
26+
```typescript
27+
import express from 'express';
28+
import type { Request, Response } from 'express';
29+
import { PocketNetProxyApi } from '../lib';
30+
import type {
31+
GetNodeInfoParams,
32+
GetUserProfileParams,
33+
SearchParams
34+
} from '../lib/rpc.types';
35+
36+
const app = express();
37+
```
38+
39+
## Управление экземпляром API
40+
Что это означает: Мы используем паттерн Singleton для управления единым экземпляром API во всем приложении. Этот подход более эффективен и предотвращает множественные ненужные подключения.
41+
42+
```typescript
43+
// lib/index.ts
44+
import PocketNetProxyApi from './pocketnet-proxy-api';
45+
46+
let pocketNetProxyInstance: PocketNetProxyApi | null = null;
47+
48+
export async function getPocketNetProxyInstance(): Promise<PocketNetProxyApi> {
49+
if (!pocketNetProxyInstance) {
50+
pocketNetProxyInstance = await PocketNetProxyApi.create();
51+
}
52+
return pocketNetProxyInstance;
53+
}
54+
55+
export { PocketNetProxyApi };
56+
```
57+
58+
## Обработчики маршрутов
59+
Что это означает: Это эндпоинты, которые ваше приложение будет предоставлять для обработки различных типов запросов. Каждый обработчик отвечает за конкретную функцию, такую как получение информации о ноде или профилей пользователей.
60+
61+
### Получение информации о ноде
62+
Что это означает: Этот эндпоинт получает текущий статус и информацию о ноде сети Bastyon, что полезно для мониторинга и диагностики.
63+
64+
```typescript
65+
// controllers/node.controller.ts
66+
import type { Request, Response } from 'express';
67+
import { getPocketNetProxyInstance } from '../lib';
68+
69+
/**
70+
* GET /nodeinfo
71+
*
72+
* Получает информацию о ноде из сети Bastyon.
73+
* Использует RPC метод getnodeinfo для получения текущего статуса ноды.
74+
*
75+
* @param {Request} req - Объект запроса Express
76+
* @param {Response} res - Объект ответа Express
77+
* @returns {Promise<void>} JSON ответ с информацией о ноде
78+
*
79+
* @example
80+
* // Регистрация маршрута
81+
* app.get('/nodeinfo', getNodeInfo);
82+
*
83+
* // Успешный ответ
84+
* {
85+
* "message": "Информация о ноде успешно получена",
86+
* "data": {
87+
* // Объект информации о ноде
88+
* }
89+
* }
90+
*/
91+
export async function getNodeInfo(
92+
req: Request,
93+
res: Response
94+
): Promise<void> {
95+
try {
96+
const api = await getPocketNetProxyInstance();
97+
const result = await api.rpc.getnodeinfo();
98+
99+
res.status(200).json({
100+
message: 'Информация о ноде успешно получена',
101+
data: result
102+
});
103+
} catch (error) {
104+
res.status(500).json({
105+
message: 'Не удалось получить информацию о ноде',
106+
error: error instanceof Error ? error.message : 'Неизвестная ошибка'
107+
});
108+
}
109+
}
110+
```
111+
112+
### Получение профиля пользователя
113+
Что это означает: Этот эндпоинт получает информацию о конкретном пользователе, используя его блокчейн-адрес. Обычно используется для отображения деталей пользователя и верификации.
114+
115+
```typescript
116+
// controllers/user.controller.ts
117+
import type { Request, Response } from 'express';
118+
import { getPocketNetProxyInstance } from '../lib';
119+
import type { GetUserProfileParams } from '../lib/rpc.types';
120+
121+
/**
122+
* GET /user/:address
123+
*
124+
* Получает информацию о профиле пользователя для заданного адреса.
125+
*
126+
* @param {Request} req - Объект запроса Express с параметром address
127+
* @param {Response} res - Объект ответа Express
128+
* @returns {Promise<void>} JSON ответ с профилем пользователя
129+
*
130+
* @example
131+
* // Регистрация маршрута
132+
* app.get('/user/:address', getUserProfile);
133+
*
134+
* // Успешный ответ
135+
* {
136+
* "message": "Профиль пользователя успешно получен",
137+
* "data": {
138+
* // Объект профиля пользователя
139+
* }
140+
* }
141+
*/
142+
export async function getUserProfile(
143+
req: Request,
144+
res: Response
145+
): Promise<void> {
146+
try {
147+
const { address } = req.params;
148+
const api = await getPocketNetProxyInstance();
149+
150+
const result = await api.rpc.getuserprofile({
151+
address,
152+
shortForm: "basic"
153+
} satisfies GetUserProfileParams);
154+
155+
res.status(200).json({
156+
message: 'Профиль пользователя успешно получен',
157+
data: result
158+
});
159+
} catch (error) {
160+
res.status(500).json({
161+
message: 'Не удалось получить профиль пользователя',
162+
error: error instanceof Error ? error.message : 'Неизвестная ошибка'
163+
});
164+
}
165+
}
166+
```
167+
168+
### Поиск контента
169+
Что это означает: Этот эндпоинт позволяет пользователям искать контент на платформе с поддержкой пагинации для эффективной обработки больших наборов результатов.
170+
171+
```typescript
172+
// controllers/search.controller.ts
173+
import type { Request, Response } from 'express';
174+
import { getPocketNetProxyInstance } from '../lib';
175+
import type { SearchParams } from '../lib/rpc.types';
176+
177+
/**
178+
* GET /search
179+
*
180+
* Поиск контента с поддержкой пагинации.
181+
*
182+
* @param {Request} req - Объект запроса Express с параметрами запроса
183+
* @param {Response} res - Объект ответа Express
184+
* @returns {Promise<void>} JSON ответ с результатами поиска
185+
*
186+
* @example
187+
* // Регистрация маршрута
188+
* app.get('/search', searchContent);
189+
*
190+
* // Запрос
191+
* GET /search?keyword=blockchain&page=1&pageSize=20
192+
*
193+
* // Успешный ответ
194+
* {
195+
* "message": "Поиск успешно завершен",
196+
* "data": {
197+
* "results": [],
198+
* "total": 0
199+
* }
200+
* }
201+
*/
202+
export async function searchContent(
203+
req: Request,
204+
res: Response
205+
): Promise<void> {
206+
try {
207+
const {
208+
keyword,
209+
page = '0',
210+
pageSize = '20'
211+
} = req.query;
212+
213+
const api = await getPocketNetProxyInstance();
214+
215+
const result = await api.rpc.search({
216+
keyword: String(keyword),
217+
type: "content",
218+
pageStart: Number(page),
219+
pageSize: Number(pageSize)
220+
} satisfies SearchParams);
221+
222+
res.status(200).json({
223+
message: 'Поиск успешно завершен',
224+
data: result
225+
});
226+
} catch (error) {
227+
res.status(500).json({
228+
message: 'Операция поиска не удалась',
229+
error: error instanceof Error ? error.message : 'Неизвестная ошибка'
230+
});
231+
}
232+
}
233+
```
234+
235+
### Экспорт контроллеров
236+
Что это означает: Этот файл централизует все обработчики маршрутов (контроллеры) в одном месте для лучшей организации и поддерживаемости.
237+
238+
```typescript
239+
// controllers/index.ts
240+
export * from './node.controller';
241+
export * from './user.controller';
242+
export * from './search.controller';
243+
```
244+
245+
### Регистрация маршрутов
246+
Что это означает: Здесь вы определяете, какие URL-адреса вызывают какие обработчики в вашем приложении. Это сопоставляет URL-адреса с соответствующими функциями.
247+
248+
```typescript
249+
// routes/index.ts
250+
import express from 'express';
251+
```

docs/ru/dev/api/introduction.md

Lines changed: 67 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,67 @@
1+
# Introduction
2+
3+
# Bastyon Pocketnet Proxy API Documentation
4+
5+
## Introduction
6+
7+
The Bastyon Pocketnet Proxy API serves as a powerful gateway for developers to build and integrate applications within the Bastyon ecosystem. This comprehensive API enables developers to harness the full potential of Bastyon's decentralized platform, providing access to core functionalities such as user management, content distribution, blockchain operations, and social networking features.
8+
9+
### What is Bastyon Pocketnet Proxy?
10+
11+
Bastyon's Pocketnet Proxy is a middleware layer that facilitates seamless communication between applications and the Bastyon blockchain network. It provides a standardized interface for developers to interact with the platform's features while abstracting the complexity of direct blockchain interactions.
12+
13+
### Key Features
14+
15+
- **User Management**: Complete suite of methods for handling user profiles, authentication, and account management
16+
- **Content Management**: Tools for creating, retrieving, and managing content across the platform
17+
- **Social Networking**: APIs for handling user interactions, subscriptions, and social connections
18+
- **Blockchain Operations**: Direct access to blockchain functionalities including transactions and block data
19+
- **Search and Discovery**: Comprehensive search capabilities across various platform elements
20+
- **Jury System**: Methods for managing the platform's decentralized moderation system
21+
22+
### API Design Principles
23+
24+
The API follows these core principles:
25+
26+
1. **Consistency**: All methods follow a standardized naming convention and response format
27+
2. **Scalability**: Built-in pagination and efficient data handling for large-scale operations
28+
3. **Security**: Robust authentication and authorization mechanisms
29+
4. **Flexibility**: Support for various use cases and integration scenarios
30+
31+
### Getting Started
32+
33+
This documentation provides a complete reference of all available API methods, including:
34+
35+
- Detailed method definitions and parameters
36+
- Working code examples for each method
37+
- Common usage patterns and best practices
38+
- Error handling guidelines
39+
- Response format specifications
40+
41+
### Who Should Use This API?
42+
43+
- Application developers building on the Bastyon platform
44+
- Integration developers connecting existing systems with Bastyon
45+
- Content creators looking to automate their workflow
46+
- Developers building tools for the Bastyon ecosystem
47+
48+
### Prerequisites
49+
50+
Before using the API, you should have:
51+
52+
- Basic understanding of REST APIs and JSON
53+
- Familiarity with blockchain concepts
54+
- Knowledge of TypeScript/JavaScript (for provided examples)
55+
- Access credentials for the Bastyon platform
56+
57+
### How to Use This Documentation
58+
59+
The documentation is organized into logical sections based on functionality:
60+
61+
1. **Method Reference**: Complete list of all available API methods
62+
2. **Usage Examples**: Real-world examples of API implementation
63+
3. **Best Practices**: Guidelines for optimal API usage
64+
4. **Error Handling**: Common error scenarios and how to handle them
65+
5. **Advanced Topics**: Complex implementation patterns and optimizations
66+
67+
Let's begin exploring the comprehensive set of API methods available for building powerful applications on the Bastyon platform.

docs/ru/dev/api/miniapps.md

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
# MiniApps

0 commit comments

Comments
 (0)