Postman get variable used in array find doesn't work - javascript

Using the newest version of Postman.
I have a predefined variable "useridToken" which is a number: 123456
var useridToken = pm.environment.get("useridToken");
//console.log(useridToken);
var jsonData = pm.response.json();
const user = jsonData.find(u => u.user_metadata.employeeId === useridToken);
const userid = user ? user.user_id : 'not found';
pm.environment.set("user_id", userid);
Whenever I run this code, it returns errors.
The console log output is the number as an integer: 123456
Whenever I run the following code:
var useridToken = 123456
var jsonData = pm.response.json();
const user = jsonData.find(u => u.user_metadata.employeeId === useridToken);
const userid = user ? user.user_id : 'not found';
pm.environment.set("user_id", userid);
It works like a charm, but I don't want the hardcoded useridToken in my code, I would like to get it from my environment variables. I don't quite understand why the first part isn't working? What am I overseeing?

This is happening because in your .find method you're using === comparison, and when you fetch from environment you always get it as a 'string' and not a 'number' (Postman always gives the value of the environment variable in the string format)
So when you use a === comparison in JS, it also checks the type of the data, here
string === number will actually be false and that's why your find doesn't work.
So, you need to update your code to actually parse the integer that you got from the environment.
This should fix your issue:
var useridToken = parseInt(pm.environment.get("useridToken"));

SOLUTION:
Since you are using === operator, it checks for the type of the variables too. The type for both operands might be different on certain scenarios. So, use the following to avoid the issue.
const user = jsonData.find(u => +u.user_metadata.employeeId === +useridToken); // converts to number then checks
or
const user = jsonData.find(u => u.user_metadata.employeeId.toString() === useridToken.toString()); // converts to string then checks
or
const user = jsonData.find(u => u.user_metadata.employeeId == useridToken); // checks without the operands type. (not recommended)

Related

Using mentions and ID commands for user [Discord.js]

Can someone help? I wanted my commands to be able to be used with #olios or 49556804 *** 0471817. I don't know what I'm doing wrong but my code isn't working.
let userLevel = mentions.users.first () || msg.guild.members.cache.get (args [0]) || msg.author
const userLevelID = userLevel.id
const userLevelName = userLevel.user.username
And I get something like this from the console:
TypeError: Cannot read property 'username' of undefined
Can it be done at all, or it worked on mentions and ID?
While both msg.mentions.users.first() and msg.author return a User, msg.guild.members.cache.get(args[0]) returns a GuildMember. Both User and GuildMember have an id property, but only GuildMember has a user.
If you try to get the user from a GuildMember, you will be fine, but you will always receive a TypeError if you try to get it from a User.
You can update your code to get the user from message.guild.members.cache.get(args[0]) only. I used optional chaining (?) to ignore it if there is no args[0] and fall back to msg.author.
The following will work with all three cases:
let userLevel =
msg.mentions.users.first() ||
msg.guild.members.cache.get(args[0])?.user ||
msg.author;
const userLevelID = userLevel.id;
const userLevelName = userLevel.username;
console.log({ userLevelID, userLevelName });
Optional chaining requires Node.js v14+. If you have an older version you can use a simple AND operator:
let userLevel =
message.mentions.users.first() ||
(message.guild.members.cache.get(args[0]) &&
message.guild.members.cache.get(args[0]).user) ||
message.author;

Split out props.location.search value

I'm trying to split out the values from props.location.search in React/Redux. I've successfully obtained the mixOne split however I can't seem to return the value of quantity. Here's my code:
const mixOne = props.location.search
? String(props.location.search.split("mixOne=")[1])
: "None";
const quantity = props.location.search
? Number(props.location.search.split("=")[1])
: 1;
And here's the URL that gets generated:
const addToCartHandler = () => {
props.history.push(
`/Cart/${productId}?quantity=${quantity}?mixOne=${mixOne}`
);
};
As you can see quantity returns null, when I need the value selected
props.location.search.split("=") on "?quantity=1?mixOne=Grape" would return [ '?quantity', '1?mixOne', 'Grape' ] since the next = is not until after mixOne.
There's a few different fixes here.
Your query string is invalid– a ? denotes the start of the query string. Separate parameters should be split up using & ampersand characters. It should look like this: ?quantity=1&mixOne=Grape
If you follow the standard here, you can then split it two ways: by = and then by & to get the different parameters. However, there is an easier way.
Using the new-ish URLSearchParams API, you can parse your parameters in a predictable way:
// Use the constructor with your `props.location.search`
const queryParams = new URLSearchParams(props.location.search);
// Use the getters to grab a specific value
const quantity = queryParams.get("quantity");
// Ensure it's a number for safety
const quantityNum = Number(quantity);
// ... the rest of your code here
The query is wrong. You're using double question marks. The second ? should be replaced with &.
?quantity=1&mixOne=Grape

Skipping undefined elements from an API call

I am gathering data from an API to show the Pokemon typing. Some Pokemon have one type, while others have two.
The variables to gather the typing data are as such.
function createPokemonCard(pokemon) {
const type = pokemon.types[0].type.name;
const second_type = pokemon.types[1].type.name;
...}
And then I call them via InnerHTML in the same function with the following code.
<small class="type"><span>${type}/${second_type}</span></small>
Predictably, when it hits undefined for a Pokemon, it breaks and doesn't display the card. However I am not sure how to get it to not print the second type when it's undefined.
I thought about doing an if statement, but what should I call if there is an undefined variable?
function undefined {
if(second_type === 'undefined') {
???
}}
Or would a for loop work better? I am not sure how to get it to bypass the undefined and print nothing.
const second_type = pokemon.types[1] ? pokemon.types[1].type.name: undefined;
`<small class="type"><span>${type}${second_type!=undefined ? `/${second_type}`: ''}</span></small>`
The ? : syntax is a ternary operator (mdn)
It's a less verbose way of writing out the following:
if (second_type!=undefined) { // check if second_type is not undefined
return `/${second_type}` // if it's not return / and the second type
} else { //otherwise
return '' // return an empty string
}
If you do not want to display the trailing / when second_type is not defined one way to go could be
const type = pokemon.types.map(({ type }) => type.name).join("/")
and then
<small class="type"><span>${type}</span></small>

Discord - showing member join position with specified number

I want to show you which number of users I entered in the argument is the order of joining the server. Like = when i use .join 1 I want to show the 1st member join in to the server. I use
let arr = message.guild.members.filter(a => !a.user.bot).array().sort((b, a) => b.joinedTimestamp - a.joinedTimestamp)
let map = arr.indexOf(sesmi) + 1
this command for showing joing position but im so confused how can i do as i said?
Try this:
// if the first argument is not a number (this message is kind of bad so you can change it)
if (isNaN(args[0])) return message.reply('you must specify what number user you want to get!')
const members = message.guild.members.cache
.filter(member => !member.user.bot)
// sorted is a member on Discord's utility class Collection that doesn't modify the original collection
.sorted((a, b) => a.joinedTimestamp - b.joinedTimestamp)
.array()
// the number user to get
const n = Number(args[0])
// if there are not enough members
if (n > members.length) {
// You only really need this if there is ever going to be only 1 member in the server
// and if you care about grammar. You could also just do
// return message.reply(`there are only ${members.length} members!`)
const plural = members.length !== 1
return message.reply(`there ${plural ? 'are' : 'is'} only ${members.length} member${plural ? 's' : ''}!`)
}
message.channel.send(members[n - 1].user.tag)
I'm assuming args will be an array of strings with the arguments passed into the command (e.g. .join 1 will have the args ['1'].

Recursicely call data in a mongodb with node

I am creating a login system and i want to implement a username system automatically after registration with the user first-name and last-name. Everything is working fine but in the case if the registered user with the same first-name and last-name is already in the system i want to concatenate a incrmental number to it.
Example if : firstname:Badmus Lastname:Kabiru is in the system as badmus.kabiru and the newly registered user is also named so the new user username will be badmus.kabiru.1 the next will be badmus.kabiru.2.
My code sample are.
assignUserTrendname: function(req_username, callback){
let userNewname = fetchUserName(req_username);
let inc = 1, newlyAssignUsername;
userNewname.then((usernames) => {
console.log(req_username+" ...................... "+usernames); //The data from the database is loging out
if (usernames.atusername == null || usernames.atusername == undefined) {
newlyAssignUsername = req_username;
console.log("Assign automaticaly "+ newlyAssignUsername);
} else {
newlyAssignUsername = req_username;
console.log(`Username Result is DB: ${usernames.atusername} Req: ${newlyAssignUsername} Search ${inc}`);
if(usernames.atusername.toString() == newlyAssignUsername.toString()){
console.log("User name exit and inc is "+ inc);
inc++;
newlyAssignUsername = `${req_username}.${inc}`;
console.log("New search..."+ newlyAssignUsername);
fetchusernames(newlyAssignUsername); // These is not fetching from the database
}
newlyAssignUsername = `${req_username}.${inc}`;
}
console.log("Assigned is ......"+ newTrendname);
callback(null, newTrendname);
})
.catch((err)=> {console.log(err); throw err;});
}
function fetchUserName(trendname){
return Trender.getUserByTrendname(trendname);
}
If i am taking the wrong route please let me know.
Thanks.
In the scenario that your.username already exists you can search your Users with a regex pattern: ((?:your\.username)\d+$). This will get all records that match: your.username{num} where {num} is any number. If your username's are formatted as your.username.123 the pattern would be: ((?:your\.username\.)\d+$).
Assuming this returns an array, existing_users, you can count the records, since you'll always be incrementing by one, which will give you your next incremented number. Pseudo code:
let inc = existing_users.length + 1;
However, in the scenario that you delete a user your count is going to be off. You would need to loop over your existing_users and extract the number at the end and only keep the largest number.
let largest_num = 0;
existing_users.forEach(user => {
let num = user.match(/\d+$/);
if ( num != null && parseInt(num[0]) > largest_num ) {
largest_num = num[0];
}
});
Then you could do the same as above: let inc = largest_num + 1 and add that to your your.username string.
I do not know what library/framework you're using to search your MongoDB so I cannot write a query and function snippet.
We cannot write your code for you. A general regex has already been given that could be a potential way to solve your problem. If you go that route you can make use of the $regex operator. If you were to store the increment of the username as a separate field you could also sort by that to get the max value as well.
Here is an example of that:
db.users.find({
username: {
$regex: < Your Regex Here >
}
}).sort({
usernameIncrement: -1
}).limit(1);
Please see:
http://mongoosejs.com/docs/queries.html
https://docs.mongodb.com/manual/reference/operator/query/regex/
https://docs.mongodb.com/manual/reference/method/cursor.sort/

Categories