Skip to content

Commit 4fc9588

Browse files
authored
docs: added openapi-axios fetcher (#1122) (#1911)
1 parent fdc6d22 commit 4fc9588

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

docs/examples.md

+70
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,76 @@ try {
140140

141141
</details>
142142

143+
<details>
144+
<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>
145+
146+
::: code-group
147+
148+
```ts [test/my-project.ts]
149+
import { OpenApiAxios } from "@web-bee-ru/openapi-axios";
150+
import type { paths } from "./my-openapi-3-schema"; // generated by openapi-typescript
151+
import Axios from "axios";
152+
153+
const axios = Axios.create({
154+
baseURL: "https://myapi.dev/v1",
155+
adapter: "fetch", // strongly recommended (available since [email protected])
156+
});
157+
158+
// Example 1. Usage with "axios" (default) status handling strategy (validStatus: 'axios')
159+
160+
const api = new OpenApiAxios<paths, "axios">(axios, { validStatus: "axios" }); // throws like axios (e.g. status 400+, network errors, interceptor errors)
161+
// const api = new OpenApiAxios<paths>(axios) // same result
162+
163+
try {
164+
const { status, data, response } = await api.get("/users");
165+
} catch (err) {
166+
if (api.isAxiosError(err)) {
167+
if (typeof err.status === "number") {
168+
// status >= 400
169+
}
170+
// request failed (e.g. network error)
171+
}
172+
throw err; // axios.interceptors error
173+
}
174+
175+
// Example 2. Usage with "fetch" status handling strategy (validStatus: 'fetch')
176+
177+
const fetchApi = new OpenApiAxios<paths, "fetch">(axios, { validStatus: "fetch" }); // throws like browser's fetch() (e.g. network errors, interceptor errors)
178+
179+
try {
180+
const { status, data, error, response } = await api.get("/users");
181+
182+
if (error) {
183+
// status >= 400
184+
}
185+
} catch (err) {
186+
if (api.isAxiosError(err)) {
187+
// request failed (e.g. network error)
188+
}
189+
throw err; // axios.interceptors error
190+
}
191+
192+
// Example 3. Usage with "safe" status handling strategy (validStatus: 'all')
193+
// (No try/catch required)
194+
195+
const safeApi = new OpenApiAxios<paths, "all">(axios, { validStatus: "all" }); // never throws errors
196+
197+
const { status, data, error, response } = await api.get("/users");
198+
199+
if (error) {
200+
if (typeof status === "number") {
201+
// status >= 400
202+
} else if (api.isAxiosError(error)) {
203+
// request failed (e.g. network error)
204+
}
205+
throw error; // axios.interceptors error
206+
}
207+
```
208+
209+
:::
210+
211+
</details>
212+
143213

144214
::: tip
145215

0 commit comments

Comments
 (0)