Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add cache.function method #5

Merged
merged 20 commits into from
Jan 6, 2020
Merged

Add cache.function method #5

merged 20 commits into from
Jan 6, 2020

Conversation

fregante
Copy link
Owner

@fregante fregante commented Dec 1, 2019

This PR lets you skip the whole if cached, return cached, else get new value and cache it

Before

async function cachedExpensiveCall() {
	const cached = await cache.get<string>('key');
	if (cached) {
		return cached;
	}

	const data = await expensiveCall();
	await cache.set('key', data, 5);
	return data;
}

After

const cachedExpensiveCall = cache.memoized(expensiveCall, {
	expiration: 5,
	cacheKey: () => 'key'
});

Next steps

  • Fix tsd
  • Add documentation
  • Release as new major because I dropped the CJS bundle in a previous commit

fregante and others added 10 commits December 1, 2019 22:21
Now `function_` has to return a valid value. `undefined` isn't a valid value
This lets you simplify the code from:

```js
const foo = await generate();
await cache.set('key', foo);
return foo;
```

to:

```js
return set('key', await generate());
```
This enables easy overloads support.

Disk caching helps functions that take a while to execute and sync functions generally don't.

If necessary, a user-side solution would be:

```ts
cache.function(async x => syncFunction(x))
```

There's no way to support overloads on sync functions: https://stackoverflow.com/q/59125705/288906

Types could be fixed to at least support overloaded async functions but I couldn't figure out how.
@fregante fregante marked this pull request as ready for review January 6, 2020 08:29
@fregante fregante changed the title Memoized Add cache.function method Jan 6, 2020
@fregante fregante merged commit e7872c8 into master Jan 6, 2020
@fregante fregante deleted the memoized branch January 6, 2020 08:40
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
enhancement New feature or request
Projects
None yet
Development

Successfully merging this pull request may close these issues.

1 participant