-
Notifications
You must be signed in to change notification settings - Fork 218
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
Merged
illright
merged 11 commits into
feature-sliced:master
from
Solant:feat/api-docs-translation
Aug 4, 2025
Merged
Changes from 4 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
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
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
144 changes: 144 additions & 0 deletions
144
i18n/ja/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,144 @@ | ||
| --- | ||
| sidebar_position: 4 | ||
| title: APIリクエストの処理 | ||
| --- | ||
|
|
||
| import Tabs from '@theme/Tabs'; | ||
| import TabItem from '@theme/TabItem'; | ||
| import TranslationBanner from "@site/src/shared/ui/translation-banner/tmpl.mdx" | ||
|
|
||
| <TranslationBanner /> | ||
|
|
||
| # APIリクエストの処理 {#handling-api-requests} | ||
|
|
||
| ## 共有APIリクエスト {#shared-api-requests} | ||
|
|
||
| 共通のAPIリクエストロジックは`shared/api`ディレクトリに配置することから始めます。これにより、アプリケーション全体でリクエストを簡単に再利用でき、プロトタイピングの高速化に役立ちます。多くのプロジェクトでは、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(); | ||
| } | ||
| // ... other methods like put, delete, etc. | ||
| }; | ||
| ``` | ||
| </TabItem> | ||
|
|
||
| </Tabs> | ||
|
|
||
| 個々のAPIリクエスト関数は`shared/api/endpoints`に、APIエンドポイントごとにグループ化して整理します。 | ||
|
|
||
| :::note | ||
|
|
||
| 例をわかりやすくするために、フォームのインタラクションとバリデーションは省略しています。ZodやValibotのようなライブラリの詳細については、[Type Validation and Schemas](/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); | ||
| } | ||
| ``` | ||
|
|
||
| `shared/api`の`index.ts`ファイルを使用して、リクエスト関数をエクスポートします。 | ||
|
|
||
| ```ts title="shared/api/index.ts" | ||
| export { client } from './client'; // If you want to export the client itself | ||
| 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); | ||
| } | ||
| ``` | ||
|
|
||
| このリクエストがアプリケーションの他の場所で必要になる可能性は低いので、ページの公開APIで`login()`関数をエクスポートする必要はありません。 | ||
|
|
||
| :::note | ||
|
|
||
| API呼び出しとレスポンスの型を`entities`レイヤーに時期尚早に配置することは避けてください。バックエンドのレスポンスは、フロントエンドのエンティティが必要とするものと異なる場合があります。`shared/api`またはスライスの`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データ型 | ||
| - キャッシュキー | ||
| - 共通のクエリ/ミューテーションオプション |
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
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
140 changes: 140 additions & 0 deletions
140
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,140 @@ | ||
| --- | ||
| 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`. Это упрощает повторное использование запросов во всем приложении и помогает ускорить прототипирование. Для многих проектов этого будет достаточно для вызовов API. | ||
|
Solant marked this conversation as resolved.
Outdated
|
||
|
|
||
| Типичная структура файлов будет такой: | ||
| - 📂 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). | ||
|
Solant marked this conversation as resolved.
Outdated
|
||
|
|
||
| ::: | ||
|
|
||
| ```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-запросы, специфичные для слайса {#client-generators} | ||
|
Solant marked this conversation as resolved.
Outdated
|
||
|
|
||
| Если API-запрос используется только определенным слайсом (например, одной страницей или функцией) и не будет использоваться повторно, поместите его в сегмент api этого слайса. Это позволит аккуратно хранить логику, специфичную для слайса. | ||
|
Solant marked this conversation as resolved.
Outdated
|
||
|
|
||
| - 📂 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` слайса позволяет вам преобразовывать данные при необходимости, сохраняя фокус сущностей на проблемах фронтенда. | ||
|
Solant marked this conversation as resolved.
Outdated
|
||
|
|
||
| ::: | ||
|
|
||
| ## Использование генераторов клиентов {#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 | ||
| - Ключи кеша | ||
| - Общие параметры запросов и мутаций | ||
|
illright marked this conversation as resolved.
|
||
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
Oops, something went wrong.
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.
Uh oh!
There was an error while loading. Please reload this page.