npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ionic-cache-http-common

v1.2.0

Published

Ionic cache service forked from ionic-cache - optimized to work with @angular/common/http first, falling back to @angular/http last, as opposite as in the original

Downloads

4

Readme

This is a fork of https://github.com/Nodonisko/ionic-cache to fix a bug with await async requiring @angular/http (deprecated) to be installed at build time first, and then not taking the up-to-date @angular/common/http library instead and not working as intended

Ionic cache service

Ionic cache service that can cache almost everything. It caches requests, observables, promises and classic data. It uses Ionic Storage so we support IndexedDB, SQLite (Cordova), WebSQL in this order. It can be used separatelety in Angular up to 5+ 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
  • Supports IndexedDB, SQLite (Cordova), WebSQL via Ionic Storage

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

Big thanks to the author!:

Big thanks to all contributors for help:

Install

Via NPM:

npm install ionic-cache-http-common @ionic/storage --save

or Yarn:

yarn add ionic-cache-http-common @ionic/storage

You can optionally add Cordova SQLite.

And inject service to your app:

app.module.ts

import { CacheModule } from "ionic-cache";

@NgModule({
  ...
  imports: [
    CacheModule.forRoot()
  ],
})

app.component.ts

import { CacheService } from "ionic-cache";

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

Usage

Cache request

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

@Injectable()
export class SomeProvider {
    constructor(private http: Http, private cache: CacheService) {}

    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.enableCache(false);

Disable offline invalidate

If you want disable invalidate when device is offline, you can do it simply.

this.cache.setOfflineInvalidate(false);