Skip to content

Instantly share code, notes, and snippets.

@agramonte
Last active December 20, 2022 19:56
Show Gist options
  • Save agramonte/d884728d7fcc616036ab1932f9acfd63 to your computer and use it in GitHub Desktop.
Save agramonte/d884728d7fcc616036ab1932f9acfd63 to your computer and use it in GitHub Desktop.
GameSalad: Save and retrieve table by guid.
exports = function(payload, response) {
const uuid = require('uuid')
var {userId} = payload.query;
//Gets a blank table from the game collection to store all the user properties.
let getBlankRecord = function() {
var newUserId = uuid.v4(); //New Guid
let filter = {};
filter["Name"] = "gameVariables"; //Name of table.
//My table only has 3 columns. Name, String, Number
record = context.services.get("mongodb-atlas").db("<yourDBName>").collection("<yourTemplateCollectionName>").findOne(filter);
record.Children[1].Properties[5].Value = "userid|"+ newUserId +"|0|"; //guid is stored in 6 row (for gamesalad) and second column.
userId = newUserId;
//Function returns table.
return record;
}
let record;
if (userId == "") { //New User. Get a new blank table.
record = getBlankRecord(); //call function above.
} else { //We got a userId (guid). Pull existing.
let userIdFilter = {};
userIdFilter["userId"] = userId; //Get the one with the matching userId (guid)
//Users is the collection where i store all the user tables.
doc = context.services.get("mongodb-atlas").db("<yourDBName>").collection("<yourUsersCollectionName>").findOne(userIdFilter);
record = doc.record;
}
//
//I do stuff with the table here.
//
try {
//Create a new doc to store the user table.
let newDoc = {};
newDoc.record = record; //This is the actual Gamesalad Table craeted or updated above.
newDoc.userId = userId; //Guid so i can search for it next time it comes in.
newDoc.lastLogin = Date.now(); //The date it was updated.
//This just tells Mongo to update it or insert it if it can't find it.
var option = {};
option.upsert = true;
//Search by Guid (userid)
let userIdFilter = {};
userIdFilter["userId"] = userId;
//Insert or update.
context.services.get("mongodb-atlas").db("<yourDBName>").collection("<yourUsersCollectionName>").replaceOne(
userIdFilter,
newDoc,
option
)
} catch (e) {
console.log("error:", e);
}
response.setStatusCode(200); //Response code to GameSalad
response.setBody(JSON.stringify(record)); //Table to GameSalad
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment