lisaogren / axios-cache-adapter

Caching adapter for axios. Store request results in a configurable store to prevent unneeded network requests.
MIT License
726 stars 107 forks source link

Caching binary contents? Possible? #82

Open armond-avanes opened 5 years ago

armond-avanes commented 5 years ago

I'm using v2.3.0 and with the following config block (as a global setup for my Axios instance): const cache = setupCache({ readHeaders: true });

I have some [GET] APIs which return binary data (image) and they have cache headers (max-age) set on their responses, but for some reason axios-cache-adapter does not cache them. I've already verified this unintended behavior using the debug option in the above config block and from the server logs.

My question is whether caching binary contents is supported and if any specific setup needs to be done to enable that support?

ghost commented 5 years ago

Hi @armond1978 !

Sorry caching binaries is disabled directly in code for now as you can see here: https://github.com/RasCarlito/axios-cache-adapter/blob/master/src/response.js#L9

This was done because when this library was first created the only reliable store was localStorage which is quite limited in space.

I've never had any use to caching binaries that were fetched with axios in my projects so I never considered changing this behavior.

Do you have any suggestions on how this should be done? Maybe I should just remove the condition which prevents caching arraybuffers or blobs?

Cheers 🍻

armond-avanes commented 5 years ago

Thanks for your positive response. Yes, it could be as simple as removing that condition.

If you can publish an alpha/beta version, I will test it in my app and will let you know if it does the job. Is there any timeline for v3.0.0?

mdmundo commented 4 years ago

For those who wants to try this now, just use npm i axios-cache-adapter@3.0.0-beta.0. Am I right?

armond-avanes commented 4 years ago

For those who wants to try this now, just use npm i axios-cache-adapter@3.0.0-beta.0. Am I right?

The pull request (https://github.com/RasCarlito/axios-cache-adapter/pull/94) has not been merged yet.

langri-sha commented 3 years ago

With https://www.npmjs.com/package/axios-cache-adapter/v/2.7.0, my store does receive setItem calls with buffered data:

const { data } = await axios.get(url, {
  responseType: 'arraybuffer',
})

I only had to update getItem for my store:

async getItem(key: string): Promise<null | any> {
  const file = this.getFile(key)

  if (await fs.exists(file)) {
    const parsed = JSON.parse((await fs.readFile(file)).toString())

    if (parsed.data?.data?.type === 'Buffer') {
      return {
        ...parsed,
        data: {
          ...parsed.data,
          data: Buffer.from(parsed.data.data),
        },
      }
    }

    return parsed
  }

  return null
}

I'm not familiar with Axios too much and I'm using some other contributing packages, so sorry if that's not the case for you!