Coder Social home page Coder Social logo

react-native-cache's Introduction

react-native-cache

LRU cache built on top of the React Native communities' AsyncStorage v2 (or included MemoryStore) and automatic pruning of least recently used items.

Installation

  • Run the following command.
npm install --save react-native-cache
  • Import the library.
import { Cache } from "react-native-cache";

Usage

You initialize a cache using the following.

const cache = new Cache({
    namespace: "myapp",
    policy: {
        maxEntries: 50000, // if unspecified, it can have unlimited entries
        stdTTL: 0 // the standard ttl as number in seconds, default: 0 (unlimited)
    },
    backend: AsyncStorage
});

Multiple caches can be mantained in an application by instantiating caches with different namespaces.

Setting a key's value in the cache

await cache.set("hello", "world");
// key 'hello' is now set to 'world' in namespace 'myapp'

Get an item in the cache

const value = await cache.get("key1");
console.log(value);
// 'hello'
});

Getting an item from the cache also moves it to the end of the LRU list: it will be evicted from the cache last.

Delete an item from the cache

await cache.remove("key1");
// 'key1' is no more.

Peeking at an item in the cache

You can also peek at an item in the cache without updating its position in the LRU list:

const value = await cache.peek("key1");
// value is retrieved but LRU value is unchanged.

Getting all of the elements in the cache

You can look at all of the elements in the cache without updating its position in the LRU list:

const entries = await cache.getAll();
console.dir(entries);
// {
//     "key1": { "value": 42 }
//     "key2": { "value": 2 }
//     ...
// }

Clearing all of the elements in the cache

You can also clear all of the items in the cache with:

await cache.clearAll();

For more usage examples, see the tests.

react-native-cache's People

Contributors

bnap00 avatar darkmattermatt avatar dependabot[bot] avatar eubnara avatar johnmarinelli avatar slavikdenis avatar timfpark avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-cache's Issues

is it possible to find cache in another page?

i setted cache in a page, and want to get it from another page with getCache and the same namespace, it does'nt work, i tried aloso to pass cache object to my new page, but not working. thanks for help.

about clearAll function

your [clearAll] function is remove all [AsyncStorage] items,but i want remove cache items only specified by namespace when call the [clearAll] function. Can you provide the this function ?

在使用 react-native-cache 的时候,调用 clearAll 方法会删除所有存储在 AsyncStorage 中的数据。但我认为,只应该删除当前指定命名空间的缓存数据。您能修改一下吗?

Can we clear default cache from this library

Hi,
I just need to know can we clear default cache data by using

cache.clearAll(function(err) {
    // the whole cache is cleared now.
});

As an example, some of my image URLs already saved in the cache. So I need to clear those. But I'm not saving any of the data to the cache by using this library.

Create policy based on size

Constrains in mobile phones are mostly related to storage. Discuss Create policy based on size X bytes (GB, MB, KB) ...

Allow passing callback to remove

I am using this package along with react-native-cached-image. I would like to clean up actual files from filesystem when LRU auto-pruning is triggered.

Can we provide a callback that gets invoked immediately after the cache is pruned? The callback function should receive keys that were removed during pruning.

stdTTL not working for release builds (console.dir undefined)

While implementing the stdTTL feature to remove cached entries after expiration, I noticed that entries were successfully removed for debug builds, but not release builds.

The error logged was: console.dir is not a function. (In 'console.dir(Date.parse(c.created))', 'console.dir' is undefined). I traced this to the following code block within the peek function in dist/cache.js:

if (this.policy.stdTTL > 0) { console.dir(Date.parse(entry.created));

It appears that this could have been added to the dist folder before the version 2.0.2 release since it's not in the repository and was accidentally left in. Console.dir is problematic for iOS and Android (facebook/react-native#29300).

Could this be removed with another release please? I'd open a PR if it was included with the repo code.

Namespaced getAll

getAll is not using the namespace of the Cache instance. It is a problem for me because I am using several instances at the same time and at some point I need all the cache elements of only one instance.

I want to make a PR but I want to know if I need to preserve the current behavior with some sort of parameter like "namespaceRestriction".

Misalignment on release 2.0.1

I think there is a misalignment between the release version 2.0.1 on npm and the one on github.

On npm is missing the new feature of "ttl" policy. As I can see the latest commit is missing.

Cheers.

[Question] How to access cache from any view?

Hello,

I am having issues accessing the cache I saved away from the view where it was saved.
Example:

Main Screen:

var cache = new Cache({
  namespace: "MainCache",
  policy: {
    maxEntries: 50000
  },
  backend: AsyncStorage
});

cache.getAll(function (err, data) {
  console.log(err + " HERE IS THE LOG: " + Object.values(data).length)
}

The above consoles out:

null HERE IS THE LOG 0

Secondary Screen where I saved the cache:

var cache = new Cache({
  namespace: "MainCache",
  policy: {
    maxEntries: 50000
  },
  backend: AsyncStorage
});

cache.getAll(function (err, data) {
  console.log(err + " HERE IS THE LOG: " + Object.values(data).length)
}

The above consoles out:

null HERE IS THE LOG 1

I am trying to access the cache I can access on the secondary screen on my main screen once it is saved.

I saw the closed issue - but it didn't really offer any insight to this? Any idea what could be going wrong here? Or if I am doing something wrong?

Thanks in advance

Add Expiration

It would be amazing if cache-entries expire automatically after a specified duration.

Max Entries in Policy Mis-documented?

The README says "if unspecified, it can have unlimited entries" for ICachePolicy's maxEntries property. But in the TS declaration file, this value is required.

maxEntried and or enforceLimit does not seem to work.

Hello, I have setup my cache as such
new Cache({ namespace: 'ImageTypeCahe', policy: { maxEntries: 3, // if unspecified, it can have unlimited entries }, backend: AsyncStorage, });

But I can add 5 items to the cache. Calling cache.enforceLimit() doesn't seem to do anything. Still have 5 items after that. What am I missing?

Thank you!

Get data from result returned

Hi all,
I wrote those lines of code,

var res = {};
    await this.cache.getItem(cachedObjKey, function(err, value) {
      console.log(err, value);
      res = {...value};
    });

One thing here is how could I get "res" from outside getItem function? If I log res outside function, it will be just {} ?
Need helps. Many thanks.

[Question] Interface for backend?

I'm wondering why the ICacheOptions.backend is any type. The comment says:

// backend is expected to have the same static interface as AsyncStorage

Why not use an interface that matches AsyncStorage? Of course, this does require tracking changes in AsyncStorage, but maybe that's happening already?

export interface IBackend {
  /**
   * Fetches key and passes the result to callback, along with an Error if there is any.
   */
  getItem(key: string, callback?: (error?: Error, result?: string) => void): Promise<string | null>;

  /**
   * Sets value for key and calls callback on completion, along with an Error if there is any
   */
  setItem(key: string, value: string, callback?: (error?: Error) => void): Promise<void>;

  removeItem(key: string, callback?: (error?: Error) => void): Promise<void>;

  /**
   * Merges existing value with input value, assuming they are stringified json. Returns a Promise object.
   * Not supported by all native implementation
   */
  mergeItem(key: string, value: string, callback?: (error?: Error) => void): Promise<void>;

  /**
   * Erases all AsyncStorage for all clients, libraries, etc. You probably don't want to call this.
   * Use removeItem or multiRemove to clear only your own keys instead.
   */
  clear(callback?: (error?: Error) => void): Promise<void>;

  /**
   * Gets all keys known to the app, for all callers, libraries, etc
   */
  getAllKeys(callback?: (error?: Error, keys?: string[]) => void): Promise<string[]>;

  /**
   * multiGet invokes callback with an array of key-value pair arrays that matches the input format of multiSet
   */
  multiGet(
    keys: string[],
    callback?: (errors?: Error[], result?: [string, string | null][]) => void
  ): Promise<[string, string | null][]>;

  /**
   * multiSet and multiMerge take arrays of key-value array pairs that match the output of multiGet,
   *
   * multiSet([['k1', 'val1'], ['k2', 'val2']], cb);
   */
  multiSet(keyValuePairs: string[][], callback?: (errors?: Error[]) => void): Promise<void>;

  /**
   * Delete all the keys in the keys array.
   */
  multiRemove(keys: string[], callback?: (errors?: Error[]) => void): Promise<void>;

  /**
   * Merges existing values with input values, assuming they are stringified json.
   * Returns a Promise object.
   *
   * Not supported by all native implementations.
   */
  multiMerge(keyValuePairs: string[][], callback?: (errors?: Error[]) => void): Promise<void>;
}

export interface ICacheOptions {
    backend: IBackend;
    namespace: string;
    policy: ICachePolicy;
}

[Question] Performance benchmarks

Hello I would like to ask you if there are some performance benchmarks to make it easier for new users to decide if and why they should use this package. Thank you so much!

getAll()

Hi, @timfpark,

Could you please add support for obtaining all currently stored objects (aka getAll() method)?

Async/Await compatibility

Please use promises or async/await instead of callbacks, to make the Api much more convenient.

Thanks :-)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.