Advertisement
Guest User

Untitled

a guest
Apr 19th, 2019
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.06 KB | None | 0 0
  1. function getRandomDocument(filterQuery){
  2. var collection = getContext().getCollection();
  3. var result = null;
  4. var count = 0;
  5. var pageSize = 50;
  6.  
  7. function query(responseOptions) {
  8. return (filterQuery && filterQuery.length) ?
  9. collection.queryDocuments(collection.getSelfLink(), filterQuery, responseOptions, onReadDocuments) :
  10. collection.readDocuments(collection.getSelfLink(), responseOptions, onReadDocuments);
  11. }
  12.  
  13. function getRandomInt(max) {
  14. return Math.floor(Math.random() * max);
  15. }
  16.  
  17. function onReadDocuments(err, docFeed, responseOptions) {
  18. if (err) throw err
  19.  
  20. if (docFeed)
  21. docFeed.forEach(function (doc) {
  22. if (getRandomInt(count++) === 0) {
  23. result = doc;
  24. }
  25. });
  26.  
  27. if (!responseOptions.continuation || !query(responseOptions)) {
  28. getContext().getResponse().setBody(result);
  29. }
  30. }
  31.  
  32. if (!query({ pageSize: pageSize }))
  33. throw new Error("The query was not accepted by the server");
  34. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement