Huge News!Announcing our $40M Series B led by Abstract Ventures.Learn More
Socket
Sign inDemoInstall
Socket

apollo-cache-persist

Package Overview
Dependencies
Maintainers
3
Versions
8
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

apollo-cache-persist - npm Package Compare versions

Comparing version 0.0.2-beta.0 to 0.0.2-beta.1

13

bundle.umd.js

@@ -194,8 +194,9 @@ (function (global, factory) {

var Persistor = (function () {
function Persistor(_a, _b) {
function Persistor(_a, options) {
var log = _a.log, cache = _a.cache, storage = _a.storage;
var maxSize = _b.maxSize;
var _b = options.maxSize, maxSize = _b === void 0 ? 1024 * 1024 : _b;
this.log = log;
this.cache = cache;
this.storage = storage;
this.paused = false;
if (maxSize) {

@@ -213,4 +214,6 @@ this.maxSize = maxSize;

data = this.cache.extract();
if (!(typeof data === 'string')) return [3, 2];
if (!(data.length > this.maxSize && !this.paused)) return [3, 2];
if (!(this.maxSize != null &&
typeof data === 'string' &&
data.length > this.maxSize &&
!this.paused)) return [3, 2];
return [4, this.purge()];

@@ -347,2 +350,3 @@ case 1:

}
this.debounce = debounce != null ? debounce : defaultDebounce;
this.persistor = persistor;

@@ -352,3 +356,2 @@ this.paused = false;

case 'write':
this.debounce = debounce || defaultDebounce;
this.uninstall = onCacheWrite({ cache: cache })(this.fire);

@@ -355,0 +358,0 @@ break;

{
"name": "apollo-cache-persist",
"version": "0.0.2-beta.0",
"version": "0.0.2-beta.1",
"description": "Simple persistence for all Apollo cache implementations",

@@ -11,3 +11,3 @@ "author": "James Reggio <james.reggio@gmail.com>",

"license": "MIT",
"main": "apollo-cache-persist.umd.js",
"main": "bundle.umd.js",
"module": "index.js",

@@ -46,4 +46,3 @@ "jsnext:main": "index.js",

"uglify-js": "^3.2.2"
},
"browser": "apollo-cache-persist.browser.umd.js"
}
}

@@ -16,3 +16,3 @@ import Log from './Log';

paused: boolean;
constructor({log, cache, storage}: PersistorConfig<T>, {maxSize}: ApolloPersistOptions<T>);
constructor({log, cache, storage}: PersistorConfig<T>, options: ApolloPersistOptions<T>);
persist(): Promise<void>;

@@ -19,0 +19,0 @@ restore(): Promise<void>;

@@ -37,8 +37,9 @@ var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {

var Persistor = (function () {
function Persistor(_a, _b) {
function Persistor(_a, options) {
var log = _a.log, cache = _a.cache, storage = _a.storage;
var maxSize = _b.maxSize;
var _b = options.maxSize, maxSize = _b === void 0 ? 1024 * 1024 : _b;
this.log = log;
this.cache = cache;
this.storage = storage;
this.paused = false;
if (maxSize) {

@@ -56,4 +57,6 @@ this.maxSize = maxSize;

data = this.cache.extract();
if (!(typeof data === 'string')) return [3, 2];
if (!(data.length > this.maxSize && !this.paused)) return [3, 2];
if (!(this.maxSize != null &&
typeof data === 'string' &&
data.length > this.maxSize &&
!this.paused)) return [3, 2];
return [4, this.purge()];

@@ -60,0 +63,0 @@ case 1:

@@ -6,4 +6,4 @@ # apollo-cache-persist

Simple persistence for all Apollo Cache 2.0+ implementations, including
[`apollo-cache-inmemory`][0] and [`apollo-cache-hermes`][1].
Simple persistence for all Apollo Client 2.0 cache implementations, including
[`InMemoryCache`][0] and [`Hermes`][1].

@@ -17,6 +17,6 @@ Supports web and React Native. [See all storage providers.](#storage-providers)

To get started, simply pass your Apollo Cache and an
To get started, simply pass your Apollo cache and an
[underlying storage provider](#storage-providers) to `persistCache`.
By default, the contents of your Apollo Cache will be immediately restored
By default, the contents of your Apollo cache will be immediately restored
(asynchronously), and will be persisted upon every write to the cache (with a

@@ -65,41 +65,52 @@ short debounce interval).

```js
```ts
persistCache({
/**
* Required
* Required options.
*/
cache, // Reference to your Apollo Cache.
storage, // Reference to your storage provider.
// Reference to your Apollo cache.
cache: ApolloCache<TSerialized>,
// Reference to your storage provider.
storage: PersistentStorage<TPersisted>,
/**
* Trigger options
* Trigger options.
*/
trigger: 'write', // Persist upon every write to the store. Default.
trigger: 'background', // Persist when your app moves to the background. React Native only.
// When to persist the cache.
//
// 'write': Persist upon every write to the cache. Default.
// 'background': Persist when your app moves to the background. React Native only.
//
// For a custom trigger, provide a function. See below for more information.
// To disable automatic persistence and manage persistence manually, provide false.
trigger?: 'write' | 'background' | function | false,
// Debounce interval (in ms) between persists.
// Defaults to 1000 for 'write' and 0 for 'background'.
debounce: 1000,
// Debounce interval between persists (in ms).
// Defaults to 0 for 'background' and 1000 for 'write' and custom triggers.
debounce?: number,
/**
* Storage options
* Storage options.
*/
// Key to use with the storage provider.
key: 'apollo-cache-persist',
// Key to use with the storage provider. Defaults to 'apollo-cache-persist'.
key?: string,
// Whether to JSON serialize before/after persisting.
serialize: true,
// Whether to serialize to JSON before/after persisting. Defaults to true.
serialize?: boolean,
// Maximum size of cache to persist (in bytes).
// Defaults to 1048576 (1 MB). For unlimited cache size, provide false.
// If exceeded, persistence will pause and app will start up cold on next launch.
maxSize?: number | false,
/**
* Miscellaneous
* Debugging options.
*/
// Purges storage & pauses persistence if trigger causes cache size to pass a threshold (in bytes). App will start up cold.
maxSize?: number,
// Enable console logging.
debug: false,
debug?: boolean,
});

@@ -110,2 +121,4 @@ ```

### Using `CachePersistor`
Instead of using `persistCache`, you can instantiate a `CachePersistor`, which

@@ -130,3 +143,2 @@ will give you fine-grained control of persistence.

// `print: true` will print them to the console; `false` will return an array.
persistor.getLogs(print);

@@ -136,6 +148,33 @@

// Resolves to 0 for empty and `null` when `serialize: true` is in use.
persistor.getSize();
```
### Custom Triggers
For control over persistence timing, provide a function to the `trigger` option.
The custom trigger should accept one argument (a `persist` callback function),
and it should return a function that can be called to uninstall the trigger.
The TypeScript signature for this function is as follows:
```ts
(persist: () => void) => (() => void)
```
For example, this custom trigger will persist every 10 seconds:
```js
// This code is for illustration only.
// We do not recommend persisting on an interval.
const trigger = persist => {
// Call `persist` every 10 seconds.
const interval = setInterval(persist, 10000);
// Return function to uninstall this custom trigger.
return () => clearInterval(interval);
};
```
## Storage Providers

@@ -153,3 +192,5 @@

[`redux-persist`](https://github.com/rt2zz/redux-persist), so you can also make
use of the providers [listed here](#storage-providers), including:
use of the providers
[listed here](https://github.com/rt2zz/redux-persist#storage-engines),
including:

@@ -159,1 +200,113 @@ * [`redux-persist-node-storage`](https://github.com/pellejacobs/redux-persist-node-storage)

* [`redux-persist-cookie-storage`](https://github.com/abersager/redux-persist-cookie-storage)
If you're using React Native and set a `maxSize` in excess of 2 MB, you must use
a filesystem-based storage provider, such as
[`redux-persist-fs-storage`](https://github.com/leethree/redux-persist-fs-storage).
`AsyncStorage`
[does not support](https://github.com/facebook/react-native/issues/12529#issuecomment-345326643)
individual values in exceed of 2 MB on Android.
## Common Questions
#### Why is the 'background' trigger only available for React Native?
Quite simply, because mobile apps are different than web apps.
Mobile apps are rarely terminated before transitioning to the background. This
is helped by the fact that an app is moved to the background whenever the user
returns home, activates the multitasking view, or follows a link to another app.
There's almost always an opportunity to persist.
On web, we _could_ support a 'background' trigger with the
[Page Visibility API](https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API);
however, data would be lost if the user closed the tab/window directly. Given
this prevalence of this user behavior and the substantially better performance
of the 'write' trigger on web, we've omitted a 'background' trigger on web.
#### I need to ensure certain data is not persisted. How do I filter my cache?
Unfortunately, this is not yet possible. You can only persist and restore the
cache in its entirety.
This library depends upon the `extract` and `persist` methods defined upon the
cache interface in Apollo Client 2.0. The payload returned and consumed by these
methods is opaque and differs from cache to cache. As such, we cannot reliably
transform the output.
Alternatives have been recommended in
[#2](https://github.com/apollographql/apollo-cache-persist/issues/2#issuecomment-350823835),
including using logic in your UI to filter potentially-outdated information.
Furthermore, the [`maxSize` option](#additional-options) and
[methods on `CachePersistor`](#using-cachepersistor) provide facilities to
manage the growth of the cache.
For total control over the cache contents, you can setup a background task to
periodically reset the cache to contain only your app’s most important data. (On
the web, you can use a service worker; on React Native, there’s
[`react-native-background-task`](https://github.com/jamesisaac/react-native-background-task).)
The background task would start with an empty cache, query the most important
data from your GraphQL API, and then persist. This strategy has the added
benefit of ensuring the cache is loaded with fresh data when your app launches.
Finally, it's worth mentioning that the Apollo community is in the early stages
of designing fine-grained cache controls, including the ability to utilize
directives and metadata to control cache policy on a per-key basis, so the
answer to this question will eventually change.
#### I've had a breaking schema change. How do I migrate or purge my cache?
For the same reasons given in the preceding answer, it's not possible to migrate
or transform your persisted cache data. However, by using the
[methods on `CachePersistor`](#using-cachepersistor), it's simple to reset the
cache upon changes to the schema.
Simply instantiate a `CachePersistor` and only call `restore()` if the app's
schema hasn't change. (You'll need to track your schema version yourself.)
Here's an example of how this could look:
```js
import { AsyncStorage } from 'react-native';
import { InMemoryCache } from 'apollo-cache-inmemory';
import { CachePersistor } from 'apollo-cache-persist';
const SCHEMA_VERSION = '3'; // Must be a string.
const SCHEMA_VERSION_KEY = 'apollo-schema-version';
async function setupApollo() {
const cache = new InMemoryCache({...});
const persistor = new CachePersistor({
cache,
storage: AsyncStorage,
});
// Read the current schema version from AsyncStorage.
const currentVersion = await AsyncStorage.getItem(SCHEMA_VERSION_KEY);
if (currentVersion === SCHEMA_VERSION) {
// If the current version matches the latest version,
// we're good to go and can restore the cache.
await persistor.restore();
} else {
// Otherwise, we'll want to purge the outdated persisted cache
// and mark ourselves as having updated to the latest version.
await persistor.purge();
await AsyncStorage.setItem(SCHEMA_VERSION_KEY, SCHEMA_VERSION);
}
// Continue setting up Apollo as usual.
}
```
#### I'm seeing errors on Android.
Specifically, this error:
```
BaseError: Couldn't read row 0, col 0 from CursorWindow. Make sure the Cursor is initialized correctly before accessing data from it.
```
This is the result of a 2 MB limitation of `AsyncStorage` on Android. Set a
smaller `maxSize` or switch to a filesystem-based storage provider, such as
[`redux-persist-fs-storage`](https://github.com/leethree/redux-persist-fs-storage).

@@ -28,2 +28,3 @@ import onCacheWrite from './onCacheWrite';

}
this.debounce = debounce != null ? debounce : defaultDebounce;
this.persistor = persistor;

@@ -33,3 +34,2 @@ this.paused = false;

case 'write':
this.debounce = debounce || defaultDebounce;
this.uninstall = onCacheWrite({ cache: cache })(this.fire);

@@ -36,0 +36,0 @@ break;

@@ -15,8 +15,8 @@ import { ApolloCache } from 'apollo-cache';

storage: PersistentStorage<PersistedData<TSerialized>>;
trigger?: 'write' | 'background' | TriggerFunction;
trigger?: 'write' | 'background' | TriggerFunction | false;
debounce?: number;
key?: string;
serialize?: boolean;
maxSize?: number | false;
debug?: boolean;
maxSize?: number;
}

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

Sorry, the diff of this file is not supported yet

SocketSocket SOC 2 Logo

Product

  • Package Alerts
  • Integrations
  • Docs
  • Pricing
  • FAQ
  • Roadmap
  • Changelog

Packages

npm

Stay in touch

Get open source security insights delivered straight into your inbox.


  • Terms
  • Privacy
  • Security

Made with ⚡️ by Socket Inc