Helpful Typescript Cache Annotation

Originally posted here:https://medium.com/@briankimball/helpful-typescript-cache-annotation-e29ed6564925

image

When building web applications I often come across the need to cache certain function responses for performances reasons. There are multiple approaches to do this from using Cache-Control Header, Web Storage APIs, or a service worker approach like Workbox (which I will explore further in a future post). But sometimes we want to have a little more control in code over what we are cacheing, this is usually done in a process call memoization. We recently added a new decorator to use for our of core libraries that makes it easier to control how we control cacheing of data.


With our new Persist decorator we can control how we cache the results of a method, whether we want to store that in memory, LocalStorage, or SessionStorage.

@Persist({ type: PersistType.Session })
image

Storage Type Options

There are a few options to help control how the response with be cached. You can use a ttl option to expire the cache. You can use the key to choose what storage api key is used.

image

Decorator Options

The methods return value is cache based on the arguments used and the ttl will be set specifically for those arguments as well. Only simple Objects or Promises can be returned from the cache, ie. no Classes or objects with methods unless you are using PersistType.Memory. Let’s take a look at an simple example and explain how it can be used.

image

Example Usage

So in the example above we have method that makes an http request to a REST Api to get a record then return that record. We are going to Persist the response for each id we request in the Session for up to 1 day, so that all subsequent calls for the same id will return the response from SessionStorage instead of making the http result.

image

Example Usage 2

This is more useful when you are doing composition of multiple http requests or processing or mapping data between them.

Credits

While I was trying to build this decorator out I drew a lot of inspiration from ts-method-cache library. It is much more robust then my implementation so i definitely recommend checking it out. I really wanted to embed this into a core library we use a lot internally at Bullhorn so you can checkout my source here.


untagged

385 Words

2018-11-20 16:13 +0000