Sitemap
Brian Kimball

Brian Kimball

Enterprise Architect at Bullhorn responsible for technology decisions, design, and implementation for the Front End.

Helpful Typescript Persistence Annotation

3 min readNov 20, 2018

A series of simple utilities

Press enter or click to view image in full size

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.

Get Brian Kimball’s stories in your inbox

Join Medium for free to get updates from this writer.

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 })
Press enter or click to view image in full size
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.

Press enter or click to view image in full size
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.

Press enter or click to view image in full size
Example

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.

Press enter or click to view image in full size

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.

--

--

Brian Kimball
Brian Kimball

Written by Brian Kimball

Enterprise Architect at Bullhorn responsible for technology decisions, design, and implementation for the Front End.