How do I include an object in a query-string as is? - javascript

I need a query-string to be in the format:
brand=samsung&model={"type":"touch"}
I am using the in built query-string module in Node.js
How would I form my object in order to output the query-string above?
My current object looks like this:
{ brand: samsung, model: { type: 'touch' } }
Which returns a query-string in the format:
brand=samsung&model=
I need to form the query-string without altering the URL.

This should do the trick:
const qs = require('querystring');
let object = {};
object.brand = "samsung"
object.model = JSON.stringify({
"type": "touch"
});
console.log(qs.stringify(object));
Here is a demo.
This is done with percent-encoding, the request will be interpreted as an object you described in your question.

Related

How to generate Joi validations via code, based on an object and save it in a file using Nodejs

I am trying to generate Joi validations via code based on an object. I would like to know if there is a way to generate them programatically and store them into a file. I tried the following way:
Lets say I have an object as follows:
let obj = [{
Key: 'key1',
Type: 'string'
}]
A function to generate an object of Joi validations:
function getJoiObject(data) {
const obj = {};
Object.keys(data).forEach(key => {
if (data[key].Type === "string")
obj[data[key].Key] = Joi.string();
else if (data[key].Type === "integer")
obj[data[key].Key] = Joi.number();
else if (data[key].Type === "boolean")
obj[data[key].Key] = Joi.boolean();
});
return obj;
}
I saved the object onto a file and used it in another file for validations.
fs.writeFileSync('validations.json', JSON.stringify({res:getJoiObject(obj)}));
The problem is that when I import the validations.json into another file and validate it with data, it wouldn't work.
const a = {key1:'abc'};
Joi.object(validations.res).validate(a)
Could you please help.
Thanks in advance.
Joi has methods to serialize and deserialize its schemas, but they aren't fully documented (as of v17.6). I had a similar question and found this GitHub issue which answered it for me.
What you can do is call the describe() method on your schemas before saving them to a file. This will serialize them into a simpler form. Then, when reading the serialized version from your file, use Joi.build() and pass in your serialized schema to deserialize them back into Joi objects. Just make sure to parse stringified JSON back into an object first.

Replace part in some string written in separate file that is being used in other file javascript

I have a config file that has different URLs for different environments. I am using the object key for base url from the given object.
const configDev = {
API: {
url: 'http://api.domain.com',
},
};
I want to add one string based on the module and add it to the above URL string like this.
const configDev = {
API: {
url: 'http://contact.api.domain.com', // if module name is not passed then it would be same as above.
},
};
This configDev object is being used in some other place in the project.
How can I place in the variable in the above-given JSON data and replace the value in the variable?
I am using configDev variable in another file like this:
const HTTP = axios.create({
baseURL: CONFIG.API.url, // CONFIG value is different based on differnt environment.
});
When you got configDev in some other place in project you can split url string and insert desired value
const splittedUrl = configDev.API.url.split('://');
splittedUrl = [ 'http', 'api.domain.com' ]
const targetUrl = `${ spilttedUrl[0] }://contact.${ spilttedUrl[1] }`

First query string parameter is not parsed using qs npm package

I fail to parse the first query string parameter using the qs npm package. What am I doing wrong?
I execute these commands in my console
import * as qs from './qs'
var addr = "https://www.somesite.se/?title=querystring&action=edit"
var parsed = qs.parse(addr)
After executing these commands parsed has the value:
{ 'https://www.somesite.se/?title': 'querystring',
action: 'edit' }
This is strange. Why is title not a property on the returned object? I would expect the value of parsed.title to be 'querystring'. but it is not. The value of parsed.title is undefined.
Why?
qs parses query strings. It does not parse URLs. Use a URL parser (new URL(addr).search.substring(1)) to get the query string from the URL first.
qs.parse("title=querystring&action=edit") should give you a correct answer.
Now that I think about it... why even use qs? new URL(addr).searchParams should already give you the params parsed...
The answer is: the qs library is using for parsing the query string only.
According to Wikipedia:
a query string is the part of a uniform resource locator (URL) which assigns values to specified parameters.
For example:
In your case, the correct codes should be:
var addr = 'title=querystring&action=edit';
var parsed = qs.parse(addr);
console.log(parsed); // {title: "querystring", action: "edit"}
To bypass the leading question mark, use ignoreQueryPrefix:
var addr2 = '?title=querystring&action=edit';
var parsed2 = qs.parse(addr2, { ignoreQueryPrefix: true });
console.log(parsed2); // {title: "querystring", action: "edit"}
Hopefully, that helps!

Ember Data's find method: handling SQL 'OR' equivalent query

i'm new to ember, and have implement Ember Data for data retrieval within my app.
I wish to retrieve a list of articles that are either in the 'Beauty' or 'Health' category.
The SQL equivalent is:
from article where category = "Beauty" OR category = "Health"
How should I do this using Ember Data?
I've tried:
this.store.find('article', {category: ['Beauty', 'Health']}
but this results in a poorly formatted GET request like:
/articles?category%5B%5D=Beauty&category%5B%5D=Health
Ideally i'd like the format to be: /articles?category=Beauty&category=Health
Appreciate any suggestions!
%5B%5D is the encoded version of [] and is perfectly valid in a URL.
Ember delegates the formatting of the request data to jQuery.ajax, which adds [] to properties containing an array. The ajax setting traditional tells jQuery to not add the brackets. One way to configure that in Ember is to extend the adapter:
App.ApplicationAdapter = DS.RESTAdapter.extend({
ajaxOptions: function (url, type, hash) {
hash = this._super(url, type, hash);
hash.traditional = true;
return hash;
},
});

URL parsing in node.js

I am developing restAPI using Node.js. In that the following is the URL for my API:
http://xxxxxxxx:3000/map70/places?node[level0=12&level1=34&level2=234][ids=1,2,3,4][key=xxxxxxxxxx][val=2011]
In this i have to get the each parameters level0,level1,level2,ids,key,value.
In normal url format like the below:
http://xxxxxxxx:3000/map70/places?key=xxxxxxx&val=2011&level0=2&level1=33&level2=602
I can parse like req.query.level0.. .But for the above url how can i parse it.I searched a lot,but i cant find the right solution.Help me to solve this..Thanks in advance....
Is there a name for this style of query parameter? I have never heard of it. If there's some standard around it, you might be able to find some obscure module that'll parse it. Otherwise, it's very likely you'll have to parse the string yourself.
You can get hold of the thing with Node's url module:
var url = require('url');
var parsed = url.parse('http://xxxxxxxx:3000/map70/places?node[level0=12&level1=34&level2=234][ids=1,2,3,4][key=xxxxxxxxxx][val=2011]');
var query = parsed.query;
At this point, query now contains node[level0=12&level1=34&level2=234][ids=1,2,3,4][key=xxxxxxxxxx][val=2011], and you can start to pull it apart with string operations.
[Update]
I'm only going off the URL you posted, so you'd probably need to write some tests cases to ensure all the parameters you care about get parsed, but I was able to get something like this:
var querystring = require('querystring');
var q2 = query.slice(5, -1);
// q2 == "level0=12&level1=34&level2=234][ids=1,2,3,4][key=xxxxxxxxxx][val=2011"
var q3 = q2.replace(/\]\[/g, '&');
// q3 == "level0=12&level1=34&level2=234&ids=1,2,3,4&key=xxxxxxxxxx&val=2011"
querystring.parse(q3);
// returns:
// { level0: '12',
// level1: '34',
// level2: '234',
// ids: '1,2,3,4',
// key: 'xxxxxxxxxx',
// val: '2011' }
You can combine it all together into:
querystring.parse(query.slice(5, -1).replace(/\]\[/g, '&'));

Categories