Non-admin User checkout (Create Order) -- Product is not defined - node.js

I am a webdev student trying to create an Ecommerce -API with Node and Express JS connected with MongoDB but I am getting this return in postman : "Product is not defined" in my Non_Admin Checkout function.
I don't really know what my mistakes are. Can you help me?
Here are my codes:
UserController
module.exports.checkout = async (data) => {
try{
let is_user_updated = await User.findById(data.userId).then((user) => {
user.orders.push({productId: data.productId})
return user.save().then((updated_user, error) => {
if(error){
return false
}
return true
})
})
}catch(err){return err.message}
try{
let is_product_updated = await Product.findById(data.productId).then((product) => {
product.orders.push({userId:data.userId})
return ordered.save().then((updated_product, error) => {
if(error){
return false
}
return true
})
})
}catch(err){return err.message}
if(is_user_updated && is_product_updated){
return {
message: 'User checkout is successful!'
}
}
return {
message: 'Something went wrong.'
}
}

Related

telegraf how to check if user is admin?

i have this code:
function isAdmin(idOfChat, IdOfUser, ctx) {
//function
return isAdminBoolean
}
bot.command("test", ctx => {
if (isAdmin(ctx.message.chat.id, ctx.message.from.id) == true) {
ctx.reply("Admin")
}else{
ctx.reply("._.")
}
})
how to make it work?
sorry for my bad English)))
You should re-write your method as a promise (because Telegraf queries from Telegram API, so, your isAdmin method could be like this)
function isAdmin(idOfChat, IdOfUser, ctx) {
return new Promise((resolve, reject) => {
//Get user information first
ctx.telegram.getChatMember(idOfChat, IdOfUser).then((user) => {
//Then check if user is admin (or creator)
resolve(user.status == "administrator" || user.status == "creator");
})
.catch((error) => {
//Reject if it's an error
reject(error);
});
});
}
Then, for use it into your main function, you should have to handle it like this:
bot.command("test", ctx => {
isAdmin(ctx.message.chat.id, ctx.message.from.id, ctx).then((result) => {
if (result) {
ctx.reply("Admin");
} else {
ctx.reply("._.");
}
})
.catch((error) => {
ctx.reply("An error has ocurred trying to get user rank: " + JSON.stringify(error));
});
});

Firebase function not returning value

I am trying to do some operations using oncall function where,
I am first checking if user exists in database, then if he exists then do some operations like updating the DB.
well the function is working as expected and updating the DB as well, but its returning response as null so I can't tell what exactly happening.
exports.populateCart = functions.https.onCall((data, context) => {
const user = context.auth.uid;
DB.collection('users').doc(user).get().then((usr_resp) => {
if (usr_resp.exists) {
DB.collection('products').doc(data.productKey).get().then((prod_res) => {
DB.collection('carts').add({
//some data
}).then(() => {
return {
response: 'CART UPDATED'
};
}).catch((carts_err) => {
return {
response: 'ERROR WHILE POPULATING CART : ' + carts_err
}
});
}).catch((prod_err) => {
return {
response: 'ERROR WHILE FETCHING PRODUCT : ' + prod_err
};
});
}
else {
return {
response: 'USER DOES NOT EXISTS OR USER NOT AUTHENTICATED'
};
}
}).catch((usr_err) => {
return {
response: 'ERROR WHILE FETCHING USER : ' + usr_err
};
});
});
There is one more similar question on stack overflow, where the solution is proposed to use,
reject(err);
resolve(lists);
methods, Please if the solution is using above methods, then please explain the use cases of this method in detail and if there are more methods like this please explain them as well.
Firebase function not returning data
You need to return every promise that you are running:
exports.populateCart = functions.https.onCall((data, context) => {
const user = context.auth.uid;
return DB.collection('users').doc(user).get().then((usr_resp) => {
if (usr_resp.exists) {
return DB.collection('products').doc(data.productKey).get().then((prod_res) => {
return DB.collection('carts').add({
//some data
}).then(() => {
return {
response: 'CART UPDATED'
};
}).catch((carts_err) => {
return {
response: 'ERROR WHILE POPULATING CART : ' + carts_err
}
});
}).catch((prod_err) => {
return {
response: 'ERROR WHILE FETCHING PRODUCT : ' + prod_err
};
});
}
else {
return {
response: 'USER DOES NOT EXISTS OR USER NOT AUTHENTICATED'
};
}
}).catch((usr_err) => {
return {
response: 'ERROR WHILE FETCHING USER : ' + usr_err
};
});
});
Try copying the above code. Also using async functions will make it look better like this:
exports.populateCart = functions.https.onCall(async (data, context) => {
try {
const usr_resp = await DB.collection('users').doc(user).get()
if (!usr_resp.exists) throw new Error("USER DOES NOT EXISTS OR USER NOT AUTHENTICATED")
const prod_res = await DB.collection('products').doc(data.productKey).get()
await DB.collection('carts').add({ . someData . })
return { response: "Cart Updated" }
} catch (e) {
console.log(e)
return { response: e }
}
});
You are not returning your promise. (see line 3 below)
exports.populateCart = functions.https.onCall((data, context) => {
const user = context.auth.uid;
// add return here before Db.collection()
return DB.collection('users').doc(user).get().then((usr_resp) => {
if (usr_resp.exists) {
return DB.collection('products').doc(data.productKey).get().then((prod_res) => {
return DB.collection('carts').add({
//some data
}).then(() => {
return {
response: 'CART UPDATED'
};
}).catch((carts_err) => {
return {
response: 'ERROR WHILE POPULATING CART : ' + carts_err
}
});
}).catch((prod_err) => {
return {
response: 'ERROR WHILE FETCHING PRODUCT : ' + prod_err
};
});
}
else {
return {
response: 'USER DOES NOT EXISTS OR USER NOT AUTHENTICATED'
};
}
}).catch((usr_err) => {
return {
response: 'ERROR WHILE FETCHING USER : ' + usr_err
};
});
});

Unable to catch and log the error from axios request

I'm validating user input and result in express and am returning 422 if the input is invalid and a 400 if result is empty. The problem is that I can't log the response object when an error occurs.
Nodejs:
if (q === '' || q.length < 3 || q.length > 150) {
console.log('invalid query');
return res.sendStatus(422).send('Search not found');
} else {
try {
// Fetch redis data
const data = await GET_ASYNC('data');
// stuff here
// Result Validation
if (!Array.isArray(data) || !data.length) {
res.status(400).send('Search not found');
} else {
// do stuff
res.status(200).send(data);
}
} catch (err) {
console.error(err);
res.sendStatus(500); // Server error
}
Now my react code:
const searchDb = useCallback(async() => {
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
try {
axios.get(`/api/bestProduct?q=${searchValue}`,
{ cancelToken: source.token })
.then(res => {
console.log(res) // nothing shows up
const data = res.data;
setData(data)
});
} catch (err) {
if (axios.isCancel(err)) {
console.log(err.response); // nothing shows up
} else {
console.log('hello??') // nothing
return setError(`There's been a problem on our end.`)
}
}
}, [])
I've looked at other solution and tried to log the res and res.status but nothing shows up. This is what my console looks like during the error:

What's the way of error handling in my case ?

I'm trying to make my Server side part to handle the errors from my 'Controllers' class to my 'Routes' class so i can show them in the Postman.
I think i should work with Promises but i don't get the way they works.
This is the code in my Controller Class,
async validatingWithDB(email: string, password: string) {
await this.client.connect(async () => {
try {
let saltKey = await this.client.query(
"SELECT salt FROM userinfo WHERE email=$1", [email]);
if (saltKey.rowCount == 1) {
let hashedLoginPassword = this.saltingValidation(password, saltKey.rows[0].salt).hash;
let result = await this.client.query(
'SELECT id FROM userinfo WHERE email=$1 AND password=$2', [email, hashedLoginPassword]);
if (result.rowCount > 1 || result.rowCount < 1) {
throw Error("Wrong or non existing user !");
} else {
console.log("Succes Login !");
}
} else {
throw Error("Wrong or non existing user !");
}
} catch (err) {
console.error(err.message);
}
});
};
}
//this is in Routes Class
app.route('/login')
.post(async (req: Request, res: Response) => {
try {
if (req.body.email !== 0) {
if (req.body.password !== 0) {
await
this.authenticationService.validatingWithDB(req.body.email,
req.body.password)
res.status(200).send(new Result(
true, { Message: 'Login Successfully !'
}
));
} else {
throw new Error("Password too short");
}
} else {
throw new Error("Email is too short");
}
} catch {
res.status(400).send(new Result(
false, { Message: 'Bad request, Please try again' }, ErrorCodes.BadRequest
));
}
})

Server sends success even if didn't find anything

I send data from my input fields to my api:
$.ajax({
url: '/api/login',
type: 'GET',
dataType: 'json',
ContentType: 'application/json',
data: {formData},
success: (data) => {
console.log('SUCCESS')
console.log(data)
this.setState({
isInProcess: false
})
},
error: (jqXHR) => {
console.log(jqXHR)
console.log('ERROR')
this.setState({isInProcess: false})
}
})
on my server-side I have a function to see if I have required user in db:
async function findUser(data) {
try {
const user = await User.findOne({email: data.email,
password: data.password})
console.log('User was found')
return { user }
} catch (err) {
console.log('error', err)
throw err
}
}
which will be executed here:
app.get('/api/login', async (req, res) => {
const data = req.query
try {
const foundUserData = await findUser(data.formData)
return res.json(foundUserData)
} catch (err) {
return res.status(400).json(err)
}
})
It works fine, but if a user wasn't found in db i sends success anyway. Why?
await findUser(data.formData) won't throw error, return either null or user object. You may check something following
app.get('/api/login', async (req, res) => {
const data = req.query
try {
const foundUserData = await findUser(data.formData)
if(foundUserData && foundUserData.user) {
return res.json(foundUserData)
} else {
return res.status(400).json({message: 'User not found'});
}
} catch (err) {
return res.status(500).json(err)
}
})
It sends success because none of your queries error'ed, just because it didn't find anything does not mean that the query failed because it obviously succeeded in finding out if what ever you're looking for exists or not.
To send an error in case of not found you need to check if response is empty in which case you want to send error
When no user is find you get a null value. You may try to put more logic on your success parameter with that for example:
success: function (data) {
if(!!data && data != null) {
alert('Success');
} else {
alert('No data');
}
}

Resources