How to back String from UUID in node-js - javascript

Using express-cassandra i am generating an uuid by uuidFromString() method. Is there any way to back it to its previous form.

Yes, just use the toString() method on the Uuid object you generated. For example:
var myUuid = Uuid.fromString('ce547c40-acf9-11e6-80f5-76304dec7eb7');
var myUuidString = myUuid.toString();
Since express-cassandra is just using the DataStax driver under the covers, you can see the Uuid docs here:
http://docs.datastax.com/en/drivers/nodejs/3.0/module-types-Uuid.html

Related

Why is an Enum represented in two different ways in an API request? [duplicate]

I have following Enum in my project
public enum CameraAccessMethod
{
Manual = 0,
Panasonic = 1,
Axis = 2,
AirCam = 3
}
I have an object that is serialized either to json or to XML depending upon different scenarios and one of object's property is of type CameraAccessMethod. The problem i have is that when this property is serialized to XML it will give string representation of enum values (Manual, Panasonic,Axis,Aircam) but in JSON it is serialized to number values (0,1,2,3). How can i avoid this inconsistency? i want strings in JSON serialization as well.
Since Web API RC you can get string representations of enums by applying a StringEnumConvert to the existing JsonMediaTypeFormatter converter collection during Application_Start():
var jsonFormatter = GlobalConfiguration.Configuration.Formatters.JsonFormatter;
var enumConverter = new Newtonsoft.Json.Converters.StringEnumConverter();
jsonFormatter.SerializerSettings.Converters.Add(enumConverter);
You can accomplish this easily if you switch to using a formatter based upon Json.NET (which will ship out of the box with next drop of ASP.NET Web API). See this SO post for details:
How to tell Json.Net globally to apply the StringEnumConverter to all enums
To use JsonMediaTypeFormatter and enumConverter both we can use below code.
//code start here
var serializerSettings = GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings;
var enumConverter = new Newtonsoft.Json.Converters.StringEnumConverter();
serializerSettings.Converters.Add(enumConverter);
GlobalConfiguration.Configuration.Formatters.Clear();
GlobalConfiguration.Configuration.Formatters.Add(new PartialJsonMediaTypeFormatter()
{
IgnoreCase = true,
SerializerSettings = serializerSettings
});

Javascript object with arrays to search param style query string

Looking for clean way to convert a javascript object containing arrays as values to a search param compatible query string. Serializing an element from each array before moving to the next index.
Using libraries such as querystring or qs, converts the object just fine, but handles each array independently. Passing the resulting string to the server (which I cannot change) causes an error in handling of the items as each previous value is overwritten by the next. Using any kind of array notation in the query string is not supported. The only option I have not tried is a custom sort function, but seems like it would be worse than writing a custom function to parse the object. Any revision to the object that would generate the expected result is welcome as well.
var qs = require("qs")
var jsobj = {
origString:['abc','123'],
newString:['abcd','1234'],
action:'compare'
}
qs.stringify(jsobj,{encode:false})
qs.stringify(jsobj,{encode:false,indices:false})
qs.stringify(jsobj,{encode:false,indices:false,arrayFormat:'repeat'})
Result returned is
"origString=abc&origString=123&newString=abcd&newString=1234&action=compare"
Result desired would be
"origString=abc&newString=abcd&origString=123&newString=1234&action=compare"
I tried reorder your json:
> var jsobj = [{origString: 'abc', newString: 'abcd' }, {origString: '123',
newString: '1234' }, {action:'compare'}]
> qs.stringify(jsobj,{encode:false})
'0[origString]=abc&0[newString]=abcd&1[origString]=123&1[newString]=1234&2[action]=compare'
But I don't know if this is a good alternative for your problem.
Chalk this up to misunderstanding of the application. After spending some more time with the API I realized my mistake, and as posted above by others, order does no matter. Not sure why my first several attempts failed but the question is 'answered'

Javascript includes method does not work with MongoDB IDs

I was trying to use includes method to check existing MongoDB Id in an array but it is always returning false.
Is it a some kind of bug in the includes method or am I doing something wrong below is my code
let user = req.user._id;
let keyword= req.query.q;
let userSearchHistory = await UserSearchHistory.findOne({searchKeywords: keyword}).exec();
if (!userSearchHistory.users.includes(user))
{
}
where users in my database is an array with ObjectId refering to user collection
I also tried converting user object
let user= mongoose.Types.ObjectId(req.user._id);
But still the same result.
Converting ObjectIds to String working for me but then I have to remove the references in my model what is the proper way to handle this ?
This is probably happening because userSearchHistory.users returns an array of objectIds.
You can try replacing userSearchHistory.users.includes(user) with userSearchHistory.users.map(user=>user.toString()).includes(user).
This way you will be able to convert the array of objectIds to array of strings before applying 'includes' function.
Edit : Did you try trimming spaces in 'req.user._id' by using req.user._id.trim() and then casting it to objectId?

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?

How to store a json array with .NET?

I Have a json array like
[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]
How can i pass(to the backend) and store(in db) that javascript object with asp.net??
EDIT:
OK to make it clearer, in some page, i got a javascript object
var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}];
, how can i pass it to some handler (like using
`$.post({url:"handler.ashx", data:array})
??), then in backend how can i save it into database or load this array later??
OR:
I'll appreciate it if u teach me how to convert
var array = [{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}];
into:
var arraystring = '[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}]';
EDIT2:
Now i use the string-solution (traversal the array and add some '"' ':' ',' '{}' manually) as i mentioned just above, is there any potential problems??
You have several options when dealing with JSON on .NET
You can simply keep the array as is in the DB and retrieve it as is and use it
You can parse it into an Object using JSON.NET Library
for example on the 2nd case you simple use the JSON.NET method:
Newtonsoft.Json.Converters.KeyValuePairConverter
Or be fancy and use a Custom Deserialize as it's really easy to pass to and from JSON.
Let's imagine that you are posting something like this:
$.post("myForm.aspx",
[{"name":"A","value":"A"},{"name":"B","value":"B"},{"name":"C","value":"C"}],
function() {
// all done.
});
This will be converted to A,B,C when requesting the data using Request.Form["name"] or simply Request["name"] so you should change all the naming convention first and then you can simple use Request["nameA"], Request["nameB"], etc...
You would store it just like any other string you wanted to store in the database. If you want to re-instantiate it later in JavaScript you use the eval() function on the string to convert it back into an object.
The best way to do this is to de-serialize the json into object and save it to db as records.
Check JSON.NET library http://json.codeplex.com/
public class MyObj
{
public string name{get;set;}
public string value{get;set;}
}
void Main()
{
string json ="[{\"name\":\"A\",\"value\":\"A\"},{\"name\":\"B\",\"value\":\"B\"},{\"name\":\"C\",\"value\":\"C\"}]";
IList<MyObj> arr = JsonConvert.DeserializeObject<IList<MyObj>>(json);
foreach(MyObj o in arr)
{
//add each object to db...
Console.WriteLine(o.name+":"+o.value);
}
}
Ok it turns out that using JSON.parse and JSON.stringify is a not-bad solution.

Categories

Resources