-
Notifications
You must be signed in to change notification settings - Fork 206
Add ru and ja translations for api-requests page #828
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
Solant
wants to merge
11
commits into
feature-sliced:master
Choose a base branch
from
Solant:feat/api-docs-translation
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
ea68ad4
feat: add translation banner for documentation with multilingual support
Solant 5109a2f
docs: add ru translation
Solant 62933cb
docs: add Japanese API requests guide
Solant 22f6268
fix: use anchor instead of Link to prevent build error
Solant 38af454
docs: remove machine translated page
Solant f85f3a3
fix: apply review suggestion
Solant f50849c
fix: apply review suggestion
Solant 9b6db9b
fix: apply review suggestion
Solant c6d590e
fix: apply review suggestion
Solant 617130d
fix: apply review suggestion
Solant b76b691
fix: add reference to React Query article in API requests guide
Solant File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
142 changes: 142 additions & 0 deletions
142
i18n/ru/docusaurus-plugin-content-docs/current/guides/examples/api-requests.mdx
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,142 @@ | ||
--- | ||
sidebar_position: 4 | ||
--- | ||
|
||
import Tabs from '@theme/Tabs'; | ||
import TabItem from '@theme/TabItem'; | ||
|
||
# Обработка API-запросов {#handling-api-requests} | ||
|
||
## API-запросы в `shared` {#shared-api-requests} | ||
|
||
Начните с размещения общей логики API-запросов в каталоге `shared/api`. Это упрощает повторное использование запросов во всем приложении, что ускоряет разработку. Для многих проектов этого будет достаточно. | ||
|
||
Типичная структура файлов будет такой: | ||
- 📂 shared | ||
- 📂 api | ||
- 📄 client.ts | ||
- 📄 index.ts | ||
- 📂 endpoints | ||
- 📄 login.ts | ||
|
||
Файл `client.ts` централизует настройку HTTP-запросов. Он оборачивает выбранный вами подход (например, `fetch()` или экземпляр `axios`) и обрабатывает общие конфигурации, такие как: | ||
|
||
- Базовый URL бэкенда. | ||
- Заголовки по умолчанию (например, для аутентификации). | ||
- Сериализация данных. | ||
|
||
Вот примеры для `axios` и `fetch`: | ||
|
||
<Tabs> | ||
|
||
<TabItem value="axios" label="Axios"> | ||
```ts title="shared/api/client.ts" | ||
// Example using axios | ||
import axios from 'axios'; | ||
|
||
export const client = axios.create({ | ||
baseURL: 'https://your-api-domain.com/api/', | ||
timeout: 5000, | ||
headers: { 'X-Custom-Header': 'my-custom-value' } | ||
}); | ||
``` | ||
</TabItem> | ||
|
||
<TabItem value="fetch" label="Fetch"> | ||
```ts title="shared/api/client.ts" | ||
export const client = { | ||
async post(endpoint: string, body: any, options?: RequestInit) { | ||
const response = await fetch(`https://your-api-domain.com/api${endpoint}`, { | ||
method: 'POST', | ||
body: JSON.stringify(body), | ||
...options, | ||
headers: { | ||
'Content-Type': 'application/json', | ||
'X-Custom-Header': 'my-custom-value', | ||
...options?.headers, | ||
}, | ||
}); | ||
return response.json(); | ||
} | ||
// ... другие методы put, delete, и т.д. | ||
}; | ||
``` | ||
</TabItem> | ||
|
||
</Tabs> | ||
|
||
Организуйте свои отдельные функции API-запросов в shared/api/endpoints, группируя их по API эндпоинтам. | ||
|
||
:::note | ||
|
||
Для простоты, в примерах ниже мы опускаем взаимодействие с формами и валидацию. Для получения подробной информации о том, как работать с такими библиотеками как Zod или Valibot, обратитесь к секции [Проверка типов и схемы](/docs/guides/examples/types#type-validation-schemas-and-zod). | ||
|
||
::: | ||
|
||
```ts title="shared/api/endpoints/login.ts" | ||
import { client } from '../client'; | ||
|
||
export interface LoginCredentials { | ||
email: string; | ||
password: string; | ||
} | ||
|
||
export function login(credentials: LoginCredentials) { | ||
return client.post('/login', credentials); | ||
} | ||
``` | ||
|
||
Используйте файл `index.ts` в `shared/api` для экспорта ваших функций запросов. | ||
|
||
```ts title="shared/api/index.ts" | ||
export { client } from './client'; // Если нужно экспортировать клиент | ||
export { login } from './endpoints/login'; | ||
export type { LoginCredentials } from './endpoints/login'; | ||
``` | ||
|
||
## API-запросы, специфичные для слайса {#slice-specific-api-requests} | ||
|
||
Если API-запрос используется только определенным слайсом (например, одной страницей или фичей) и не будет использоваться повторно, поместите его в сегмент `api` этого слайса. Это позволит аккуратно отделить логику, специфичную для слайса, от всего остального приложения. | ||
|
||
- 📂 pages | ||
- 📂 login | ||
- 📄 index.ts | ||
- 📂 api | ||
- 📄 login.ts | ||
- 📂 ui | ||
- 📄 LoginPage.tsx | ||
|
||
```ts title="pages/login/api/login.ts" | ||
import { client } from 'shared/api'; | ||
|
||
interface LoginCredentials { | ||
email: string; | ||
password: string; | ||
} | ||
|
||
export function login(credentials: LoginCredentials) { | ||
return client.post('/login', credentials); | ||
} | ||
``` | ||
|
||
Вам не нужно экспортировать функцию `login()` через публичный API страницы, потому что маловероятно, что какое-либо другое место в приложении будет нуждаться в этом запросе. | ||
|
||
:::note | ||
|
||
Избегайте преждевременного размещения API-запросов и типов ответов бэкенда в слое `entities`. Ответы бэкенда могут отличаться от того, что нужно вашим сущностям фронтенда. Логика API в `shared/api` или сегменте `api` слайса позволяет вам преобразовывать данные при необходимости, сохраняя фокус сущностей на проблемах фронтенда. | ||
|
||
::: | ||
|
||
## Использование генераторов клиентов {#client-generators} | ||
|
||
Если ваш бэкенд предоставляет OpenAPI спецификацию, инструменты как [orval](https://orval.dev/) или [openapi-typescript](https://openapi-ts.dev/), могут генерировать типы API и функции запросов. Разместите сгенерированный код, например, в `shared/api/openapi`. Обязательно включите `README.md` для документирования того, что это за типы и как их генерировать. | ||
|
||
## Интеграция с библиотеками состояния сервера {#server-state-libraries} | ||
|
||
При использовании библиотек состояния сервера, таких как [TanStack Query (React Query)](https://tanstack.com/query/latest) или [Pinia Colada](https://pinia-colada.esm.dev/) вам может потребоваться совместное использование типов или ключей кеша между срезами. Используйте общий слой `shared` для таких вещей, как: | ||
|
||
- Типы данных API | ||
- Ключи кеша | ||
- Общие параметры запросов и мутаций | ||
|
||
Подробнее о том, как работать с server state библиотеками, читайте в статье [React Query](/docs/guides/tech/with-react-query) |
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
suggestion: would be nice to link to the article about using FSD with tanstack query here
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
done, hope this helps