Angular Http Caching using Interceptor and Refresh

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
this video is made assuming that you have a fair understanding of how an angular interceptor works this is code with shinny let's get started caching an http request for get calls is highly important as it will avoid making an api service calls unnecessarily an interceptor can be used to delegate caching without disturbing your existing http calls angular already have a documentation outlines on these subjects but the problem here is it is missing the full implementation the core idea is very well outlined here so we are going to make use of this core idea and build our very own caching interceptor and cache resolver service let's get started by creating our very own cache resolver service a cache resolver service is a simple dependency injection service that sits and gets url query strings along with http response so let's create our class here and it's an injectable so it should be injectable export class cache resolver service and it should contain a private variable of a cache or field as a cache and it should be instantiated with a map class amp class as a data type of a string and a tuple of date and response object so let's define them here it should be a string and a tuple which is basically a collection of of objects in an array and http response and next bit is the constructor and we will be storing all the http response using a key which is basically act as an unique identifier the unique identifiers are basically the api calls that we may we may make for example let's assume that you are going to fetch list of users right so if there is going to be all users you'll be fetching it should be api v1 slash users and that will be acting as a unique identifier and it will it will hold the list of responses that pertaining to the api call whereas if you're going to search for a username called jeremy or j e g e r then it will act as a unique identifier and that string will be acting as a unique identifier i hope you get what i'm trying to say we'll be getting in detail as we move along so let's go to the set part of our interceptor resolver so this will be a set which will have a key and a value basically the http responses that you will be storing and time to live so time to live could be a number or it could be null so by default let's call it as null we'll do one let's log what we are getting through set method so set cache key and the key so we know what sort of unique idefire or the url that we will it will be passed through the set method and the core logic the time to live if the time to live is present so basically time to live we may set it as a 60 seconds which is one minute or however number of minutes that you want to store the cache the data so you can set it all through here so you will be passing the time to live through the interceptor and if the time to live is present we have to write a little logic here which is fairly straightforward expires in as new date and expires set seconds which is expires in dot get seconds right plus time to time to live right so here we are describing how many number of seconds that you want our cache to be enabled to be stored and finally we need to store this cache so this cache set so the map comes up with a list of a list of methods where you can uh you can set you can get let's look at you can delete and you can i trade them you can do various operations with the inbuilt methods that it offers so we are going to set the key and the actual values so the key will be our unique identifier and we're going to set the tuple as well so tuple in case if we have time to live we will be setting at expires in and the http response will be our value fair enough and in the else part l spot is when you don't have a time to live we can set it like this and we can set a null for that right so this is the set part now we have to move to the get part of the map indicate method we have to use our unique identifier which is a key so basically we'll be storing based on the key right so we'll fetch the stored value if it is there and if it is not there we'll be sending a null so we need to split our data based on the key so let's call them as tuple cache get and key based on the url git call let's say v1 user and the query string something else is there based on them whatever that's saved will be fetched and put them in tuple now the first check is tuple is not there then obviously there are no information present whatsoever and we're going to send the uh we're going to send the null and here we will extract our tuple into a date and response and yeah constant expires in equals tuple of zero zero is the index because the first index we are we are saving the expires in the date as the as the first index so that's why we are getting the expires in from the tuple of zero and the next bit is constant http saved response this will be our second index which is of one in an array and now so this now plays a slightly important role here using the date now we're going to check if the expired time is less than the current time so if so we are going to delete the cache and then return the null otherwise return the http save response so it's fairly simple logic so expires in if the expire is in presence and it is not null and expires in get time is less than the now get time in that case firstly we are going to delete the cache because we don't we don't want to hold these obsolete information in our in memory cache so we are going to delete them using the key and return null okay this is first part of our check the last part is return whatever that you have like the saved response that you have and this is pretty much the http cache resolver the logic is fairly simple so we are using key as an argument and we are fetching the stored value of our mapped cache so the map data object will look like this and if the cache is null right we are going to return a null to the cache interceptor otherwise the cache is extracted in two parts the two parts is this the expires in the http saved response and if the time to live is expired which is this section if it is expired then we will return the null otherwise we will return the saved response to our cache sorry cached interceptor the cat all the returns right it will be handled in the interceptors so next the big picture here is creating a cache interceptor so let's get started with creating an interceptors let's create a folder called interceptors cache interceptor ts looks like it's working obviously the interceptor is similar to the cache resolver they both are services they both needs to have an injectable and it is a dependency injection service injectable and export class cache interceptor implements http interceptor so the caching receptor interceptor requires intercept as a property which is missing before that let's go to the constructor and inject our cache resolver so cache resolver and cache resolver service and the next bit is we need to have an intercept as our missing property the intercept requires a request which is a http request of any and next handler which will be passing on to the next interceptor or completes the interceptor and obviously an interceptor will return an observable should it could be null or anything but it should return an observable of an event right so the first part is in our cache interceptor we are going to cache only the get cost not the post calls or put calls because we we don't want them to be cashed so we don't want to cash the post calls or put calls or anything that we're going to save we don't need them so first bit is we will check with the method if the method is not equals get in that case we're going to return pass on the pass on the information pass on the request to next next interceptor okay so that's what this means we need to get the cash resolver so we need to get the requested url from the cache resolver so the cache resolver sorry cached response will be from the cache resolver and we have seen right so in the cache resolver we'll be passing on the key so that key will be the url now in here we need to write little complicated logic so if the cached response is there then if it is present if it is not null in that case so there are there is a situation where we'll be returning a null and we'll be returning a response so in case we are sending a null as a return then we need to use the off operator from the observable and send the cached response if it is not null we are returning a cached response if the cache is available otherwise we need to write a separate logic we cannot accommodate everything in this intercept function so we need to write a separate method called set request where a little bit of logic is played upon using the request and next and then pass that information on on to the return so since there is no space to write the entire logic here we'll be extending them into a separate function let's call it as this dot set request sorry not set request it's a send request and we'll be making use of that in in the return statement of intercept so send request takes in a request and next that's from the intercept methods obviously a rick which is a http request and next which is an http handler it returns an http event like uh in the intercept method all right so yeah we have an observable actually beyond it compliance because we didn't we are not returning anything here as of now so let's write a little bit of our logic so it's a return next handle of request but before passing on the request we are going to pipe them we are going to pipe it and we are going to tap which is a psychic using a tap method we are going to listen to the events in the uh yeah using an event we are going to check if event instance of if it is a response because sometimes you might get errors as well so we're going to check if object type is a response we need to add them in our angular code in that case so this is the actual logic so if that's the case we are going to set a request of a url and the event which is the actual http response and finally we forgot a major thing here which is time to live time to live as a constant which is a constant of time to live as 10. all right so our interceptors are completed and cash resolvers are completed we need to create a mini application where we can test this out firstly to understand this a cache interceptor is just like any other interceptors our cache interceptor initializes the cache resolver which is here and in the constructor to make the caching mechanism to work next we need to capture only the get calls so this is this part is where we are capturing only the get calls thing we are checking if it is a get call uh we need to introduce a special header called x refresh we will cover that a little bit later and last part is where we use the cache resolver to set the actual uh url and the response for our caching mechanism okay so this is pretty much it now let's build a simple application where we making where we can make use of our caching mechanism i already have a mini application build so i already copy pasted all my code to this editor so this is where all the information i added for example the cached solver needs to be in the provider and the data service and and including the interceptor without this information nothing will work the interceptors will never work the data service part which is basically i'm going i'm fetching a list of users and the search users and things like that i mean we're going to make use of them so based on this we are we're going to get a list of uses so that's what i'm trying to say so the data service part is done and finally the http sorry the app component where i added some forms so let me just uncomment them immediately we see a an issue so yeah we are far from building our application in the app component we need to have a constructor in the constructor we should call the data service we need a method to handle that will get list of users from the data service so get users and this dot um we need a subscriber as well which we forgot to add so let's add our subscriptions and observables which will be user sub will be our subscription point and search subscription and list of uses of course so we i haven't created an interface for this we need to have an interface for the data model that you are working so it should have a model and it should i mean all your application should be based on that so that's one best practice that you need to follow and we need a functionality called search users and in the search users search user input search user input which is a html input element we are going to fetch information from um from the html input element which is uh which is a input element here search input element we are going to catch we're going to query this we're going to call this html input element first off let's see what this search input element returns so we can track and the next thing is there is a check box called i introduced a check box called latest check uh which is basically if i want the latest results to be updated not the cached one i can check this box so it's it'll come in handy sometimes in your application so i just added them for uh for convenience reason latest boolean but there is some there is an error we need to import http client module for right let's ignore this for now i'm going to open up a console that way we will have a clear picture of what's going on so so we have the interface application and all the errors cleared and the application is up and running so when we type in let's say jer which is short for jeremy and i'm getting the um i'm getting the value here which is from from the console and the the way it operates is i have a button which is this search button and on the click of it i'm calling a search users with a search user interpret template variable from this text box and also the check box that you see is from from this code is from here so the get latest results check box when i click on it and search for it it'll turn to true so the logic is if you want to get the latest information from the api it will avoid the caching mechanism and then it will uh it will get it from the server we need to have a little check it's purely uh i mean purely optional we don't have to stress on this so if the search input value of the length of the search input value is greater than zero only then we have to make a call otherwise we don't have to so i'm going to empty the users array and research subscription this data search users search input value i'm passing on the value that it requires and yeah the other value is the latest check the latest check functionality will never work because we haven't implemented them in our cache mechanism and we will be covering that soon so let's complete this flow first in the subscribe block we will have a next which will give us the results users too we need to see what results we are getting so use a list of users and this uses equals users yeah from http response so it is expecting an explicit right so next one is the error in case your application crashes or the server doesn't work console.error and finally the complete so i'll just copy from here search completed all right pretty much our application is completed if i search for something i should be getting the cache key that we have seen in our cache interceptor looks like i made a minor mistake i added interceptor outside the app folder which should be inside and in the interceptor we should also fix this yeah now it's all right right so let's begin with our testing right let's do a search here so if i type in kim it goes for call and in your console you will see the search is made and there is no result for kim let's try another one we have a list of uses here so let's try for will so there is a wilford prince and in the network if you see the search is made for will and this will be considered as your unique identifier the entire url string so let's do little testing on this so if i search for jer jeremy it'll give out our result and again if i do a test the the api call won't be triggered but it will return the information from the saved resource saved cache and there's one little thing that i forgot to mention in the interceptor part where we set the time to live the the time to leave is set only for 10 seconds so after 10 seconds if i do a search it triggers right so this needs to be extended so for the testing purpose let's keep it as 10 seconds but in your real world application you should decide on how many number of seconds that you need to have we have searched for jer let's search for another name called will so will and if i do a search again it won't happen because it didn't cross the time to live of 10 seconds now again if i do a search it triggers a new api so so far we have seen how an interceptor is used to do a cache resolving here the other bit is we haven't looked upon using the uh getting the latest results system right this is not yet done so that can be done using our data service which is over here so based on the latest right so we are going to send whether the information we need is the latest or not using the the flag that we have seen for example in the console you might have seen false and if i do a if i click on them if i check on them you'll be seeing them as true so that information right so that is intercepted over here the latest check and that will be passed on to our data service as a latest check and in the data service you'll be having a boolean called latest so what i'm trying to say is we can append that information we can check that information using the latest and i i can set a custom header it's already been set here so i'm just trying to explain if the latest is true i'm setting a header called x refresh as true so this information is enough for for us to catch them in the interceptor over here we can write a little logic that bypasses all the other functional logic here we can have a check here that says not here exactly um just above the cached response that says if request of headers and i'm going to get if x refresh x refresh is present right otherwise this will be truthy if the x refresh is present in all of the cases this won't come through inside this block in the x refresh i'm going to return the fresh request it won't be a cached response so i'm going to bypass this cached response entirely altogether so it will be this part there you have it i think this is pretty much uh pretty much it now let's test this out and as a test i may need to increase our time to live let's say four thousand so i am using i'm searching jeremy okay and if i do a search nothing happens again but if i click the get latest result it should trigger an api which it does so yeah that works now and that's pretty much it about the http caching interceptor the entire app or this mini app will be available to you i will be providing a link in this video in the description please take a look at it and make use of it in conclusion this video outlines only the basic principle of http caching technique our caching mechanism is really bare minimum and simple however if you refresh the browser tab the stored values will be removed so what i suggest is we can extend the cash mechanism by saving them in a local storage and making them persistent we can create a separate service injectable service called storage service and we can handle all the storage mechanism in a separate service in a really large application we can make use of local storage and we can make use of a very efficient storage system so this is pretty much it for the angular hdb cache with interceptor thank you for watching this video and welcome to code with srini again please subscribe to my channel and share it with your friends thank you and if you have any other suggestions please drop down that in my comment sections and i will have a look at it and probably respond to you as soon as possible thanks again bye
Info
Channel: CodeWithSrini
Views: 6,465
Rating: undefined out of 5
Keywords: Angular, Tutorials, Use case, Scenario, HTTP Web Caching, HTTP Interceptor, Angular Caching, Angular Web Caching, Cache, Storage, Web Api, API Cache
Id: y921lgvICnQ
Channel Id: undefined
Length: 22min 29sec (1349 seconds)
Published: Tue Apr 19 2022
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.