Skip to content

Commit 1ca5cd3

Browse files
committed
docs(ja): add web-bee-ru/openapi-axios to examples, 4fc9588
1 parent ad854a0 commit 1ca5cd3

File tree

1 file changed

+76
-0
lines changed

1 file changed

+76
-0
lines changed

docs/ja/examples.md

Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -142,6 +142,82 @@ try {
142142

143143
</details>
144144

145+
<details>
146+
<summary><a href="https://www.npmjs.com/package/@web-bee-ru/openapi-axios" target="_blank" rel="noreferrer">openapi-axios</a> by <a href="https://github.com/web-bee-ru" target="_blank" rel="noreferrer">@web-bee-ru</a></summary>
147+
148+
::: code-group
149+
150+
```ts [test/my-project.ts]
151+
import { OpenApiAxios } from "@web-bee-ru/openapi-axios";
152+
import type { paths } from "./my-openapi-3-schema"; // openapi-typescriptで生成された型
153+
import Axios from "axios";
154+
155+
const axios = Axios.create({
156+
baseURL: "https://myapi.dev/v1",
157+
adapter: "fetch", // 強く推奨 (axios@1.7.0 から利用可能)
158+
});
159+
160+
// 例1. "axios"(デフォルト)のステータス処理方法での使用 (validStatus: 'axios')
161+
162+
// axiosのようにエラーを投げる(例:status >= 400、ネットワークエラー、インターセプターエラー)
163+
const api = new OpenApiAxios<paths, "axios">(axios, { validStatus: "axios" });
164+
165+
// const api = new OpenApiAxios<paths>(axios) // 同じ結果になる
166+
167+
try {
168+
const { status, data, response } = await api.get("/users");
169+
} catch (err) {
170+
if (api.isAxiosError(err)) {
171+
if (typeof err.status === "number") {
172+
// status >= 400
173+
}
174+
// リクエスト失敗(例:ネットワークエラー)
175+
}
176+
throw err; // axios.interceptors のエラー
177+
}
178+
179+
// 例2. "fetch" ステータス処理方法での使用 (validStatus: 'fetch')
180+
181+
// ブラウザのfetch()のようにエラーを投げる(例:ネットワークエラー、インターセプターエラー)
182+
const fetchApi = new OpenApiAxios<paths, "fetch">(axios, {
183+
validStatus: "fetch",
184+
});
185+
186+
try {
187+
const { status, data, error, response } = await api.get("/users");
188+
189+
if (error) {
190+
// status >= 400
191+
}
192+
} catch (err) {
193+
if (api.isAxiosError(err)) {
194+
// リクエスト失敗(例:ネットワークエラー)
195+
}
196+
throw err; // axios.interceptors のエラー
197+
}
198+
199+
// 例3. "safe" ステータス処理方法での使用 (validStatus: 'all')
200+
// (try/catch は不要)
201+
202+
// エラーは投げない
203+
const safeApi = new OpenApiAxios<paths, "all">(axios, { validStatus: "all" });
204+
205+
const { status, data, error, response } = await api.get("/users");
206+
207+
if (error) {
208+
if (typeof status === "number") {
209+
// status >= 400
210+
} else if (api.isAxiosError(error)) {
211+
// リクエスト失敗(例:ネットワークエラー
212+
}
213+
throw error; // axios.interceptors のエラー
214+
}
215+
```
216+
217+
:::
218+
219+
</details>
220+
145221
::: tip
146222

147223
良い fetch ラッパーは**ジェネリクスの使用は避ける**べきです。ジェネリクスは多くのタイプ指定が必要で、エラーを隠してしまう可能性があります!

0 commit comments

Comments
 (0)