How to keep users array updated with user - node.js

Sorry, wasn't sure what exactly to search for as I'm sure this has been answered before but here goes. I have a webchat server using nodejs, I made a player class, but if I push the player class to the players array that contains all the users and update the player class such as player.id, the changes do not appear in the players array. How can I solve this?
var User = require('./User.js');
var wsID = 1; // should be random just for this example
var USERS = {};
USERS[wsID] = {
socket: "",
clientDetails: {
username: "",
isGuest: ""
}
}
user = new User();
user.setUsername("test");
USERS[wsID].username = user.getUsername; // works perfectly
user.setUsername("updatedit"); // fails to update array
console.log(USERS[wsID].username); // returns test and not updatedit...
class file:
var wsId,
socket,
username,
isGuest;
function User() {
}
User.prototype.getUsername = function(){
return this.username;
}
User.prototype.setUsername = function(name){
this.username = name;
}
module.exports = User;

You are missing the reference when you do this:
USERS[wsID].username = user.getUsername;
That's because you are cloning the current value of the property into another object. One way to solve this would be to change you code so you carry the instance "user" inside your "clientDetails" so it keeps updated:
user = new User();
user.setUsername("test");
USERS[wsID].clientDetails = user; // carry the entire instance
user.setUsername("updatedit");
console.log(USERS[wsID].clientDetails.username); // should return "updatedit"

Related

NodeJS | How to not allow creation of an Object if constructor parameter has been used

My wording of the question probably butchered what I was trying to say; I'll just attach my code below:
class Game {
constructor(userID) {
if ( /* an object has not been created with this userID */ ) {
console.log("Game with this ID already exists");
}
else {
this.gameID = userID;
console.log("Created Game");
}
}
}
const gameOne = new Game(1234); // "Created Game"
const gameTwo = new Game(1234); // "Game with this ID already exists"
const gameThree = new Game(1235); // "Created Game"
Is there a way to check other objects that have been created from a class, or should I just store all the ID's in an array and check that?
You have to track which games have been created already.
It's not entirely clear what you want to happen when a game is created that has the same id as an existing game, but you could just return the existing game instance:
class Game {
static #ids = {};
constructor(userID) {
const game = Game.#ids[userID];
if (game) {
console.log("Game with this ID already exists");
return game;
}
Game.#ids[userID] = this;
this.gameID = userID;
console.log("Created Game");
}
}
Or, instead of return game, throw an error.

SharePoint userProfileProperties JSOM (JavaScript Object Model)

I am tryin to get some info from PeopleManager.getMyProperties() function.
I get the object,some values are null.when i check it from User Profile from Management,I can see the value. How can i fix this one ?
There is my working code to get object.
Note : I want to access Custom Property from User Profile which I created before.
I can see the property in the object but value is not coming.
Thank You All..
$(document).ready(function(){
SP.SOD.executeOrDelayUntilScriptLoaded(loadUserData, 'SP.UserProfiles.js');
});
var userProfileProperties;
function loadUserData(){
//Get Current Context
var clientContext = new SP.ClientContext.get_current();
//Get Instance of People Manager Class
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
//Get properties of the current user
userProfileProperties = peopleManager.getMyProperties();
clientContext.load(userProfileProperties);
//Execute the Query.
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
console.log(userProfileProperties)
}
function onFail(sender, args) {
console.log("Error: " + args.get_message());
}
Try the below code and let me know. It works fine for me. I have passed the user name instead of My account. So that you can pass any user account here.
function getUserProperties(userName) {
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
var profilePropertyNames = ["FirstName", "LastName", "CustomProperty"]; //Have to load all the needed properties here
var targetUser = userName.trim();
var userProfilePropertiesForUser = new SP.UserProfiles.UserProfilePropertiesForUser(clientContext, targetUser, profilePropertyNames);
userProfileProperties = peopleManager.getUserProfilePropertiesFor(userProfilePropertiesForUser);
clientContext.load(userProfilePropertiesForUser);
clientContext.executeQueryAsync(onSuccess, onFail);
}
function onSuccess() {
// userProfileProperties result index is same as the properties loaded above
var firstName=userProfileProperties[0];
var lastName=userProfileProperties[1];
var customprop=userProfileProperties[2];
}
Mark it as answer if it helps.
I forget to write the solution,sorry for that one.
I tried the code which written by #NaveenPrasath. It is giving a lot of fields but it didn't return "Custom Prop Field".
Working code is shown below.
function getUserProperties(targetUser) {
var clientContext = new SP.ClientContext.get_current();
var peopleManager = new SP.UserProfiles.PeopleManager(clientContext);
personProperties = peopleManager.getPropertiesFor(targetUser);
clientContext.load(personProperties);
clientContext.executeQueryAsync(onRequestSuccess, onRequestFail);
}
function onRequestSuccess() {
var fullName = personProperties.get_userProfileProperties()['CustomPropField'];
}

Need if-else advice in actionscript3

function clickButtonHandler(event:MouseEvent):void
{
var message:Object = new Object();
message.text = txtMessage.text;
message.userName = txtUser.text;
//Posts to this swf
showMessage(message);
//Posts to ALL OTHER swf files..
group.post(message);
}
function showMessage(message:Object):void
{
output_txt.appendText(message.userName+": "+message.text + "\n");
}
function jsalertwindow(event:MouseEvent):void
{
var alert:URLRequest = new URLRequest("javascript:alert('Please enter your User name')");
navigateToURL(alert, "_self");
}
As you can see there are two function which are contain mouseevent. I want to send those function with an if-else statement. If user write something in text input component which name is txtUser and,
send_btn.addEventListener(MouseEvent.CLICK, clickButtonHandler);
will work, else(if the user forget writing anything)
send_btn.addEventListener(MouseEvent.CLICK, jsalertwindow);
will work.
And one more question should i use MouseEvent.CLICK or MouseEvent.MOUSE_DOWN? Thanks for your advice.
Assign a single handler to the button click (MouseEvent.CLICK is the right event to use) and check the field is populated in the handler:
function clickButtonHandler(event:MouseEvent):void
{
var message:Object = new Object();
// Check the field is populated
if (txtUser.text != "")
{
message.text = txtMessage.text;
message.userName = txtUser.text;
showMessage(message);
//Posts to ALL OTHER swf files..
group.post(message);
}
else
{
// Nothing in the input field, show the alert
showAlert();
}
}
function showMessage(message:Object):void
{
output_txt.appendText(message.userName+": "+message.text + "\n");
}
function showAlert():void
{
var alert:URLRequest = new URLRequest("javascript:alert('Please enter your User name')");
navigateToURL(alert, "_self");
}

Static variable change does not take effect, nodeJS

I'm writing a little nodeJS based email server. I have a Request object, and in it there's one static variable that stores all the users and is defined like so:
Request.publicMemory = new Object();
Request.publicMemory.users = new Object();
Request.prototype.getPublicMemory = function() {
return (Request.publicMemory);
};
I store User objects in it:
function User(params) {
this.mails = new Array();
this.sent = new Array();
var details = new Object();
details.username = params.username;
details.password = params.password
return;
}
As you can see there's also a static function that returns it.
Now, I can add uesrs and that change is actually made, but when I change anything in Request.publicMemory.usesrs[someuser] the change is always local to the function, and does not take effect in other places. Here's an example of how I do it:
function addMail(request) {
var users = request.getPublicMemory().users;
var to = request.parameters['to'];
users[to].mails.push(mail);
}
I've never used a static variable in nodeJS before, and I'm quite new to it so this might be silly, but I still can't solve it. Any ideas?
Thanks!

How I can create a model instance in the same model's schema method?

Subject. I want init a new instance of model in it static method:
var Schema = new mongoose.Schema({...});
//...
Schema.statics.createInstance = function (name, pass) {
var newPerson = new Person; // <--- or 'this', or 'Schema'?
newPerson.name = name;
newPerson.pass = pass;
newPerson.save();
return newPerson;
}
// ...
module.exports = db.model("Person", Schema);
How I can do this?
You were on the right track; this is the Model the schema is registered as within a schema.statics method, so your code should change to:
Schema.statics.createInstance = function (name, pass) {
var newPerson = new this();
newPerson.name = name;
newPerson.pass = pass;
newPerson.save();
return newPerson;
}
And Leonid is right about handling the save callback, even if it's only to log errors.
You almost answered your question. The only problem with your code is that you don't have a registered model at this point. But you can use mongoose.model to fetch it dynamically:
Schema.statics.createInstance = function (name, pass) {
var newPerson = new db.model('Person'); // <- Fetch model "on the fly"
newPerson.name = name;
newPerson.pass = pass;
newPerson.save();
return newPerson;
}
Ow. And consider handling save callback. You can't be sure that save operation won't fail.

Resources