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

Is possible to store data into Firebase with some connector¿? #197

Closed alexllao closed 3 years ago

alexllao commented 4 years ago

Thnks a lot.

jahead commented 3 years ago

You can override the store, you'd just need to implement a store that is based by firebase.

This is now I implemented the async storage for react native

import AsyncStorage from '@react-native-community/async-storage';

const generateKey = (prefix: string, key: string) => `${prefix}${key}`;

export default class AsyncStorageStore {
  private store: any;

  private prefix: string;

  constructor() {
    this.store = AsyncStorage;
    this.prefix = 'cache/';
  }

  getItem = async (key: string) => {
    try {
      const valueStr = await this.store.getItem(generateKey(this.prefix, key));
      if (valueStr) return JSON.parse(valueStr);
      return null;
    } catch (e) {
      throw new Error(`unable to get item, ${e}`);
    }
  };

  setItem = async (key: string, value: string) =>
    this.store.setItem(generateKey(this.prefix, key), JSON.stringify(value));

  removeItem = async (key: string) =>
    this.store.removeItem(generateKey(this.prefix, key));

  clear = async () => {
    const keys = await this.store.getAllKeys();
    const filtered = keys.filter((key: string) => key.startsWith(this.prefix));

    if (filtered.length <= 0) return;

    await this.store.multiRemove(filtered);
  };

  length = async () => {
    const keys = await this.store.getAllKeys();
    const filtered = keys.filter((key: string) => key.startsWith(this.prefix));
    return filtered.length;
  };

  iterate = async (fn: Function) => {
    const keys = await this.store.getAllKeys();
    const filtered = keys.filter((key: string) => key.startsWith(this.prefix));

    if (filtered.length <= 0) return;

    const keyValues = await this.store.multiGet(filtered);
    const tasks = keyValues.map((pair: [string, string]) =>
      fn(pair[0].replace(new RegExp(`^${this.prefix}`), ''), pair[1])
    );
    await Promise.all(tasks);
  };
}
ghost commented 3 years ago

Hey @alexllao !

Closing issue because as @jahead said you can implement your own store adapter. If you'd like firebase adapter to be included with axios-cache-adapter you can submit a PR.

Cheerss