I am developing the node js API and I a querying data by the URL
get_posts_default?pageId=ge4JqBn9F0srzHnVFHmh&asking_post=false&asking_responce=false&maxSort=-1&minSort=-1&limit=20
This is the function who is responsible for handling this request
public async get_poset_list(userDeta: hs_I_fb_en_user_auth_paylode,pageId:string,asking_post:boolean,asking_responce:boolean,maxSort:number,minSort:number,limit:number):Promise<hs_I_fb_en_post_return[]>{
try {
hs_d_w("Is asking post: - "+asking_post);
hs_d_w("Limit: - "+limit);
if(asking_post===true){
hs_d_w("Asking post true");
if(minSort<=-1 && maxSort<=-1){
hs_d_w("Asking post Defolt");
return this._postQueryes.get_only_poses(pageId,limit);
}else{
if(minSort>-1){
hs_d_w("Asking post MIn");
return this._postQueryes.get_only_poses_min(pageId,minSort,limit);
}
if(maxSort>-1){
hs_d_w("Asking post Max");
return this._postQueryes.get_only_poses_max(pageId,maxSort,limit);
}
hs_d_w("Asking post None");
return [];
}
}else{
if(minSort<=-1 && maxSort<=-1){
hs_d_w("Asking talk Defolt");
return this._postQueryes.get_only_talkes(pageId,limit);
}else{
if(minSort>-1){
hs_d_w("Asking talk min");
return this._postQueryes.get_only_talkes_min(pageId,minSort,limit);
}
if(maxSort>-1){
hs_d_w("Asking talk max");
return this._postQueryes.get_only_talkes_max(pageId,maxSort,limit);
}
hs_d_w("Asking talk none");
return [];
}
}
} catch (e) {
hs_d_w("get_poset_list : " + e);
return Promise.reject(e)
}
}
Now if I call set asking_post=false or asking_post=true it allways call the main else area of this function
return this._postQueryes.get_only_talkes(pageId,limit);
This one.
I don't understand why it's happening? Can anyone please help me on this?
When you get something from the req.query it will always return a String. So, make sure to convert it to boolean using
const variable = (variable == 'true')
// or
const variable = (variable === 'true')
On a side note, when a variable is boolean you don't have to check explicitly with ===. This will also work
if(foo) {
} else {
}
EDIT: as #Kamalakannan said Boolean('string') will not work. My apologies.
Query params are considered as strings. So if you check with ===, it will be falsy.
Do string comparison, like if ("true" === asking_post) or if ("false" === asking_post)
Boolean(asking_post) will always return true for string values
const t = Boolean("true");
const f = Boolean("false");
console.log("Value of 'true':", t);
console.log("Value of 'false':", f);
So don't use Boolean(asking_post).
You can simply convert it with JSON.parse.
const x = JSON.parse('true');
const y = JSON.parse('false');
It will return boolean values for both.
When you get any values from request you always get String type.
So you need to convert it into Boolean first. Or just check with String.
You can do this: (I personally preferred)
var isTrue = (asking_post == 'true');
But please be caution to use following method:
var isTrue = Boolean("false"); // return true
var isTrue = !!"false"; // return true
Any string which is not empty will give you true by using the above methods.
Related
i need to find a cookie name is available or not in the cookie string , i have achieved this, we can use cookie-parser but i don't want to use the package so i have written the below code ,can i reduce the code in a better way more optimised ?
function checkCookie(cookie, cookieToBeSearched){
if(cookie === "" || cookie === undefined){
return false
}
let res = cookie.split(";").some(cookie => {
let eachCookie = cookie.split("=");
return eachCookie[0].trim() === cookieToBeSearched
});
return res;
}
let cookie = "_ga=GA1.2.2091695351.1539084164; __qca=P0-338702612-1539084164095; __gads=ID=770d92bcdac8de40:T=1539084164:S=ALNI_MbsRKpoSJdn8tsdShMHMZUAR17uZA; _gid=GA1.2.798724103.1539582973";
console.log("Cookie is available - ", checkCookie(cookie, "_gid"))
console.log("Cookie is available - ", checkCookie(cookie, "_giddd"))
The regular expression is a nice solution.
function getCookie(name) {
var exp = new RegExp('[; ]'+name+'=([^\\s;]*)');
var matchs = (' '+document.cookie).match(exp);
if (matchs) return matchs[1];
return false;
}
Why don't you use
if (document.cookie.indexOf('cookie_name') > -1 ) {
//alert("cookie exists");
return true
}
Its simple!
You can avoid explicitly checking cookie value for "" and undefined. You can also splitting the string on =.
function checkCookie(cookie, cookieToBeSearched){
if(!cookie){
return false
}
let res = cookie.split(";").some(cookie => {
let cookieReg = new RegExp('^'+cookieToBeSearched+'=')
return cookie.trim().match(cookieReg)
});
return Boolean(res);
}
let cookie = "_ga=GA1.2.2091695351.1539084164; __qca=P0-338702612-1539084164095; __gads=ID=770d92bcdac8de40:T=1539084164:S=ALNI_MbsRKpoSJdn8tsdShMHMZUAR17uZA; _gid=GA1.2.798724103.1539582973";
console.log("Cookie is available - ", checkCookie(cookie, "_gid"))
console.log("Cookie is available - ", checkCookie(cookie, "_giddd"))
By converting the string as an object, we can use an Object/Hashmap to quickly find the corresponding value of key, rather than iterate over the array when we need to find the value of the key.
Therefore, we can leverage O(1) for finding in hashmap rather than O(N) by iterating over the array.
const cookies = (key, cookie = document.cookie) => {
if (!cookie) return;
return cookie.split(";").reduce((acc, item) => {
item ? acc[item.split('=')[0].trim()] = item.split('=')[1] : null;
return acc;
}, {})
}
cookies("key")
Datatype of stack id either can be an array or a string.
In the below code stack[0].id is Array and stack[1].id is string.
Issue is stackConfig is undefined when id is returned as array.
How do i handle this dynamically?
let stack = [{id:['stack1','stack2']},{id:'stack2'}]
let stackConfig = this.stackConfigs.find(c => c.id === selectionId);
You could try something like this:
let stack = [{id:['stack1','stack3']},{id:'stack2'},{id:'stack4'}]
let selectionId = 'stack2';
let stackConfig = stack.find(c => {
if(Array.isArray(c.id)) { if (c.id.indexOf(selectionId) != -1) return true;}
else { return c.id === selectionId }
return false;
});
console.log(stackConfig);
The first thing you should do is check whether c.id === selectionId is true at any point. This might never be true, hence why it is undefined.
You could try to handle having the selectionId also undefined as follows:
if (c.id.indexOf(selectionId) != -1) return true;
I would like test my Array (input value) before submit my form.
My array with value :
const fields = [
this.state.workshopSelected,
this.state.countrySelected,
this.state.productionTypeSelected,
this.state.numEmployeesSelected,
this.state.startAt
];
I've try this :
_.forEach(fields, (field) => {
if (field === null) {
return false;
}
});
alert('Can submit !');
...
I think my problem is because i don't use Promise. I've try to test with Promise.all(fields).then(());, but i'm always in then.
Anyone have idea ?
Thank you :)
The problem is that even though you're terminating the lodash _.forEach loop early, you don't do anything else with the information that you had a null entry.
Instead of lodash's _.forEach, I'd use the built-in Array#includes (fairly new) or Array#indexOf to find out if any of the entries is null:
if (fields.includes(null)) { // or if (fields.indexOf(null) != -1)
// At least one was null
} else {
// All were non-null
alert('Can submit !');
}
For more complex tests, you can use Array#some which lets you provide a callback for the test.
Live example with indexOf:
const state = {
workshopSelected: [],
countrySelected: [],
productionTypeSelected: [],
numEmployeesSelected: [],
startAt: []
};
const fields = [
state.workshopSelected,
state.countrySelected,
state.productionTypeSelected,
state.numEmployeesSelected,
state.startAt
];
if (fields.indexOf(null) != -1) {
console.log("Before: At least one was null");
} else {
console.log("Before: None were null");
}
fields[2] = null;
if (fields.indexOf(null) != -1) {
console.log("After: At least one was null");
} else {
console.log("After: None were null");
}
You do not need to use promises unless there is an asynchronous operation (for example if you are getting that array from your server).
If you already have that array you can do something like:
// Using lodash/underscore
var isValid = _.every(fields, (field) => (field!==null)}
// OR using the Array.every method
var isValid = fields.every((field)=>(field!==null))
// Or using vanilla JS only
function checkArray(array){
for(var i = 0; i < array.length ; i ++){
if(array[i]===null){
return false;
}
}
return true;
}
var isValid = checkArray(fields);
// After you get that value, you can execute your alert based on it
if(!isValid){
alert('Something went wrong..');
}
Try this simple snippet
var isAllowedToSubmit = true;
_.forEach(fields, (field) => {
if (!field) {
isAllowedToSubmit = false;
}
});
if(isAllowedToSubmit)
alert('Can submit !');
You can do that without library:
if (fields.some(field => field === null)) {
alert('Cannot submit');
} else {
alert('Can submit');
}
You don't need to use lodash, you can do this in simple vanilla javascript. Simply iterate over each field and if an error occurs set your errors bool to true
let errors = false;
fields.forEach(field) => {
if(field === null || field === '') {
errors = true;
}
});
if (!errors) {
alert('Yay no errors, now you can submit');
}
For an es6 you can use.
const hasNoError = fields.every((field, index, selfArray) => field !== null);
if (!hasNoError) {
alert('yay It works');
};
Have a look at Array.every documentation Array every MDN documentation
I'm currently trying to do some maths on my json data. But it's not doing what I want. I made a loop so the calculation apples to every row (by the way I work with angularJS)
Here's the part of my code where I'm trying to process the data :
angular.module('recordService', []).factory('recordService', ['$http', function($http) {
var url;
var recordService = [];
recordService.getAll = function(callback) {
url = "http://localhost/app/www/database/json.php";
$http({
url: url
}).then(function(rs) {
callback(rs.data);
function logArrayElements(element, index, array) {
var thdi = rs.data[index].THDI1_avg;
console.log(thdi + 5);
}
rs.data.forEach(logArrayElements);
}, function(err) {
console.log(err)
})
}
As you can see I trying to take one element from my array and add 5 to it (it's only a test; I want to do some more advanced math later). I can see in the console.log that's its not doing what I want.
For example, if my data is 10.25, I get 10.255 when I would like 15.25. Any ideas on what I'm doing wrong?
Thanks in advance
You need to convert the JSON data into a number as #epascarello has mentioned. JSON is serialized as strings.
function logArrayElements(element, index, array) {
var thdi = Number(rs.data[index].THDI1_avg);
console.log(thdi + 5);
}
The reason you get 10.255 is, because you are adding 5 to a string.
Try:
console.log(parseFloat(thdi) + 5);
Update regarding Not a Number:
There are a couple of ways you could check whether the value is a number.
isNaN()
if(isNaN(thdi)) {
console.log("Not a number");
} else {
console.log("Is a number");
console.log(parseFloat(thdi) + 5);
}
try / catch
try{
console.log(parseFloat(thdi) + 5);
} catch(err) {
console.log("not a number");
}
Edit: Won't give desired result.
typeof
if(typeof thdi === 'number') {
console.log("Is a number");
console.log(parseFloat(thdi) + 5);
} else {
console.log("not a number");
}
Also see: How do you check that a number is NaN in JavaScript?
Note: if thdi is undefined, then isNaN() will throw an error. typeof will be able to deal with undefined.
I'm trying to write a set of reusable functions to abstract a bunch of SharePoint's REST API web services which is probably unnecessary context but I always feel kind of weird framing these questions.
Anyway. The endpoints all take parameters and I've decided to feed the operation that does the AJAX call and handles the return a Javascript object (if there's a better way to do this, I'm still learning, totally open to suggestions) called "Options" that has as its properties the parameters, like so:
ApiHelper.prototype.getListData = function(options){
//Set the base endpoint Url.
var executeUrl = "/web/lists/getByTitle('"+options.list+"')";
//Determine if the URI will have parameters.
var params;
var paramList = [];
if(options.select.length || options.filter.length || options.expand.length || options.top.length){
params = true;
paramList.push(options.select,options.filter,options.expand,options.top);
}else{
params = false;
}
//The first two ops are super basic and don't take parameters, so I collapse them into a single line.
if(options.op == 'All'){return this.execute(executeUrl).then(function(data){if(data.d){return data.d;}else{throw "Something bad happened..."}});
}else if(options.op == 'Id'){executeUrl+='/Id';return this.execute(executeUrl).then(function(data){if(data.d){return data.d.Id;}else{throw "Something bad happened..."}});
}else if(options.op == 'Forms' || options.op == 'Views' || options.op == 'WorkflowAssociations'){
executeUrl+=options.op;
return this.execute(executeUrl).then(function(data){
if(data.d && data.d.results){
return new QueryResults(data.d.results);
} else {
throw "Something bad happened...";
}
});
}else{
if(params){
//No idea...
}else{
//If we're doing Items but without params...
executeUrl+='/items';
}
return this.execute(executeUrl).then(function(data){
if(data.d && data.d.results){
return new QueryResults(data.d.results);
} else {
throw "Something bad happened...";
}
});
}
For ease of use on the user, I wanted to make the parameters optional. Originally, I was doing something like this with the parameters:
if(typeof options.select === 'undefined'){options.select = '';}
if(typeof options.filter === 'undefined'){options.filter = '';}
if(typeof options.expand === 'undefined'){options.expand = '';}
if(typeof options.top === 'undefined'){options.top = '10000';}
And then constructing the URL with the parameters attached anyway, just empty. That... works, but it seems inelegant and with SharePoint, you know, I can never be sure it will work. So, my goal here is to look at the options object and if, for example, there's a select statement, then append $select=[whatever], but if not, then don't. Same for filter, expand, and top.
Don't forget to encode all the parts of the URL query
function param(obj) {
return Object.keys(obj).map(key => {
return [key, obj[key]].map(encodeURIComponent).join('=');
}).join('&');
}
You may also look at jQuery's $.param. It does basically the same and supports arrays. You can find the source here.
function getProps(obj){
var str='';
for(var prop in obj){
if(str)str+='&';
else str='?';
str+=prop+'='+obj[prop];
}
return str;
}
I hope this will help.