How to make query parameter values case-insensitive - javascript

I want an endpoint that is a GET method to /book with a query parameter called name. If the name is 'scott', I want to return "Cracking the Coding Interview," but if it's 'SCOTT,' I want to do the same thing. Why does this not work?
app.get('/book', function (req, res) {
let result = ''
const name = req.query.name.toString().toLowerCase()
if (name === "scott") {
result = "Cracking the Coding Interview"
} else if (name === "enoch") {
result = "The Pragmatic Programmer"
} else {
result = "Good Old Neon"
}
res.send(result);
});

req.query.name could be undefined, and so we must unwrap it to access that value; search up "swift optionals" if this terminology is confusing.

Related

JS: Cannot search for two parameters - async gives back only the first parameter

I am trying for a day now and cannot solve this problem:
I have a website where I can add contacts to a SQLite database. I want to query the database by studentID or nachname (this means last name). I have an API endpoint which seems to be working and a getContact function which only works for the first parameter. In this case it only searches for studentID and if I change the order I can only get my data by nachname.
For now I just want to display the response simply at the URL localhost:8000/api/contacts/studentID or /nachname to see the json response.
I tried this getContact function:
async getContact(**studentID, nachname**) { //here only the first parameter works
let result = [];
let query;
let params = [];
if (studentID && !nachname) {
query = "SELECT * FROM contacts WHERE studentID = ?";
params.push(studentID);
} else if (nachname && !studentID) {
query = "SELECT * FROM contacts WHERE nachname = ?";
params.push(nachname);
} else if (studentID && nachname) {
query = "SELECT * FROM contacts WHERE studentID = ? OR nachname = ?";
params.push(studentID, nachname);
}
result = await new Promise((resolve, reject) => {
db.all(query, params, (error, row) => {
if (error) {
reject(error);
} else {
resolve(row);
}
});
});
return result;
}
My API endpoint (setup with Express.js in Node.js) looks like this currently:
app
.get("/api/contacts/:studentID?/:nachname?", async (request, response) => {
const studentID = request.params.studentID;
const nachname = request.params.nachname;
console.log(request.params.studentID);
console.log(request.params.nachname);
const contact = await contactsManager.getContact(studentID, nachname);
if (contact) {
response.status(200).send(contact);
} else {
response.status(404);
}
})
I don't understand why the getContact function only works with the first parameter.
One strange thing I recognized: Right now I could search for localhost:8000/api/contacts/1 and would see the right entry, and when I add .../contacts/1/Behrens I see the entry with the ID 1 and also the entries of the people named Behrens. Maybe this information helps?
The issue is that in your getContact function, you are using the ** operator in front of studentID and nachname, which is causing them to be treated as keyword arguments instead of regular arguments. As a result, the function is only able to identify and use the first argument passed to it, while the second argument is ignored.
To fix this, you should remove the ** operator from the function definition so that the function takes in two regular arguments:
async getContact(studentID, nachname) {
// ...
}
Also, you can use SELECT * FROM contacts WHERE studentID = ? AND nachname = ? instead of SELECT * FROM contacts WHERE studentID = ? OR nachname = ? if you want to check the both parameter are exist in the database.
Also, you should check for the existence of the parameters in the API endpoint before passing them to the getContact function, otherwise, you may end up passing undefined values to the function which will cause an error.
app.get("/api/contacts/:studentID?/:nachname?", async (request, response) => {
let studentID = request.params.studentID;
let nachname = request.params.nachname;
if(!studentID) studentID = null;
if(!nachname) nachname = null;
console.log(studentID);
console.log(nachname);
const contact = await contactsManager.getContact(studentID, nachname);
if (contact) {
response.status(200).send(contact);
} else {
response.status(404);
}
})
Also, you can use only one parameter in the endpoint and use if-else statements to check which parameter is passed and then act accordingly in the function.
app.get("/api/contacts/:param?", async (request, response) => {
let studentID = request.params.param;
let nachname = request.params.param;
if(studentID.match(/^\d+$/)){
studentID = request.params.param;
nachname = null;
}else{
studentID = null;
nachname = request.params.param;
}
console.log(studentID);
console.log(nachname);
const contact = await contactsManager.getContact(studentID, nachname);
if (contact) {
response.status(200).send(contact);
} else {
response.status(404);
}
})
This should fix the issue with the getContact function only working with the first parameter, and allow you to query the database by both studentID and nachname.

How to solve TypeError: result.select is not a function in a Node.JS, Express JS and MongoDB App

I am creating a store API.
I am trying to filter out the result using the field from req.query and select. Everything else works fine except the select.
Error: TypeError: result.select is not a function
if (field) {
const sortField = field.split(",").join(" ");
result = result.select(sortField);
}
Not sure why is the select not a function.
From the image, looks like result is a unresolved promise when you call the select.
Also, there's no select method for an array (witch I believe, is what you're trying to filter out); instead you can use filter
Try this:
let newResult;
if (field && result) {
const sortField = field.split(",").join(" ");
newResult = result.filter(x=> x === sortField);
}
Try with:
let products;
if (field) {
products = await product.find(queryObject).select(field.split(',').join(' '));
} else {
products = await product.find(queryObject);
}
res.status(200).json({ products, number: products.length });

How to check if a variable is a number discord.js

I'm fairly new to discord bots coding and I would like to check if a variable is a number. My code looks like this, I've tried many options for the "if" statement.
const { DiscordAPIError } = require('discord.js');
const Discord = require('discord.js');
module.exports = {
name: 'givecookies',
description: 'Gives cookies to the mentioned user',
execute(message, args) {
let User = message.guild.member(message.mentions.members.first());
if (!User) return message.channel.send('Invalid User');
var cookiesAmount = args.join(' ').slice(22);
if (!cookiesAmount) {
message.reply('invalid amount of cookies');
}
if (typeof `${cookiesAmount}` === 'number') {
console.log('Amount of cookies is a number');
console.log(`USER = ${User}`);
console.log(`Amount of cookies = ${cookiesAmount}`);
var UserID = User.id;
console.log(`USER ID = ${UserID}`);
} else {
message.reply('invalid amount of cookies');
console.log('Amount of cookies is not a number');
console.log(`USER = ${User}`);
console.log(`Amount of cookies = ${cookiesAmount}`);
var UserID = User.id;
console.log(`USER ID = ${UserID}`);
}
},
};
I've also tried if (typeof(cookiesAmount) === 'number') and if (typeof cookiesAmount === 'number'), but none of them worked. Regardless what the value is, it acts like if it wasn't a number. I made it to log the value of cookiesAmount and it is always right, it logs '5', but it acts like if it wasn't a number. Any ideas of how to fix this? Thanks.
I'm using discord.js version 12
Since you are taking the variable from a Discord message, it will always be a string. However, you can convert it using the + operator.
var cookiesAmounts = 'notANumber';
if (Number.isNaN(+cookiesAmounts)) console.log('This is not a number');
else console.log('This is a number')
var cookiesAmounts = '1';
if (Number.isNaN(+cookiesAmounts)) console.log('This is not a number');
else console.log('This is a number')
JSFiddle
First, this is more of a JS question (it is not Discord specific). The reason it always returns false is that all the args are strings. You should convert the string to a number using the parseInt (or parseFloat) function and check if the result is NaN to know if it is a valid number.
If there is anything unclear with my answer, just ask me a question in the comments

validate multiple variables without writing multiple if else statements

Lets say we have 3 variables and I want to check them empty or not without using multiple if else blocks.
let firstName = "adem"
let lastName = "corona"
let email = "adamcorons#gmai.com"
If(firstName === " " && lastName !== " " && email !== " "){
Console.log("first name empty")
} else if .......
What is the best way of solving this?
Thanks a lot
You can avoid chained if-else stataments by returning directly from an if statement. For example, you can have a function such as this one:
function isInputValid({ firstName, lastName, email }) {
if (firstName === '') {
return false;
}
if (lastName === '') {
return false;
}
if (email === '') {
return false;
}
return true;
}
console.log(isInputValid({ firstName: 'adem', lastName: 'corona', email: 'adamcorons#gmai.com' }));
console.log(isInputValid({ firstName: 'adem', lastName: '', email: 'adamcorons#gmai.com' }));
Instead of a boolean value, you could also return an object containing an error message, so you can point out which field is missing.
You could try looping over a required array of fields like this to make it short and flexible:
const validate = (values, required) = {
let errors = {}
required.map(field => {
if (values[field] == '') {
errors[field] = 'Required';
}
}
return errors;
}
const required = ['firstName', 'lastName', 'email'];
const values = {
firstName = '',
lastname = 'test',
email = ''
}
const errors = validate(values, required);
console.log(errors);
// errors = { firstName: 'Required', email: 'Required' }
Making the values an object instead of individual parameters makes it possible to access them dynamically in a loop. This might work depending on what your needs and requirements are.
Then to check if errors exist, just see if the size of the object is 0 by converting it to an array:
if (Object.keys(errors).length == 0) {
// No errors, continue as valid
} else {
// There are errors, handle them as needed.
}
Another great way is to use YUP. It is possible to provide validation anywhere. I always use it. Here is an example.
const schema = Yup.object({
last_name: Yup.string()
.when('first_name', {
is: true,
then: Yup.string().required().label("Last Name"),
}),
});
You can use a similar as following. It also has many other amenities. You can find all the information from the official website below.
https://github.com/jquense/yup
I guess you can try something like this
// declare vars where you should, and add the vars you want to test in an object
let result = [];
let toTest= {
firstName = "adem",
lastName = "corona",
email: "adamcorons#gmai.com",
}
// declare this function to test your values
function testValue(){
Object.keys(toTest).map(key => {
if(!toTest[key]){
result.push(key);
}
}
}
// where you need, call your function to test your strings
testValue();
// in your result array you will have the keys of all the empty vars in your object
Note: if its for field validation you have some plugins like Yup(if Formik) or validate.js that are great for it ! have a look ! https://validatejs.org/
EDIT: Changed the response to an array so you can have all the results. I recommande you to set result as an object {key: errorMessage, ...} so its easier for you to use him after (ex: call the error.nameOfInput in your form to display the error.
EDIT2:
With object result would look like this
// declare vars where you should, and add the vars you want to test in an object
let error= {};
let toTest= {
firstName = "adem",
lastName = "corona",
email: "adamcorons#gmai.com",
}
// declare this function to test your values
function testValue(){
Object.keys(toTest).map(key => {
if(!toTest[key]){
error[key]={`${key} cannot be empty`};
}
}
}
// where you need, call your function to test your strings
testValue();
// in your render
<input name="firstName" ...props />
{error.firstName && <div className='error'>{error.firstName} </div> }
I believe you can't achieve this with plain if like in your example. You would need to have a validation schema and function that you run to validate, like most libraries do it. So you would need have some kind of initial object that couples the field names, their rules and error messages. But then you would need to use object with properties instead of plain variables. With those you cannot avoid checking them without separate if statements.
For reference check how joi or yup works. Although I do understand that using one of those might be too much for you, so I'd just check each field separately.

How to run a javascript function that checks if a username is available

I'm building a javascript function that receives an input and checks it against stored objects in an array to see if it matches against any
The if else statement don't work
const accounts = []; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
let match = (toMatch) => toMatch === newuser.username
if (accounts.some(match) === true) {
return alert("choose another `username");
}
accounts.push(newuser)
return alert("account created")
};
var clik = document.getElementById("login").addEventListener("click", getinput);
It should tell the user if a username is available or not
The direct answer to your question would be along the lines of:
function getInput() {
/* store the value of the input */
var current_userName = document.getElementById("username").value;
/* check if that value already exists in the accounts Array */
var matched = accounts.find(account => account.username === current_userName);
/* conditional for each of the two cases */
if (!matched) {
/* code if username is available */
} else {
/* code if username is NOT available */
}
};
document.getElementById("login").addEventListener("click" , getInput);
You have some mistakes in your code, which need fixing.
Also, look into Array.prototype.find() for more info.
Hope this will help you get started in the right direction. Best of luck!
Finally understood what I was doing wrong had to point toMatch of accounts to check for username contained within the array of object
const = [ ]; //holds all user name and password
function getinput() {
let pass = document.getElementById("password").value;
let user = document.getElementById("username").value;
let newuser = {
username: user,
password: pass,
};
//this was where I got it wrong I was doing toMatch === newuser.username which was wrong
let match = (toMatch) => toMatch.username === user
if (accounts.some(match) === true) {
return alert("choose another username");
}
accounts.push(newuser)
return alert("account created")
};
document.getElementById("login

Categories

Resources