Get 4 random items from the API

I have…

I’m submitting a…

  • [x] Documentation issue or request

Environment

App Name: sharescreen-africa

  • [x] Cloud version

Version: ?

Browser:

  • [x] Brave (linux)

Others:
I have a schema called “presenters”.

I would like to fetch 4 random “presenters” from the API. The use case for this is that my client is requesting that we have certain sections on the website that displays a random selection of content whenever a user lands on a page. This way, different content types can be promoted and displayed to users without any bias.

I thought that it might be possible to do this using scripts, by creating a counter and incrementing the counter when content is CREATED. So for example, create a presenter, counter is 1, create another presenter, counter is 2. I have tested this and it works fine, this is my code:

ctx.data.number.iv = incrementCounter('presenter-test');
replace();

This way, each presenter will have their own unique number, that is a sequential positive number, and then I can do a query from my app where I retrieve the total number of “presenters”, then select 4 random numbers from that total amount and then request the presenters from the API if they have that counter number.

So e.g. there is a total of 100 presenters. Then get 4 random unique numbers between 1 and 100 e.g. 5,18,24,67. Then query the API and ask to only return presenters that has those values as their number field. This will work fine.

However, this creates another issue, because when DELETING a presenter, the number does not decrement. So I tried to create a script that runs on DELETE to decrement the counter, but this did not work sadly, I think I made a mistake somewhere in my code.

var newValue = incrementCounterV2('presenter-test');
newValue = newValue-2;
resetCounter('presenter-test', null, newValue);

However, even if it did work, it would create gaps in the numbers when I delete a presenter with a number value that is in the middle.

E.g. if the counter is at 100 and I delete a presenter with number value of 80, then my query above will no longer work, because if one of the 4 random numbers is 80, then I would get nothing back from the API, or I would only get 3 presenters back instead of 4.

I am trying to think of a way how I can achieve this, to get 4 random presenters returned from the API, but am stuck at the moment.

Any help in the right direction would be appreciated.

Thanks!

If delete rarely I would just get 6 random items and then choose 4 or make a few more queries. I do not see another option.

Thats actually a pretty good idea. Thanks @Sebastian

1 Like