meilisearch-js-plugins icon indicating copy to clipboard operation
meilisearch-js-plugins copied to clipboard

Allow passed API key to be a callback function

Open Zarathustra2 opened this issue 3 years ago • 5 comments

Description Currently one can only pass in a master key for the search but it would be nice if we could provide a callback function to set the api key.

We hide our meilisearch behind a proxy api, if we could add the users token to each request made by instant meili search we could distinguish between different users and then show the user based on their tier (free, premium) the data they have access to.

Basic example


const searchClient = instantMeiliSearch("", {
  placeholderSearch: false,
  apiKey = () => {
          return localStorage.getItem("TOKEN");
  }
});

Zarathustra2 avatar Jun 02 '22 20:06 Zarathustra2

Hey @Zarathustra2

Having apiKey accept both a string and a function is a great addition. I'm open to add this feature for those willing to contribute

bidoubiwa avatar Jun 06 '22 11:06 bidoubiwa

Tbh I am not 100% sure if that is needed after thinking about it more. In most cases you gonna have an Authentication context anyways and then one can simply do:

const { token } = React.useContext(AuthContext);
const [searchClient, setSearchClient] = React.useState(createClient(token));

React.useEffect(() => {
   setSearchClient(createClient(token));
}, [token])

But having a callback function might add some more benefits that I am right now missing! :)

Zarathustra2 avatar Jun 06 '22 11:06 Zarathustra2

Absolutely, nonetheless it could be cool 😊

bidoubiwa avatar Jun 07 '22 10:06 bidoubiwa

Hi @bidoubiwa

I would like to pick it up. However I just want to know the approach that is being discussed for the actual implementation.

bsantosh909 avatar Oct 04 '22 09:10 bsantosh909

Hey @TheLearneer thanks for your interest.

It would be

  • [ ] Implement the code (see line 35 below):
    • Check if apiKey is string or function. If function then run it.
  • [ ] Updating the README with that information
  • [ ] Add a test on both values

And as a bonus, we could introduce validating of values where we check if apiKey is either a string, a function or undefined, and if not, throw an error.

https://github.com/meilisearch/instant-meilisearch/blob/3cdebfd4aa10722f9921d732a8b09a76ceb592cf/src/client/instant-meilisearch-client.ts#L27-L40

What do you think?

Nonetheless, I can not assign you as assigning is against or policy

bidoubiwa avatar Oct 04 '22 10:10 bidoubiwa

HI @TheLearneer, checking in, are you working on this?

a11rew avatar Oct 22 '22 16:10 a11rew

Hi @a11rew 👋

Nope, I got caught up on other things, so you are free to work on it if you want to. Do follow the instructions from @bidoubiwa though 🙏

bsantosh909 avatar Oct 22 '22 16:10 bsantosh909

Ahh, got it :+1:

a11rew avatar Oct 22 '22 16:10 a11rew