A coworker asked me the best way for him to cache the results of his angular service. Not knowing the answer, we went to the documentation and discovered `$cacheFactory`. This factory will allow you to build a `Cache` object to cache data.
However, I discovered two glaring flaws with this:
- Using it by itself requires you to manually check if the value is in the cache, and then use the value if it is. Otherwise, you must run the service as normal. All this checking would have to be done on a per-service basis, which violates DRY principles.
- There is no TTL, so the data will stay in the cache until you remove the data manually.
The main part of the code wraps the `put`, `get`, and `remove` functions of the standard cache so I can add TTL functionality.
However, the `run` function is the meat of the solution. By using `serviceCache.run` and passing in the function, the result will be cached. If the return value is a promise, then the result of the promise will be cached. The next time the run function is called, it will return the cached value.
The target use for this module is cases in which you don’t want/need to actually reach out to your services every time, but also want more flexibility than having to manually remove entries. I will be using this in my future projects, and have many ideas on how to improve it in the future, so stay tuned!
Check out what jobs are available at Interactive Business Systems!