Git Product home page Git Product logo

angular-caching's Introduction

Hi there ๐Ÿ‘‹

I'm Ezz abuzaid a Computer Engineer by specialization, Software Engineer by profession, and an Engineer at heart.

Nowadays, I mainly code TypeScript and used to do C# and Dart. I love working with new languages and technologies wherever an opportunity presents itself.

I love writing and have in-depth disucssions, my ultimate goal beside programming to be A Dev Journalist.

Sharing knowledge is a passion of mine, I do this by writing blog posts and helping newbies.

Technical Articles

Workshops

Trivia

  • ๐Ÿ”ญ I'm working as Software Engineer @Equiti Group
  • ๐Ÿงฌ I read about compilers occasionally.
  • ๐ŸŒฑ Currently building Tiny Injector and SQL Tooling
  • ๐Ÿ“š Currently reading Design for Developers
  • ๐Ÿ‘ฏ Ready to collaborate on open sourceopen-source๐Ÿ’ฌ Here to answer your questions about Web/Mobile Development

Open Source Projects

Project Description
SQL Tooling Simple SQLite Parser Done In TypeScript
Tiny Injector Mix of .NetCore and Angular dependency injection
RFC 7807 Typescript implementation of RFC 7807
Fayona .NetCore like framework using Node.js
Ngx-Request-Options Angular package that make passing properties to interceptors possible
Ngx-Form-Factory Angular package to build complex forms without the need to write any markup boilerplate
Document Storage JavaScript package that provides a unified interface for browser storages
Flutter Form Validators A set of predefined validators that makes field validation straightforward
C# class to ProtoBuf If you're moving from Monolithic to Microservices, you need to convert your models
Docker Compose Environment Variable To JSON Converting docker-compose environment varaibles To JSON

My older Technical Articles you might read

๐Ÿ“ซ Where to find me

angular-caching's People

Contributors

ezzabuzaid avatar

Stargazers

 avatar

Watchers

 avatar

angular-caching's Issues

Implement caching strategies

  1. Cache First (Cache Falling Back to Network)
  2. Network First (Network Falling Back to Cache)
  3. Network Only
  4. Cache Only
  5. Stale-While-Revalidate

Part 1 Update.

Angular API Caching

Update (Date Here): change the implementation to use localForage library.

This article will take you through the way to efficiently handle the HTTP client request and cache them inside different browser storage.

For clarity about what Iโ€™m going to talk about, the full project is available to browse through Github.

What Is Caching

Caching is a way to store data that is often in use (HTTP response in our case) in storage to quickly access it later on. So instead of asking for the same data twice, you store a copy of it, and later on, you got that copy instead of the original.

How It Works

  1. A request made to server X to get data Y.
  2. The request goes through the cache to check if there's a copy from point 4.
  3. No copy found so the request will be delegated to the actual server. otherwise, jump to point 5.
  4. The server returned data Y and pass a copy through the cache.
  5. The request initiator gets the data to deal with it.
  6. Data will remain in cache till it expires or the cache is cleared.

That is the basic flow of how cache works.

There're many advantages of caching in general so I'll just point out some of what the Front End interested in

When/Why To Use Cache

  • Reduce the number of requests.
  • Store response that doesn't frequently change.
  • Request that the application addressing frequently.
  • Improve responsiveness by retrieving the response immediately.
  • Show some content while you requesting the fresh content.
  • Show some data while there's no internet connection to provide an offline experience

And of course, there might be other use cases depends on your custom usage.

Where To Store The Cache Data

  1. LocalStorage
  2. SessionStorage
  3. IndexedDB
  4. WebSql
  5. Cache API
  6. Cookie
  7. And InMemory ๐Ÿ˜

We will use localForage library that acts as one interface for most of the mentioned storages, of course, you can use whatever you see suitable.

you can install from here npm install localforage

Example Usage

import { Injectable } from '@angular/core';
import { HttpClient, HttpResponse } from '@angular/common/http';

@Injectable()
export class ExampleService {

    constructor(
        private httpClient: HttpClient,
    ) { }

    getData() {
        const url = '/endpoint-url';
        return this.httpClient.get(url);
    }

}

Sample showing an example service that gets data from a server

import * as localforage from 'localforage';
const store = localforage.createInstance({
    driver: localforage.INDEXEDDB, /** Here where you can change the storage */
    version: 1.0,
    storeName: 'cache',
});

Configure a store, I'm using IndexedDB but feel free to use anything else.


Going back to the start.

  1. Initiate a request to server X to get data Y. (the request initiator is getData method )
  2. The request goes through the cache to check if there's a copy from point 4.
  3. No copy found so the request will be delegated to the actual server. otherwise, jump to point 5.
  4. The server returned data Y and pass a copy through the cache.
  5. The request initiator gets the data to deal with it.
  6. Data will remain in cache till it expires or the cache is cleared.
getData() {
    const url = 'https://jsonplaceholder.typicode.com/todos/1';
    return defer(() => store.getItem(url) /** step 2 */)
        .pipe(switchMap((cachedData) => {
            if (cachedData === null || cachedData === undefined) { /** step 3 */
                return this.httpClient.get(url) /** step 1 */
                    .pipe(switchMap((newData) => store.setItem(url, newData)));
            }
            return of(cachedData); /** step 5 */
        }))
}

defer used to create an Observable from Promise.

More about caching.

Caching Strategy

You might not want always to return the data from the cache perhaps you want only to hit the cache if the server call failed in this case you have something to show to the user or you want to hit the cache and the server so you have something to present quickly from the cache in the same time you're getting the fresh data from the server.

  1. Cache First (Cache Falling Back to Network)
    This implies that the cache has a higher priority to fetch data from. what we already did above.

  2. Network First (Network Falling Back to Cache)
    As opposite, fetch data from the network and if an error occurred or no internet connection use cache as a fallback

  3. Stale-While-Revalidate
    Return data from the cache while fetching the new data from the server.

Read more on web.dev

Resources
https://web.dev/service-worker-caching-and-http-caching/

how does one cast as specific types?

Your caching code is elegant, but I'm afraid I'm wrapped around the axle trying to use it.

the httpCacheHelper.get method returns a type of Observable<HttpResponse>
whereas my uncacheable method allows me to cast the expected type.
http.get<Sector[]>(api).subscribe(result => {this.sectors = result; }, error => console.error(error));

I'm wondering if you might have an example of such?

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.