GithubHelp home page GithubHelp logo

urbiwanus / ionic-cache Goto Github PK

View Code? Open in Web Editor NEW

This project forked from nodonisko/ionic-cache

0.0 2.0 0.0 37 KB

Ionic 2 and Angular 2 cache service with WebSQL support

License: MIT License

TypeScript 100.00%

ionic-cache's Introduction

Ionic cache service

Ionic cache service that can cache almost everything. It caches request, observables, promises and classic data. It uses WebSQL or SQLite as storage and work well with Observables. With few little changes it can be used separatelety in Angular 2 application.

Key features:

  • Request caching
  • Delayed observable caching (see docs for more info)
  • Don't invalidate cache if is browser offline
  • Set and invalidate groups of entries

TO DO:

  • Add cordova-sqlite-storage plugin support again

Please report all bugs to bug report or fix it, or better fix it and send pull request :)

Contributors

Big thanks to all contributors for help. Currently only one Vojta Tranta, but I hope there will be more names in future :)

Install

Via NPM:

npm install ionic-cache --save

And inject service to your app:

app.module.ts

import {CacheService} from "ionic-cache/ionic-cache";

@NgModule({
  ...
  bootstrap: [IonicApp],
  entryComponents: [
    MyApp,
    AboutPage
  ],
  providers: [CacheService],
})

app.component.ts

import {CacheService} from "ionic-cache/ionic-cache";

@App({
    templateUrl: "build/app.html"
})
class MyApp {
    constructor(cache: CacheService) {
        ...
        this.cache.setDefaultTTL(60 * 60); //set default cache TTL for 1 hour
        ....
    }
    ...
}

Usage

Cache request

...
import {CacheService} from "ionic-cache/ionic-cache";

@Injectable()
export class SomeProvider {
    constructor(http: Http, cache: CacheService) {
        this.http = http;
        this.cache = cache;
    }

    loadList() {
        let url = "http://ip.jsontest.com";
        let cacheKey = url;
        let request = this.http.get(url).map(res => res.json());

        return this.cache.loadFromObservable(cacheKey, request);
    }
    ...

Cache whole request response

Sometimes you need to cache whole response, if you need to look to Headers etc. It can be done only with simple move .map(res => res.json()) after loadFromObservable method. loadFromObservable returns Observable, so you can also use other Observable operators.

...
let request = this.http.get(url);
return this.cache.loadFromObservable(cacheKey, request).map(res => res.json());
...

Cache classic data (arrays, objects, strings, numbers etc.)

Cache service works well with observables, but you can cache classic data as well.

...
let key = 'heavily-calculated-function';

this.cache.getItem(key).catch(() => {
    // fall here if item is expired or doesn't exist
    let result = heavilyCalculatedFunction();
    return this.cache.saveItem(key, result);
}).then((data) => {
    console.log("Saved data: ", data);
});
...

Cache promises

...
let key = 'some-promise';

this.cache.getItem(key).catch(() => {
    // fall here if item is expired or doesn't exist
    return somePromiseFunction().then(result => {
        return this.cache.saveItem(key, result);
    });
}).then((data) => {
    console.log("Saved data: ", data);
});
...

Cache with custom Observable operators

loadFromObservable method using Observable and return Observable, so you are free to use all Observable operators. For example error handling (on error, retry request every 6 seconds if fails):

...
let request = this.http.get(url)
                    .retryWhen((error) => {
                        return error.timer(6000);
                    }).map(res => res.json());
return this.cache.loadFromObservable(cacheKey, request);
...

Cache entries grouping

Sometimes you need to invalidate only some group of cache entries. For example if you have have long infinite scroll with lots of pages, and user trigger pull to request you want to delete all cache entries for all pages. So this is time for third parameter.

...
loadList(pageNumber) {
    let url = "http://google.com/?page=" + pageNumber;
    let cacheKey = url;
    let groupKey = "googleSearchPages"

    let request = this.http.get(url).map(res => res.json());
    return this.cache.loadFromObservable(cacheKey, request, groupKey);
}
...

And when pull to refresh is fired, delete all cache entries in group googleListPages:

...
pullToRefresh() {
    this.cache.clearGroup("googleSearchPages");
}
...

Delayed observable caching

Features that using full power of observables. When you call this method and it will return data from cache (even if they are expired) and immediately send request to server and return new data after request successfuly finish. See example for more details:

...
    let request = this.http.get(url).map(res => res.json());
    let delayType = 'all'; // send new request to server everytime, if it's set to none it will send new request only when entry is expired
    let response = this.cache.loadFromDelayedObservable(cacheKey, request, groupKey, ttl, delayType);

    response.subscribe(data => {
        console.log("Data:" data);
    });

    //result will look like this:
    // Data: "Hello world from cache"
    // Data: "Hello world from server"
...

Set custom TTL for single request

If you want custom TTL for single request, it can by easily done by third parameter.

let ttl = 60 * 60 * 24 * 7; // TTL in seconds for one week
let request = this.http.get(url).map(res => res.json());

return this.cache.loadFromObservable(cacheKey, request, groupKey, ttl);

Set default TTL

this.cache.setDefaultTTL(60 * 60); //set default cache TTL for 1 hour

Delete expired entries

It's automatically done on every startup, but you can do it manually.

this.cache.clearExpired();

Delete all entries

this.cache.clearAll();

Disable cache

You can disable cache without any worrying, it will pass origin Observable through and all Promises will be rejected. Without any errors.

this.cache.disableCache(true);

Disable offline invalidate

If you want disable "don't invalidate" when device is offline, you can do it simply.

this.cache.setOfflineInvalidate(false);

ionic-cache's People

Contributors

aemr3 avatar imatefx avatar nodonisko avatar vojtatranta avatar

Watchers

 avatar  avatar

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.