How to use the apollo-cache-persist.CachePersistor function in apollo-cache-persist

To help you get started, we’ve selected a few apollo-cache-persist examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github cloudkeeper-io / cloudkeeper-ui / src / configs / apollo.config.ts View on Github external
export const getApolloClient = (getIdToken: () => Promise) => {
  const cache = new InMemoryCache()

  const persistor = new CachePersistor({
    cache,
    storage: window.localStorage as any,
    maxSize: 4.5 * 1024 * 1024,
  })

  const lastPurge = localStorage.getItem(PERSIST_LAST_PURGE_KEY)
  if (!lastPurge || Number(lastPurge) < Date.now() - PERSIST_TTL) {
    localStorage.setItem(PERSIST_LAST_PURGE_KEY, String(Date.now()))
    persistor
      .purge()
      // eslint-disable-next-line no-console
      .catch((err) => console.log(`Cache purge error: ${err}`))
  } else {
    persistor
      .restore()
      // eslint-disable-next-line no-console
github rkclark / pullp / src / components / App / index.js View on Github external
),
            );
          if (networkError) console.log(`[Network error]: ${networkError}`);
        }),
        stateLink,
        authLink,
        new HttpLink({
          uri: process.env.REACT_APP_GITHUB_API_URL,
          credentials: 'same-origin',
        }),
      ]),
      cache: apolloCache,
    });

    try {
      const persistor = new CachePersistor({
        cache: apolloCache,
        storage: window.localStorage,
        debug: true,
        maxSize: 2097152, // 2mb
      });

      const currentVersion = await window.localStorage.getItem(
        SCHEMA_VERSION_KEY,
      );

      if (
        currentVersion &&
        currentVersion.toString() === SCHEMA_VERSION.toString()
      ) {
        // If the current version matches the latest version,
        // we're good to go and can restore the cache.
github cloudkeeper-io / cloudkeeper-ui / src / configs / apollo.config.ts View on Github external
export const getApolloClient = (getIdToken: () => Promise) => {
  const cache = new InMemoryCache()

  const persistor = new CachePersistor({
    cache,
    storage: window.localStorage as any,
    maxSize: 4.5 * 1024 * 1024,
  })

  const lastPurge = localStorage.getItem(PERSIST_LAST_PURGE_KEY)
  if (!lastPurge || Number(lastPurge) < Date.now() - PERSIST_TTL) {
    localStorage.setItem(PERSIST_LAST_PURGE_KEY, String(Date.now()))
    persistor
      .purge()
      // eslint-disable-next-line no-console
      .catch((err) => console.log(`Cache purge error: ${err}`))
  } else {
    persistor
      .restore()
      // eslint-disable-next-line no-console
github demokratie-live / democracy-client / src / graphql / client.js View on Github external
let client; // eslint-disable-line

const cache = new InMemoryCache({
  dataIdFromObject: o => {
    switch (o.__typename) {
      case 'Procedure':
        return o.procedureId;

      default:
        return o._id;
    }
  },
});

const persistor = new CachePersistor({
  cache,
  storage: AsyncStorage,
  debug: false,
  debounce: 1000,
  // maxSize: false
});

const authLinkMiddleware = setContext(async (_, { headers }) => {
  // get the authentication token from local storage if it exists
  const token = await AsyncStorage.getItem('auth_token');
  const refreshToken = await AsyncStorage.getItem('auth_refreshToken');

  if (token && refreshToken) {
    const decodedToken = jwtDecode(token);
    const decodedRefreshToken = jwtDecode(refreshToken);
github devinit / datahub / src / apollo / index.tsx View on Github external
const persist = async () => {
  const persistor = new CachePersistor({
    cache: cache(),
    storage: localforage as any
  });
  // Read the current schema version from AsyncStorage.
  const currentVersion = await localforage.getItem(SCHEMA_VERSION_KEY);

  if (APP_VERSION === currentVersion) {
    // 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 localforage.setItem(SCHEMA_VERSION_KEY, APP_VERSION);
  }
github ahmedlhanafy / guchub / src / utils / setupApollo.js View on Github external
/* @flow */

import { AsyncStorage, Platform } from 'react-native';
import { ApolloClient } from 'apollo-client';
import { HttpLink, InMemoryCache, ApolloLink } from 'apollo-client-preset';
import { CachePersistor } from 'apollo-cache-persist';
import { generateClientStateLink, getSchemaVersion, saveSchemaVersion } from './';
import packageJson from '../../package.json';

const currentSchemaVersion = packageJson.schema_version;

const cache = new InMemoryCache();

const persistor = new CachePersistor({
  cache,
  storage: AsyncStorage,
  trigger: Platform.OS === 'web' ? 'write' : 'background',
});

export default async () => {
  const cacheSchemaVersion = (await getSchemaVersion()) || 0;
  if (currentSchemaVersion === cacheSchemaVersion) {
    await persistor.restore();
  } else {
    await persistor.purge();
    await saveSchemaVersion(currentSchemaVersion);
  }

  const clientStateLink = await generateClientStateLink(cache);
  return new ApolloClient({
github bastiRe / eLadder / app / createApolloClient.js View on Github external
return null;
      }
    }
  },
  defaults: {
    leagueIds: []
  }
});

export const client = new ApolloClient({
  link: ApolloLink.from([errorLink, authLink, stateLink, httpLink]),
  cache
});

// needs to be declared after client otherwise there might be problems with defaults
export const persistor = new CachePersistor({
  storage: AsyncStorage,
  cache,
  debug: true
});
github open-app / app-hub-mobile / src / utils / ApolloWrapper.js View on Github external
async function getApolloClient() {
  const cache = new InMemoryCache()
  const persistor = new CachePersistor({
    cache,
    storage: AsyncStorage,
    trigger: 'background',
  })
  try {
    const currentVersion = await AsyncStorage.getItem(SCHEMA_VERSION_KEY)
    if (currentVersion === SCHEMA_VERSION) {
      console.log('Restoring cache')
      await persistor.restore()
    } else {
      console.log('Creating cache')
      await persistor.purge()
      await AsyncStorage.setItem(SCHEMA_VERSION_KEY, SCHEMA_VERSION)
    }
  } catch (error) {
    console.log('ERROR on cache', error)
github aerogear / offix / packages / offix-client / src / ApolloOfflineClient.ts View on Github external
constructor(options: ApolloOfflineClientOptions) {
    const config = new ApolloOfflineClientConfig(options);
    super(config);

    this.initialized = false;
    this.mutationCacheUpdates = config.mutationCacheUpdates;
    this.conflictProvider = config.conflictProvider;

    if (config.cachePersistor) {
      if (!(config.cachePersistor instanceof CachePersistor)) {
        throw new Error("Error: options.cachePersistor is not a CachePersistor instance");
      }
      this.persistor = config.cachePersistor;
    } else {
      this.persistor = new CachePersistor({
        cache: this.cache,
        serialize: false,
        storage: config.cacheStorage,
        maxSize: false,
        debug: false
      });
    }

    this.scheduler = new OffixScheduler({
      executor: this,
      storage: config.offlineStorage,
      networkStatus: config.networkStatus,
      serializer: ApolloOperationSerializer,
      offlineQueueListener: config.offlineQueueListener
    });

apollo-cache-persist

Simple persistence for all Apollo cache implementations

MIT
Latest version published 7 years ago

Package Health Score

62 / 100
Full package analysis

Similar packages