这花了一些时间和一些帮助,但这是我结束的地方。它按我的意图工作。
function insert(item, user, request) {
// Store the passed in item object for us when inserting or updating
resultsItem = item;
// Store the request object to allow calld functions to send respond commands
thisRequest = request;
// Retrieve the HighScore table so we can check it for an existing record
hsTable = tables.getTable('HighScore');
// Update the leaderboard
updateLeaderboard(item);
}
// Global variables
var resultsItem, hsTable, thisRequest;
function updateLeaderboard(item){
//Filter the table using the where operator to only include those
// records for the current PlayerGUID and PlayerBadge fields
hsTable.where({
PlayerGUID: item.PlayerGUID,
PlayerBadge: item.PlayerBadge
}).read({
success:updateScore,
error: errorHandler
})
}
function updateScore(results){
if(results.length > 0) {
// If a record already exists then check the PlayerTime
if(results[0].PlayerTime > resultsItem.PlayerTime)
{
// Update the PlayerTime if it is less than the currently saved value
hsTable.update({
id: results[0].id,
PlayerTime: resultsItem.PlayerTime
}, {
success: logSuccess,
error: errorHandler
})
} else {
// Send them OK. Could change this and use the returned code/text to display a custom
// message that tells the user that a previous time is faster.
thisRequest.respond(statusCodes.OK);
}
} else {
// The record for this PlayerGUID and PlayerBadge exists so write one
hsTable.insert({
PlayerName: resultsItem.PlayerName,
PlayerCountry: resultsItem.PlayerCountry,
PlayerTime: resultsItem.PlayerTime,
PlayerBadge: resultsItem.PlayerBadge,
PlayerGender: resultsItem.PlayerGender,
PlayerDOB: resultsItem.PlayerDOB,
PlayerGUID: resultsItem.PlayerGUID
}, {
success: logSuccess,
error: errorHandler
})
}
}
// Called if there is an error
function errorHandler(error){
console.error
("An error occurred trying to update leaderboard infor for player" +
resultsItem.PlayerName);
thisRequest.respond(statusCodes.BAD_REQUEST);
}
//Called if things work out ok.
function logSuccess()
{
thisRequest.respond(statusCodes.OK);
}