Skip to content

Commit 41dee3e

Browse files
authored
readme: openapi-typescript-fetch (openapi-ts#793)
1 parent 93f0c42 commit 41dee3e

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

README.md

+49
Original file line numberDiff line numberDiff line change
@@ -88,6 +88,55 @@ Even though `operations` isn’t present in your original schema, it’s a simpl
8888

8989
_Thanks to [@gr2m](https://github.com/gr2m) for the operations feature!_
9090

91+
#### openapi-typescript-fetch
92+
93+
The generated spec can also be used with [openapi-typescript-fetch](https://www.npmjs.com/package/openapi-typescript-fetch) which implements a typed fetch client for openapi-typescript.
94+
95+
```ts
96+
import { paths } from './petstore'
97+
98+
import { Fetcher } from 'openapi-typescript-fetch'
99+
100+
// declare fetcher for paths
101+
const fetcher = Fetcher.for<paths>()
102+
103+
// global configuration
104+
fetcher.configure({
105+
baseUrl: 'https://petstore.swagger.io/v2',
106+
init: {
107+
headers: {
108+
...
109+
},
110+
},
111+
use: [...] // middlewares
112+
})
113+
114+
// create fetch operations
115+
const findPetsByStatus = fetcher.path('/pet/findByStatus').method('get').create()
116+
const addPet = fetcher.path('/pet').method('post').create()
117+
118+
// fetch
119+
try {
120+
const { status, data: pets } = await findPetsByStatus({
121+
status: ['available', 'pending'],
122+
})
123+
await addPet({ ... })
124+
} catch(e) {
125+
// check which operation threw the exception
126+
if (e instanceof addPet.Error) {
127+
// get discriminated union { status, data }
128+
const error = e.getActualType()
129+
if (error.status === 400) {
130+
error.data.validationErrors // 400 response data
131+
} else if (error.status === 500) {
132+
error.data.errorMessage // 500 response data
133+
} else {
134+
...
135+
}
136+
}
137+
}
138+
```
139+
91140
#### Outputting to stdout
92141

93142
Simply omit the `--output` flag to return to stdout:

0 commit comments

Comments
 (0)