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 GetContext() method and LoaderContext interface #120

Open
swithek opened this issue Jan 23, 2024 · 1 comment
Open

Add GetContext() method and LoaderContext interface #120

swithek opened this issue Jan 23, 2024 · 1 comment

Comments

@swithek
Copy link
Contributor

swithek commented Jan 23, 2024

#83 (comment)

[T]his particular aspect of the library is still less than ideal. Having a separate type for this could be a solution we've been looking, but I'm a bit hesitant to go ahead with this because of all the duplicate code this might produce. As I mentioned in the previous comment, another solution (this time it's slightly updated) would be to have an alternative Get() method:

GetContext(ctx context.Context, key K, opts Options) (Item, error)

Also, the loader interface (there could be a separate LoaderContext interface) would have a method that returns an error and accepts a context. The options struct would allow the user to set the loader to either Loader (current interface) or LoaderContext (new interface) and depending on where the loader is used, i.e., Get() or GetContext(), the error returned from the loader would be either discarded or passed through to the caller.

So the end result would be as follows:

The Options type: the user is now able to use Loader or LoaderContext when setting the loader (WithLoader() func).
The Get(key K, opts Options) Item method: if the normal Loader is used -> no changes; if the new LoaderContext is used -> pass context.Background() as a context argument and discard the returned error (if any).
GetContext(context.Context, key K, opts Options) (Item, error) method: if the normal Loader is used -> same result as with Get() and the error is nil; if the new LoaderContext is used -> use the provided context parameter and return the loader's error to the caller.

I think this way the API will remain simple, but at the same time it won't hinder people whose loader implementations are more complex.

@ShivamKumar2002
Copy link
Contributor

This is a nice enhancement. But wouldn't it be better to add a separate loaderContext field in options? That way, the flow can be like this:

  • If GetContext is called, check if loaderContext exists, if not, use loader if exists.
  • If Get is called, check if loader exists, if not, use loaderContext if exists.

This will allow users more control over which loader is used and which context is passed.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

2 participants