samedi 31 août 2019

Serialize and Cache return values from function and playback snapshot of results

Foo is an example of a function that works "now" but in the future it will possibly throw an error or return some different value.

const foo = () => {
  if (new Date() < new Date('2019-09-05') {
     return 'Hello world"
  }
  throw new Error('failure')
}

const x = cacheLock(foo())

What I am looking for is a way to wrap the return value of foo() so that If a value is returned successfully on initial execution it will cache a snapshot of the result to a file locally and on subsequent executions of this code the stored value is automatically returned and the contents of foo() is never run.

I'm looking for a way to serialize functions results as well as async / awaited promises locally, then playback the stored results.

An ideal feature would be a way to also re-run the code and update the cache.

Is this possible? I know there are issues when it comes to serializing objects and using .toJSON() .fromJSON() methods is one way to solve that.

Are there any libraries out there that can do this? Is there a means of achieving this without serialization?

I'd love a generic solution to this problem that's not tied to testing, or databases. But my top use case is easily mocking / stubbing API calls and Database reads. The sources of which can change with time and aren't reliable to run in tests. There are many solutions when it comes to those mocking databases or mocking api calls, but I would find that some way to cache live calls, and store them for later the most intuitive.

This idea is more of a post-runtime memoization, a cache that sustains even when the process is finished, while traditional memoization just lasts within the runtime of a process.

Aucun commentaire:

Enregistrer un commentaire