api icon indicating copy to clipboard operation
api copied to clipboard

Restructure the data we're returning so it's easier to access Response data

Open erunion opened this issue 3 years ago • 1 comments

With the way api currently is if you want to access response status codes or headers you need to set sdk.config({ parseResponse: false }) and then handle res.json() or res.text() yourself. Because we can do better than this we can return all this data back for the user instead:

const petstore = require('@api/petstore');
const { data, status, headers, res } = await petstore.listPets();
console.log(`My pets name is ${data[0].name}!`);
  • data: equates to the current default data we return in the SDK promise (the result of res.json() or res.text()
  • status: Will be the content of res.status
  • headers: Maps to res.headers
  • res: This is the raw Response object that the fetch API returns.

  • [ ] Update api/core to return data in this shape.
  • [ ] Update codegen to return data in this shape, with correct typing.
  • [ ] Update code snippet generation to return data in this shape.
  • [ ] Write an upgrade doc as this will be a breaking change.

erunion avatar Oct 17 '22 22:10 erunion

We're also going to do the same for errors that are thrown and stuff these four datapoints into a new FetchError error that's thrown for responses that have an HTTP status of >=400 and <=599. Here's what this will look like:

await petstore
  .deletePet({ id: petId })
  .catch(({ status, data }) => {
    // status = 404
    // data = 'Not Found'
  });

Or if you want to assert that the error being caught is maybe something else:

await petstore
  .deletePet({ id: petId })
  .catch(err => {
    if (!(err instanceof FetchError)) {
      throw err;
    }

    // err.status = 404
    // err.data = 'Not Found'
  });  

erunion avatar Oct 19 '22 17:10 erunion