How to define property at runtime in nodejs - javascript

I have the following property defined for my database access in nodejs. The problem is that I need also the url parameter defined for a certain function. I have therefore written the helper function getDataUrl()
var config = {
db: {
db: 'dbname', // the name of the database
host: "12.12.12.12", // the ip adress of the database
port: 10091, // the port of the mongo db
username: "name", //the username if not needed use undefined
password: "pw", // the password for the db access
url: undefined // also tried url: getDataUrl()
}
};
function getDataUrl() {
var dataUrl = "mongodb://";
if (config.db.username !== undefined) {
dataUrl += config.db.username + ':' + config.db.password + '#';
}
dataUrl += config.db.host + ":" + config.db.port;
dataUrl += '/' + config.db.db
return dataUrl;
}
module.exports = config;
However I do not want to call this function but use instead the property config.db.url.
I am at the moment struggling how to do that. I have tried the following:
write url: getDataUrl() this produce: TypeError: Cannot read property 'db' of undefined
call getDataUrl() which then writes the property, however this does not overwrite the url property. When I then read the value the following error occures: Cannot read property 'url' of undefined
write config.db.url = getDataUrl(); this also does not overwrite the url property.
I am very new to JavaScript and nodejs therefore I do not know how to achieve this behavior or if it is even possible.

You could try a getter property:
var config = {
db: {
db: 'dbname', // the name of the database
host: "12.12.12.12", // the ip adress of the database
port: 10091, // the port of the mongo db
username: "name", //the username if not needed use undefined
password: "pw", // the password for the db access
get url() {
var dataUrl = "mongodb://";
if (this.username)
dataUrl += this.username + ':' + this.password + '#';
dataUrl += this.host + ":" + this.port + '/' + this.db;
return dataUrl;
}
}
};
console.log(config.db.url); // automatically computed on [every!] access

To fix
write url: getDataUrl() this produce: TypeError: Cannot read property
'db' of undefined
you should change the "configs" variable to "config" in your getDataUrl() function:
function getDataUrl() {
var dataUrl = "mongodb://";
if (config.db.username !== undefined) {
dataUrl += config.db.username + ':' + config.db.password + '#';
}
dataUrl += config.db.host + ":" + config.db.port;
dataUrl += '/' + config.db.db
return dataUrl;
}

Related

How do I display JSON data to an HTML DOM Element after JSON.parse()?

I have two functions I am using to pull JSON from my server side to then display it to HTML.
The first function that pulls the data from the route handler is successfully pulling the data and parsing it successfully with JSON.parse() and displaying the needed information to the console without issue. I am not having and ajax or route handling issue...
Here is how I am dealing with the JSON first in my function called "projectInfo()":
projInfo = JSON.stringify(data);
console.log("DEBUG DONE WITH CAPTURING project_info DATA: " );
// This console.log() prints the JSON string
// successfully pulled from route handler
// var projInfo is a local string var declared in the scope of
// this first function
console.log("var projInfo: " + projInfo);
// parse JSON data in projInfo and store in string var p
// string var p is a local var declared inside of the scope
// of this function
p = JSON.parse(projInfo);
console.log("Parsed Project JSON: " + p.Project);
// update "Global" pInfo with the value of the JSON data for
// "Project" as needed
pInfo = p;
console.log("What is inside of pInfo???: " + pInfo);
// This last console.log prints [object Object] to console
// How do I pul the value out of this Object?
The second function calls the first function in order to update a global variable with the parsed JSON data that I need to then display the global variable's data to the DOM element that I am trying to display.
Here is how I am trying to update my global var with a JSON Object in my function called "loginFun()":
// Call projectInfo() in order to update Global pInfo
// with the needed project info
projectInfo();
// This console.log() prints nothing...?
console.log("projectInfo var data should be aa2: " + pInfo);
document.getElementById("userBar").style.display = "";
// This is where I try to Display pInfo in the DOM but I only get Undefined...?
document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
When I JSON.parse() the data in the first function I run a console.log() statement and I get the needed data to print from a variable local to the function I am getting my JSON with using ajax and I verify that the function is in fact doing what I need so that part is good up until I get the [object Object] output.
I am having issues when I call this function from my second function to then try to use the global variable which should have the data stored.
when I try to use the global variable with the needed data I get an 'undefined'...
I have also tried returning the data that has been parsed in the first function to then storehttps://codepen.io/lopezdp/pen/owKGdJ the value returned into a local variable in the second function but I still get 'undefined'.
If you would like to see the complete code for both functions I have put them on a CodePen to make it easier at:
https://codepen.io/lopezdp/pen/owKGdJ
How can I get my Project Data to display in my DOM element?
EDIT: The JSON Data that I am using looks like this:
{"User":"aa2","Owner":"aa2_role","Status":"locked","Port":"5432","Description":"Transferred from CFS01 on Jun29","Project":"aa2","Server":"localhost"}
I rewrote your login function like this and it worked for me. I also eliminated the projectInfo() function!
var allMn = [];
var tags = [];
var pInfo = '';
function loginFun() {
var username = document.getElementById('username').value;
var password = document.getElementById('password').value;
if (username == "" || password == "") {
alert("Required fields cannot be left blank.");
} else {
$.ajaxSetup({
cache: false
});
$.ajax({
type: 'GET',
url: 'http://139.169.63.170:' + port + '/login/' + username + "zlz" + password,
cache: false,
success: function (data) {
// NEED SUB ROUTINE HERE FOR AJAX CALL DPL
// Make async call to ccdd tool database to get new data
// This collects allMn[] data!!!
getMnJson();
// END SUB ROUTINE HERE
// Checks to make sure user is logged in if not
// the condition redirects user to loginFun()
if (data.search("HTTP ERROR: ") != -1) {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
document.getElementById('searchResults').innerHTML = "Login Failed";
document.getElementById('searchRBar').style.display = "";
loginFun();
} else {
login = 1;
// Call projectInfo() in order to update pInfo with the needed project info
//projectInfo();
var projInfo = '';
var p = '';
// Get all Mn Data on startup tp display in DOM -DPL
$.ajax({
type: 'GET',
url: 'http://139.169.63.170:' + port + '/role',
dataType: 'json',
cache: true,
success: function (data) {
// projInfo = JSON.stringify(data);
console.log("DEBUG DONE WITH CAPTURING project_info DATA: " );
// console.log("var projInfo: " + projInfo);
// parse JSON data in projInfo
p = data['Project']; //JSON.parse(projInfo);
console.log("Parsed Project JSON: " + p);
// update "Global" pInfo with the value of the JSON data for "Project" as needed
pInfo = p;
console.log("What is inside of pInfo???: " + pInfo);
document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
}
}).fail(function () {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
console.log("Error. /role data access Error.");
});
console.log("projectInfo var data should be aa2: " + pInfo);
document.getElementById("userBar").style.display = "";
// Display pInfo in the DOM
// document.getElementById("signedinas").innerHTML = "<font face=\"verdana\" size =\"4\" color=\"white\">Logged in as: " + username + " Project: " + pInfo + " </font>";
$("div.create").children().remove();
//-------------------------------------------------------------------END OF GLOBAL VARIABLES
$.ajaxSetup({
cache: false
});
// get table data from proxy server on port 7071 DPL
// NEED SUB ROUTINE HERE FOR AJAX CALL
// Make call to server-side code to reload JSON data into table from port 7071
pushJsonData();
// END SUB ROUTINE HERE!!!
// getTblJson();
}
}
}).fail(function () {
alert("Login Failed.");
document.getElementById('username').value = "";
document.getElementById('password').value = "";
console.log("Error. Need user Credentials");
});
}
}

Firebase setWithPriority results in Firebase.update failed

I'm trying to write data to the Firebase Database with a given Priority, in order to then retrieve the childs in reversed order than they are currently in. The following I got from the answer of another question regarding this issue:
var postData = {
url: urlvar
};
// Get a key for a new Post.
var newPostKey = firebase.database().ref().push();//.key;
newPostKey.setWithPriority(postData, 0 - Date.now());
var updates = {};
updates['/user-posts/' + uid + '/' + '/urls/' + newPostKey] = postData;
return firebase.database().ref().update(updates);
However, when trying to trigger this, I'm getting (from the extensions popup console):
Error: Firebase.update failed: First argument contains an invalid key
Which argument is meant by that, what exactly is wrong here?
What did work, before I tried to set a priority, was simply the code above but newPostKey was attached a key:
var newPostKey = firebase.database().ref().push().key;
After trying around different approaches I have found a solution where I can just add the priority to the postData, and then write it to the DB:
var postData = {
url: urlvar,
".priority": 0 - Date.now()
};
var newPostKey = firebase.database().ref().push().key;

ReferenceError: Invalid left-hand side in assignment at Object

Trying to finish an OAuth2 flow, but keep getting an uncaught referenceerror. Fairly new to Node.js and cant seem to find out what's going on.
// require the blockspring package.
var blockspring = require('blockspring');
var request = require('request');
// pass your function into blockspring.define. tells blockspring what function to run.
blockspring.define(function(request, response) {
// retrieve input parameters and assign to variables for convenience.
var buffer_clientid = request.params["buffer_clientid"];
var buffer_secret = request.params["buffer_secret"];
var redirectURI = request.params["redirectURI"];
var tokencode = request.params["tokencode"];
request({
method: "POST",
url: "https://api.bufferapp.com/1/oauth2/token.json",
headers: {
'User-Agent': 'request',
},
body: client_id=buffer_clientid&client_secret=buffer_secret&redirect_uri=redirectURI&code=tokencode&grant_type=authorization_code
}, function(error, response, body){
console.log(body);
// return the output.
response.end();
});
});
That's not valid JavaScript syntax:
body: client_id=buffer_clientid&client_secret=buffer_secret&redirect_uri=redirectURI&code=tokencode&grant_type=authorization_code
I'm assuming you are trying to concatenate your variable values to a string? Try this instead:
body: "client_id=" + buffer_clientid + "&client_secret=" + buffer_secret + "&redirect_uri=" + redirectURI + "&code=" + tokencode + "&grant_type=" +authorization_code
Strings in nodejs need to be quoted. In your request function, you're passing a key of body, with a value of what appears to be a giant variable. Because there are no quotes around client_id=buffer_clientid&client_secret=buffer_secret&redirect_uri=redirectURI&code=tokencode&grant_type=authorization_code, it's trying to treat this as a variable. When the parser gets to the = sign, it's trying to then set client_id = the following. This is throwing the error.
Simply quote the entire string or if you need to use variables concat using 'string' + variable + 'string'.
Judging by your variable names, you can simple rewrite it as follows:
request({
method: "POST",
url: "https://api.bufferapp.com/1/oauth2/token.json",
headers: {
'User-Agent': 'request',
},
body: 'client_id=' + buffer_clientid + '&client_secret=' + buffer_secret + '&redirect_uri=' + redirectURI + '&code=' + tokencode + '&grant_type=authorization_code'
}, function(error, response, body){
console.log(body);
// return the output.
response.end();
})

Override cached image in ajax response

I have an ajax response that is returning images that are cached. I can bust this cache with a random number generator, but having an issue applying it correctly to the returned URI.
The cached image has a URI coming from the response represented by "obj.entity.entries[property].uri" that looks like this:
http://xx.domain.com/api/v2/img/5550fdfe60b27c50d1def72d?location=SQUARE
The newly uploaded image needs to have the random number applied to it, so that it is appended to the end of the URI, right before the ?, like so:
http://xx.domain.com/api/v2/img/5550fdfe60b27c50d1def72d+6?location=SQUARE, where +6 is the randomly generated number.
I believe the best approach is to use a regex to look for the end of the URI before the ? and apply the var storing the random number, then reapply this new URI to the response. I have the following worked out, but not sure how to apply the regex correctly:
$('.image-search').on('click', function () {
var root = "http://localhost:7777/proxy/staging/rest/v1/cms/story/id/";
var encodeID = $("#imageid").val();
var bearerToken = localStorage.getItem('Authorization');
var imageCacheBust = Math.floor((Math.random() * 10) + 1);
//IF TESTING ON LOCALHOST
if (document.domain == 'localhost') {
url = root + encodeID + "/images";
} else {
//IF IN PRODUCTION
url = "/cropper/admin/cropv2/rest/v1/cms/story/id/" + encodeID + "/images";
//GRAB REFERRER URL FOR VIMOND ASSET
//SET VALUE SUCCEEDING ASSETS AS ASSET ID
var regexp = /assets\/(\d+)/;
var assetid = regexp.exec(window.document.referrer);
$("#imageid").val(assetid[1]);
};
$.ajax({
url: url,
method: 'GET',
headers: {
"Authorization": bearerToken
},
}).then(function (response) {
var obj = response;
var regexp = "REGEX HERE";
var imageURI = regexp.exec(obj.entity.entries[property].uri);
$("#imageid").css("border-color", "#ccc");
$(".search-results").empty();
for (var property in obj.entity.entries) {
if (obj.entity.entries.hasOwnProperty(property)) {
$(".search-results").append($("<li><a href='" + imageURI + "' target='_blank'><div class='thumbnail'><img width='30' height='30' src='" + imageURI + "' target='_blank'/></img><div class='caption'><p>" + obj.entity.entries[property].orientation + "</p></div></a></li>"));
}
}
}).fail(function (data) {
$(".search-results").empty();
$(".search-results").append("<p class='alert alert-danger'>Invalid ID</p>");
$("#imageid").css("border-color", "red");
});
});
You don't need to add your random digits to the file path part of the URL, just append to the URL parameters instead, that is enough to prevent caching.
For example use:
img/5550fdfe60b27c50d1def72d?location=SQUARE&6
Where the 6 is your randomly generated value.
Also, be aware that a randomly generated number might not be the best choice here, since it might be undesirably duplicated. Consider using a hash or timestamp instead of a purely random number.
The solution ended up being fairly simple:
I set var imageCacheBust = Math.random(); and then used it in the returned URI like so: var imageURI = obj.entity.entries[property].uri + "?" + imageCacheBust;

Properties for an object and this

I would like Create an object to store variables which I will use in my web app.
I cannot access the clientId and clientSecret from uriGetToken using this.
Also I can use the function in mApiGetToken in token.
Could you tell me what I'm doing wrong and how to fix it?
$(document).ready(function () {
// General Settings
var mApiSettings = {
clientId: 'aaa',
clientSecret: 'bbb',
token: mApiGetToken(),
uriGetToken: 'https://ccc/oauth/token?grant_type=client_credentials&client_id=' + this.clientId + '&client_secret=' + this.clientSecret
}
console.log(mApiSettings.uriGetToken);
// Get Autheticated, it requires getting a Token from HollyByte
function mApiGetToken() {
$.getJSON(mApiSettings.uriGetToken, processData);
function processData(data) {
mApiSettings.token = data.access_token;
}
//return token;
}
// For Testing
console.log(mApiGetToken());
});
The value of this is determined for the function in which it appears when that function is called.
There is no connection between the object literal in which you are using this and the value of this.
There is also no way to access a property of an object in the middle of the object literal statement that is creating it.
You need to use variables.
Although your examples don't have any special characters in them, you should make it a habit to escape any data you are inserting into a URI.
var clientId, clientSecret, mApiSettings;
clientId = 'aaa';
clientSecret = 'bbb';
mApiSettings = {
clientId: clientId,
clientSecret: clientSecret,
token: mApiGetToken(),
uriGetToken: 'https://ccc/oauth/token?grant_type=client_credentials&client_id=' + encodeURIComponent(clientId) + '&client_secret=' + encodeURIComponent(clientSecret)
}
It is a common Javascript question because this keyword doesn't behave like other OOP language like Java or C++.
The problem is:
var o = {
a : 2,
b : this.a *2
}
console.log( b ); //prints NaN because the value for this.a is undefined at the time b is being initialized
Because this is not accessible inside the object literal initialization. A workaround would be to use the name of the object instead of this:
var o = {
a : 2,
b : o.a *2
}
console.log( b ); //prints 4
Or you can define the object one-piece at a time:
var o = {
a : 2
}
o.b = o.a *2;
console.log( b ); //prints 4
Anyway your code should work if you change the mApiSettings to:
var mApiSettings = {
clientId: 'aaa',
clientSecret: 'bbb',
token: mApiGetToken()
}
mApiSettings.uriGetToken = 'https://ccc/oauth/token?grant_type=client_credentials&client_id=' + mApiSettings.clientId + '&client_secret=' + mApiSettings.clientSecret;
You can read more about the Javascript this keyword here: http://unschooled.org/2012/03/understanding-javascript-this/
EDIT:
as the other answer suggests you may want to encode your clientSecret and clientId before embedding them into the URL. If that is the case, you can use this code:
var mApiSettings = {
clientId: 'aaa',
clientSecret: 'bbb',
token: mApiGetToken()
}
mApiSettings.uriGetToken = 'https://ccc/oauth/token?grant_type=client_credentials&client_id=' + encodeURIComponent( mApiSettings.clientId ) + '&client_secret=' + encodeURIComponent( mApiSettings.clientSecret );

Categories

Resources