I made a blog in which a user can only edit it the blogs they created. But now I want to make an admin that can edit and delete any post he wants.
if(foundBlog.author.id.equals(
req.user._id ||
foundBlog.author.username === "ADMIN"
)) {
next();
} else {
res.redirect("back");
}
But my code doesn't work.
equals() is not a valid String function except you have implemented this yourself. If you haven't and want to, you could do something as simple as
String.prototype.equals = function(str){
return this.toString() === str;
}
and then
"hello".equals("hello") // gives true
"hello".equals("kitty") // gives false
However, I would advice against poisoning the prototype of a well-known/built-in object or any shared global space for that matter cause that is a recipe for disaster.
With that said, I'll just go for the strict equality comparison.
if(foundBlog.author.id === req.user._id || foundBlog.author.username === "ADMIN")
No harm no foul.
Related
Is there a way to check to variable in localstorage ?
Storage {user: 'undefined', new: '{"_id":"61dd228336a3923d2286b994","email":"ahmadsa…","updatedAt":"2022-01-11T06:24:03.675Z","__v":0}', lscache-localhost:preview:v20180702-cacheexpiration: '27376332', lscache-localhost:preview:v20180702: '{}', length: 4}
And sometimes the data may be on the user property base on user login . below is the login that returns the property in user
Storage {user: '{"team_members":{"memberFullname1":"memberFullname…","updatedAt":"2022-01-10T01:43:30.288Z","__v":0}', new: 'null', length: 2}
How can I create condition that checks both property an only return the ones that contain a value ?
Base on user log in, I can only use one variable either new or user. Is there not away I can check two conditions before rendering my data from localStorage ?
This is the Method I try. But it only check the first condition even though the second condition is there, it return. Uncaught error in Json.parse()
if (typeof Storage !== "undefined") {
if (localStorage.getItem("new")) {
setUser(JSON.parse(window.localStorage.getItem("new")));
} else if (localStorage.getItem("user")) {
setUser(JSON.parse(window.localStorage.getItem("user")));
}
return;
}
Is there a way I can check both condition ? Your time is really appreciated. please I am a brother need..
And lastly how can I prevent re-rendering of the state
If user undefined, do new, if that's undefined, do {}, parse.
if (typeof Storage !== "undefined") {
setUser(JSON.parse(localStorage.user || localStorage.new || '{}'));
}
Though, if you look at new, it's not the same as user, in terms of structure so you might want to fix that else they are not the same thing.
I found these code allows me to check both conditions and it didn't return error like the previous one.
useEffect(() => {
const fetchStates = async () => {
const result = await axios(
"https://nigerian-states-info.herokuapp.com/api/v1/states"
);
setStates(result.data.data);
};
fetchStates();
if (localStorage.user === "undefined") {
return setUser(JSON.parse(localStorage.getItem("new")));
} else if (localStorage.new === "undefined") {
return setUser(JSON.parse(localStorage.getItem("user")));
}
}, [formData, user]);
Finally after a bunch of try and error, I finally arrived at that part. I want to sent my sincere appreciation to all those who took there time and review my issues even those that did not get to answer. I send A BIG THANK YOU especially to lawrence cherone your idea was a great helpful in shaping my thought. thank you all
I am returning a number from a php call. The console is printing the number correctly when I return the value in a subscribe function. When I try to run an if statement to act on the return I am receiving an error in my code that I don't know how to fix. I looked around, but couldn't find any answers to this problem.
This is all happening inside of a subscribe function. I can't refer to the variable accountStatus outside of the subscribe.
this.apiService.checkAccountStatus().subscribe((accountStatus)=>{
console.log("user account", accountStatus);
if(accountStatus = 0)
{
//account doesn't exist
console.log("user doesn't exits.", accountStatus);
}
if(accountStatus = 1)
{
//account does exist
console.log("user does exist.", accountStatus);
}
})
Debugging Errors I am receiving:
Type 'number' is not assignable to type 'Account_Info'.ts(2322)
Account_Info is the name of the ts file I am using to access the database. In my apiService.checkAccountStatus() function this is what it looks like:
checkAccountStatus(){
return this.httpClient.get<Account_Info>(`${this.PHP_API_SERVER}/api/checkaccount.php`, {withCredentials: true});
}
Any advice is welcome. Thank you!
this.apiService.checkAccountStatus().subscribe((accountStatus:any)=>{
console.log("user account", accountStatus);
if(accountStatus = 0)
{
//account doesn't exist
console.log("user doesn't exits.", accountStatus);
}
if(accountStatus = 1)
{
//account does exist
console.log("user does exist.", accountStatus);
}
})
you need to define type of accountStatus like in above code i define accountStatus:any ,use this code and let me know if it work
If Account_Info is an interface, it, indeed, is not a number. You can log it to the console because you can log anything. You cannot check for a type Account_Info to be a number in TypeScript. Also in the if clause, you are assigning, not comparing the values. You have to use the following:
//...
if(+accountStatus == 0) console.log("user doesn't exist", accountStatus)
else if(+accountStatus == 1) console.log("user does exist.", accountStatus);
//...
The reason for prepending a plus before accountStatus is that the Unary operator + in JavaScript attempts to convert the value that follows it to be a number. More info: Unary Plus on MDN
N.B.: This only ever works if the value is indeed a number. Else, +accountStatus will be NaN(not a number).
First, change type of observable.
checkAccountStatus(){
return this.httpClient.get<number>(`${this.PHP_API_SERVER}/api/checkaccount.php`, {withCredentials: true});
}
Then, set the type on subscriber and also, be careful, you are assigning instead of comparing.
this.apiService.checkAccountStatus().subscribe((accountStatus:number)=>{
console.log("user account", accountStatus);
if(accountStatus === 0) // you have (accountStatus = 0)
{
//account doesn't exist
console.log("user doesn't exits.", accountStatus);
}
if(accountStatus === 1) // you have (accountStatus = 1)
{
//account does exist
console.log("user does exist.", accountStatus);
}
})
I have a home SPA based on Vue. One of the components is driven by a v-if="isDisplayed".
This isDisplayed is set by listening to a MQTT topic (see footnote) and new messages received are handled by the following function (I sepcifically used 'hello' instead of false to make sure the switch goes there). The topic of interest is display_school_edt.
mqttMessage(topic, message) {
console.log(`App.vue received topic ${topic} with payload '${message}'`)
if (topic === "dash/reload") {
window.location.href = window.location.href
document.location.reload(true);
}
if (topic === "dash/darkmode") {
this.nightmode = JSON.parse(message) ? "night" : "day";
}
// this is the part I have problems with, I left everything for completness
if (topic === "display_school_edt") {
console.log(`edt display received: '${message}'`);
if (message === 'on') {
this.isEdtDisplayed = true
} else {
this.isEdtDisplayed = 'hello'
}
// I initially went for the ternary below - same results
// message === "on" ? this.isEdtDisplayed = true : this.isEdtDisplayed = 'hello';
console.log(`new edt display: ${this.isEdtDisplayed}`);
}
}
When I publish to the monitored topic display_school_edt (twice: one the message is on and the other time off), here is what I get on the console:
In other words, no matter if on or off is received, the condition is always false.
There is something obviously wrong with my code but the more I look, the better it looks.
Footnote: the fact that it is that specific protocol does not matter (it is a kind of bus often used with IoTs), you can assume that somehow mqttMessage() is executed with the parameters topic and message that are both strings.
This is indeed unexpected if message is of type string. However, it probably is not, and the only times you output message, you actually coerce it to string. So if you see from a previous output that it coerces to "no", then in the if condition you should do the same, and force that conversion to string:
if (message+'' === 'no')
NB: This will call message.toString(), just like it does when you reference it within a template literal as ${message}.
I want to make a switch for discord.js, where a mentioned role gets removed when the user already has it, and if he doesn´t have it, it gets attached. So the code here is
let tempRole = message.guild.roles.find("name", args);
if(message.member.roles.has(tempRole)) {
console.log(`User has the role`);
}
args is the array for the command params, like "!role [role name with spaces]"
So if I have the role "Test", and I type "!role Test" it outputs "User has the role"
so how is the code for the opposite, if the user doesn´t have the role?
Because
else if(message.member.roles.has(!tempRole)) {
console.log(`User has not the role`);
}
isn´t really working, but the '!' is the only thing i know to negate the result
The ! operator negates whatever is found on the right side, in your case you are only negating the tempRole, however what you really want is to negate the result of the has call, like this:
!message.member.roles.has(tempRole)
Nonetheless since there is already an if statement verifying if the user has the role you could just use else
let tempRole = message.guild.roles.find("name", args);
if(message.member.roles.has(tempRole)) {
console.log(`User has the role`);
} else {
console.log(`User has not the role`);
}
Or even shorter with the ternary operator
message.member.roler.has(tempRole)
? console.log('User has the role')
: console.log(`User has not the role`);
I am making a script in Javascript script that gets a SQL response, then processes it. Basically, I want to check if the username value exists in result[1]. When it checks, it errors out and says that it does not exist. If it does not exist, I want it to return false, not stop the program.
Here is the code:
if (result[1].username != undefined) {
return true;
} else {
return false;
}
I have tried using typeof(result1) == undefined, but it gives me the same error.
First, you have to make sure the result exists, otherwise you'd be indexing into undefined which would crash your application.
Second, you can make that check less verbose with:
return (result[1] && result[1].username)
which will return a falsey value if it doesn't exist, and whatever the username is, if it does.
In case you need an explicit true to be what the function returns, you can coerce it:
return (result[1] && (result[1].username && true))
I would make sure to refactor for readability, but that's the gist.
You could use the in operator. For example:
let trueObj = { username: 'Foo' };
let falseObj = { };
if ('username' in trueObj) {
console.log('username found in trueObj');
} else {
console.log('username not found in trueObj')
}
if ('username' in falseObj) {
console.log('username found in falseObj');
} else {
console.log('username not found in falseObj')
}
First of all please check whether the result itself exists or not and make the corresponding & operator and i think this will definitely help
if (result && result[1] && result[1].username) {
return true;
} else {
return false;
}
But if you don't want to make your code complex then you can try lodash library.
https://lodash.com/