Making Requests
If the API you're using doesn't have any documented operation IDs, api
will generate some for you to use.
With an instance of your SDK, you make an HTTP request against an operation on the API like so:
const petstore = require('@api/petstore');
petstore.listPets().then(({ data, status, headers, res }) => {
console.log(`My pets name is ${data[0].name}!`);
});
Here, the data returned in the promise from listPets
is an object containing the following data:
data
: The data that came back in the API request. Under the hood this is the result ofapi
runningres.json()
orres.text()
on the Response object from the Fetch API.status
: This is the HTTP status code of the response.headers
: The headers that came back in the response. This is an instance of the Headers object.res
: This is the raw Response object we received from the Fetch API.
Error Handling
For every response that is returned with an HTTP status code between 400 and 599, api
will throw a custom error: FetchError
. Identical to how responses are returned from successful requests, instances of FetchError
can be destructured to obtain the same data. For example:
await petstore.deletePet({ id: petId }).catch(({ status, data }) => {
// status = 404
// data = 'Not Found'
});
Alternatively if you'd like to check for an error other than FetchError
(i.e., an error with the SDK itself), you can do that too:
await petstore.deletePet({ id: petId }).catch(err => {
if (!(err instanceof FetchError)) {
throw err;
}
// err.status = 404
// err.data = 'Not Found'
});
Request Timeouts
By default, the Fetch API generally has a default timeout of 30 seconds. If you wish to configure this, you can with the .config()
method:
petstore.config({ timeout: 100 }); // 100 milliseconds
await petstore
.deletePet({ id: petId })
.then(() => {
// goodbye, friend
})
.catch(err => {
// err.message = The operation was aborted.
});
By supplying a timeout to .config({ timeout })
, in milliseconds, api
will automatically initialize an AbortController to abort your request if it takes longer than your timeout
value. Please note that if you set a custom timeout, the error that is thrown will be an instance of AbortError
, not FetchError
.
The
.config()
method is not chainable.
Updated about 1 year ago