Validating URL Query string in Node.js - javascript

A correctly formed query string looks like:
http://baseurl.thing/update?id=123&foo=50&bar20
I want to map this "safely" into an object, but I don't want to end up with undefined values. Is there a nice way of validating the query string?
Details: I want to turn this into an object with the url module. i.e.:
var url_parts = url.parse(request.url, true);
and then I can route based on url_parts.pathname. I want to access url_parts.query.id, url_parts.query.foo and url_parts.query.bar, but only if they all exist and only if no other parameters were supplied, so that I don't get silent undefined values appearing.

set up defaults, and then overwrite them with values from your url.
EXAMPLE
var defaults = {
id : 0,
foo : 'default value',
bar : 'default.value'
};
var url_parts = url.parse(request.url, true);
var query = url_parts.query;
query.prototype = defaults; //does the inheritance of defaults thing
// now query has all values set, even if they didn't get passed in.
Hope that helps!

Related

Access variables from another JavaScript file

I need to get a variable currentID from renderermain.js and use it in renderermem.js.
However, I need to do this without having to add this to mem.html:
<script src="renderermain.js"></script>
<script src="renderermem.js"></script>
Because I cannot mix these two.
I have tried:
renderermain.js
globalVariable={currentID:activeID};
renderermem.js
var currentID = globalVariable.currentID;
But this doesn't work.
Note: I am switching html files at this point from main.html (using renderermain.js) to mem.html (using renderermem.js).
Does anyone have any ideas?
Thanks.
Basically there are two ways to pass variables between web pages. The first method is to use sessionStorage, or localStorage. The second method is to use a query string with the URL.
To use sessionStorage or localStorage:
This goes in the first web page:
// "myVariable" is the sessionStorage variable name
// "variable_one" is the variable string value
sessionStorage.setItem("myVariable", "variable_one);
// This goes in the second web page:
// Retrieve the sessionStorage variable
var myVariable = sessionStorage.getItem('myVariable');
Query String with URL:
Pass a string as a parameter.
Example:
Go to filename
When Go to filename is clicked, filename.html is loaded with the query string
"?data1|data2|data3"
appended to the filename in the address bar. To get the query string into variables,
use:
var queryString = location.search.substring(1);
The variable queryString now has the value
"data1|data2|data3"
To break these out into individual variables use split:
var a = queryString.split("|");
// which creates an array
Then get the values out of the array and put them into variables:
var value1 = a[0];
var value2 = a[1];
var value3 = a[2];
Now:
value1 == "data1", value2 == "data2", value3 == "data3"

Javascript create a mapping of array values

I am working on a project where I give a user the ability to create their own email templates and insert tags into them as placeholder values that will eventually replaced with content.
The tags are in the format of [FirstName] [LastName]
I am trying to figure out the best approach to create a function that maps these tags to their values.
For example (Psuedo code):
function convertTags(message){
// Convert all instances of tags within the message to their assigned value
'[FirstName]' = FirstNameVar,
'[LastName]' = LastNameVar
// Return the message with all tags replaced
return message;
}
I assume I could do something like the following:
function convertTags(message){
message = message.replace(/[FirstName]/g, FirstNameVar);
message = message.replace(/[LastName]/g, LastNameVar);
return message;
}
I am just trying to come up with a clean way to do this, preferably in an array/mapping style format that I can easily add to.
Any recommendations on achieving this?
You're on the right lines. You just need to generalise your REGEX to match all params, not specifically 'firstname' or some such other hard-coded value.
Let's assume the replacers live in an object, replacers.
var replacers = {
'foo': 'bar',
'something-else': 'foo'
};
And here's our template:
var tmplt = 'This is my template [foo] etc etc [something-else] - [bar]';
For the replacement, we need iterative replacement via a callback:
tmplt = tmplt.replace(/\[[^\}]+\]/g, function(param) { //match all "[something]"
param = param.replace(/\[|\]/g, ''); //strip off leading [ and trailing ]
return replacers[param] || '??'; //return replacer or, if none found, '??'
});
The value of tmplt is now
This is my template bar etc etc foo - ??
Let's say you have an object like this:
var tagMapper: {};
In this object you can add anything you want as key-value pairs, example:
function addTag(key, value){
key = "__prefix__" + key;
tagMapper[key] = value;
}
addTag("key1", "value1");
The difference between an object and an array in javascript is that one uses named indexes while the other uses numbered indexed to set and retrieve data.
Now every time your user adds a new tag, you just add a new key-value pair to this object by calling the addTag function, then to replace those keys in your template just loop over the object as such:
for (var key in tagMapper) {
if (tagMapper.hasOwnProperty(key)) {
template = template.replace(key, tagMapper[key]);
//key here has value "__prefix__key1" and maps to "value1" from our example
}
}
The prefix was added to ensure the script doesn't replace an undesirable string from our template. Your tag format may be sufficient if you are sure the template doesn't contain any [] tags containing the same key as one in the tagMapper object.

use express.js to get the query string of a url

I'm looking for a way to get the query string part of a url using node.js or one of it's extension module.
I've tried using url and express but they give me an array of parameters.
I want to original string.
Any ideas ?
example; for:
http://www.mydom.com?a=337&b=33
give me
a=337&b=33
(with or without the ?)
Use url.parse. By default it will return an object whose query property is the query string. (You can pass true as the second argument if you want query to be an object instead, but since you want a string the default is what you want.)
var url = require('url');
var urlToParse = 'http://www.mydom.com/?a=337&b=33';
var urlObj = url.parse(urlToParse);
console.log(urlObj.query);
// => a=337&b=33
How about using the built-in url.parse method?

mongodb/meteor collection check if subdocument field exists when field is a variable

I'm trying to use something as follows
collection.find({"myField."+variable : {$exists: true})
But obviously that doesn't work because the collections doesn't take strings. Instead, I tried building a a fully query string in JSON but that won't parse correctly because I'm just searching for a field name and not an entire object
var qry = '{"myField.'+variable+'"}'; //no go
I've also tried the meteor collection fields logic
var qry = 'myField.'+variable;
collection.find({}, {fields: {qry: 1}})
to no avail. I know that a query can take a JSON object but I'm not sure how to write this up.
Give this a try:
var selector = {};
selector["myField." + variable] = {$exists: true};
Collection.find(selector);
This can be accomplished using bracket notation
var fieldQuery = {};
fieldQuery["myField"+variable] = {$exists: true};
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_Accessors#Bracket_notation

how to pass a dynamic key value from a string in mongo data base

I try to dynamically access a field in mongo database.
The target field is given by this line:
var contextTarget= Session.get('contextLayout')+"BackgroundColor";
Where
Session.get('contextLayout') could be either a string or an _id of a collection(eg. userHomeBackgroundColor or 56xhPYg8w3Qtv9xPLBackgroundColor).
I don't know how to access the value.
I tried this code:
var contextTarget= Session.get('contextLayout')+"BackgroundColor";
var tempStore ={};
tempStore['target']=contextTarget;
var newTarget = tempStore.target;
console.log(newTarget);//return the correct value
var color = customConfiguration.findOne({'author':auth}).newTarget;
console.log(color);//return undefined
It doesn't work. I suppose that it's because the newTarget variable is a string because if I directly write the expected result in the console, it works.How can I do?
EDIT.
like said BraveKenny:
var color = customConfiguration.findOne({'author':auth})[contextTarget];
In fact, it was not necessary to pass by the object tempStore. With the square brackets keys are properly sent. I had already try it but with a dot before the square bracket.
#Michael: For the schema, I don't have a schema for this collection, because the key names are dynamically created.
Thanks a lot.
If I understand correctly, in the end, you want to get a variable attribute of your customConfiguration object, which name is contained in newTarget.
Maybe try this instead:
var color = customConfiguration.findOne({'author':auth})[newTarget];
Basically when you type:
someObject.toto = 'someValue';
var someAttribute = 'toto';
console.log(someObject.someAttribute); //undefined
console.log(someObject[someAttribute]); // 'someValue'
JavaScript will always assume someAttribute is an attribute of someObject when it's called with a dot notation. Not a variable set in the scope. If you want the value of an attribute toto which is contained in a string variable (in my case, someAttribute), you have to pass this variable as an index, like this:
console.log(someObject[someAttribute]); // 'someValue'
It would be helpful if you could describe the schema of the collection customConfiguration. I just guess that it contains a collection of documents with just one property each (e.g. userHomeBackgroundColor or 56xhPYg8w3Qtv9xPLBackgroundColor) and you are interested in the one document with the correct property name to read the property value. So I guess, in JSON notation the collection looks something like this:
[
{"userHomeBackgroundColor": "red"},
{"56xhPYg8w3Qtv9xPLBackgroundColor": "green"},
{"someOtherConfigProperty" : "someOtherValue"}
]
If this assumption is correct, I would replace your original line
var color = customConfiguration.findOne({'author':auth}).newTarget;
With something like this:
var selector = {}; // Empty selector object for findOne
selector[contextTarget] = // Add dynamic property and as its value
{$exists: true}; // an object with an $exists-property
// with value true
// now find the (first) configuration document having the dynamic property
var configDocument = customConfiguration.findOne(selector);
// read the value of the dynamic property of the configuration document
var color = configDocument[contextTarget];
But to verify this, I need more background about the schema of the collection customConfiguration. You might also want to check the documentation of $exists (http://docs.mongodb.org/manual/reference/operator/query/exists/#op._S_exists) and findOne() (http://docs.mongodb.org/manual/reference/method/db.collection.findOne/) in the documentation.
If, however, the collection customConfiguration contains one configuration document for each author, change your line to just this:
var color = customConfiguration.findOne({'author':auth})[newTarget];
This solution has been described in a previous answer.

Categories

Resources