Hi …
now I have implemented a similar script in groovy, that stores the rating:
{{groovy}}
import java.util.stream.Collectors;
import groovy.json.JsonOutput
import groovy.json.JsonSlurper
import org.xwiki.model.reference.ObjectReference
if (request.method == "POST" && xcontext.action == "get") {
def body = new BufferedReader(new InputStreamReader(request.getInputStream()))
.lines().collect(Collectors.joining("\n"));
def payload = new JsonSlurper().parseText(body)
if (payload.doc != null && payload.id != null) {
def ref = services.model.resolveObject(payload.doc + "^" + payload.id);
def user = xcontext.getUser();
def vote = services.ratings.aufgaben.setRating(ref, payload.vote)
def average = services.ratings.aufgaben.getAverageRating(ref).get()
def json = [
ref: "" + ref,
vote: payload.vote,
user: user,
averageVote: average.averageVote,
totalVote: average.totalVote,
]
print JsonOutput.prettyPrint(JsonOutput.toJson(json))
}
else {
def user = xcontext.getUser();
def json = [
message: 'doc and/or id missing',
body: body
]
print JsonOutput.prettyPrint(JsonOutput.toJson(json))
}
}
{{/groovy}}
It’s callable by means of a fetch:
var sendRate = function (rid, vote) {
fetch(new XWiki.Document('WebHome', 'Macros.Aufgabenbewertung').getURL('get') + "?outputSyntax=plain", {
method: "POST",
headers: { "Content-Type": "application/json"},
body: JSON.stringify({
vote: vote,
doc: XWiki.currentDocument.space + ".WebHome",
id: rid,
form_token: document.documentElement.getAttribute("data-xwiki-form-token")
})
}).then(data => {
console.log(data.json())
});
}
It seems to work. However, when I try to read the average rating with #set($average = $services.ratings.aufgaben.getAverageRating($ref))
, I do not get the expected value. My explorations (getCurrentUserRatings) reveal, that there are actually multiple ratings stored with the same [object reference / user reference] combination:
reference = [Object xwiki:Sandbox.WebHome^test], vote = [4], scale = [5],
reference = [Object xwiki:Sandbox.WebHome^test], vote = [1], scale = [5]
I’d expect, that a certain user can only give one single vote per object reference!?
Now I wonder, if it is actually possible, to store a rating with arbitrary object references, for which there are no real objects? Sandbox
is an existing page, but there is no object named test
contained in that page.