Skip to content

Convert axios response to Response() object to cache API requests #5857

Discussion options

You must be logged in to vote

I haven't gone through the codebase, but here's how we can convert an axis response into a Response object.

`
import axios from 'axios';
function convertToResponseLike(axiosResponse) {
  const { data, status, statusText, headers } = axiosResponse;

  class ResponseLike {
    constructor(responseData, init = {}) {
      this.body = responseData;
      this.status = init.status || 200;
      this.statusText = init.statusText || 'OK';
      this.headers = init.headers || new Headers();
    }

    async json() {
      return JSON.parse(this.body);
    }
  }

  return new ResponseLike(JSON.stringify(data), {
    status,
    statusText,
    headers,
  });
}
axios.get('https://api.example.com/da…

Replies: 3 comments

Comment options

You must be logged in to vote
0 replies
Answer selected by christianholland
Comment options

You must be logged in to vote
0 replies
Comment options

You must be logged in to vote
0 replies
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants
Converted from issue

This discussion was converted from issue #5799 on September 04, 2023 12:54.