Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function getRandomDocument(filterQuery){
- var collection = getContext().getCollection();
- var result = null;
- var count = 0;
- var pageSize = 50;
- function query(responseOptions) {
- return (filterQuery && filterQuery.length) ?
- collection.queryDocuments(collection.getSelfLink(), filterQuery, responseOptions, onReadDocuments) :
- collection.readDocuments(collection.getSelfLink(), responseOptions, onReadDocuments);
- }
- function getRandomInt(max) {
- return Math.floor(Math.random() * max);
- }
- function onReadDocuments(err, docFeed, responseOptions) {
- if (err) throw err
- if (docFeed)
- docFeed.forEach(function (doc) {
- if (getRandomInt(count++) === 0) {
- result = doc;
- }
- });
- if (!responseOptions.continuation || !query(responseOptions)) {
- getContext().getResponse().setBody(result);
- }
- }
- if (!query({ pageSize: pageSize }))
- throw new Error("The query was not accepted by the server");
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement