Alert Controller stacked in nested condition - javascript

I am doing a comparison to validate QR Code using the data retrieved from Firestore. It should navigate to another page if the condition is satisfied. Based on my code, it kept on returning 'Invalid Code' and multiple stacked alerts even if the condition is true. Is there a simpler solution to compare? I just can't quite figure it out. Here's my code.
scan() {
this.scanner.scan().then((data) => {
let qrcode = data.text.length;
this.afs.firestore.collection('item1')
.get()
.then((snapshot) => {
snapshot.docs.forEach(doc1 => {
var data1 = doc1.data();
var itemName = data1.itemname;
var itemID = data1.itemid;
this.afs.firestore.collection('item2')
.get()
.then((snapshot) => {
snapshot.docs.forEach(doc2 => {
var data2 = doc2.data();
var itemName2 = data2.itemname2;
var itemID2 = data2.itemid2;
var description = data2.description;
if (doc1.exists) {
if (qrcode == 10 && itemName == itemName2 && itemID == itemID2) {
this.navCtrl.navigateForward('/nextPage');
} else {
return this.presentAlert('Error', 'Invalid Code')
}
} else if (description == null) {
return this.presentAlert('Error', 'Nothing found')
} else {
return this.presentAlert('Error', 'QR Not Found')
}
})
})
})
})
}, (err) => {
console.log('Error: ', err);
})
}

I think that your issue is because you have 2 nested "forEach" cycles and even is you routine has a valid condition there isn't a return statement and your cycles never been stopped(using break)
I adjusted your code to break the cycles
scan() {
this.scanner.scan().then((data) => {
let qrcode = data.text.length;
this.afs.firestore.collection('item1')
.get()
.then((snapshot) => {
snapshot.docs.forEach(doc1 => {
var data1 = doc1.data();
var itemName = data1.itemname;
var itemID = data1.itemid;
var check = this.afs.firestore.collection('item2')
. get()
.then((snapshot) => {
snapshot.docs.forEach(doc2 => {
var data2 = doc2.data();
var itemName2 = data2.itemname2;
var itemID2 = data2.itemid2;
var description = data2.description;
if (doc1.exists) {
if (qrcode == 10 && itemName == itemName2 && itemID == itemID2) {
return true
} else {
return this.presentAlert('Error', 'Invalid Code')
}
} else if (description == null) {
return this.presentAlert('Error', 'Nothing found')
} else {
return this.presentAlert('Error', 'QR Not Found')
}
})
})
if (check){
this.navCtrl.navigateForward('/nextPage');
break
}else{
return check
}
})
})
}, (err) => {
console.log('Error: ', err);
})
}

Related

how i can get a value through key

i want to know how i can get a value/numbers through key/username ?
look like that console.log(acc.${username})
my js
...
app.get("/account", (req, res) => {
loggedIn = req.cookies.loggedIn;
username = req.cookies.username;
if (loggedIn == "true") {
db.list().then(keys => {
if (keys.includes(username)) {
res.render("settings.html", { username: username })
var data = fs.readFileSync('2FA.json');
var acc = JSON.parse(data)
//////////////////////////////////////////////
console.log(acc.${username}) // i want to see a numbers in user name look like in here
/////////////////////////////////////////////
} else {
res.redirect("/logout");
}
});
} else {
res.render("notloggedin.html");
}
});
my json
[
{
"youssefnageeb": 927342
},
{
"youssefnageeb1":310686
},
{
"youssefnageeb2": 105380
},
{
"youssefnageeb3": 431816
},
{
"youssefnageeb4": 484728
}
]
I am guessing "data" is in the format mentioned above.
So, you can do
const index = data.findIndex(function isAccountRow(row) { return typeof row[username] === 'number'; })
if(index === -1) {
return res.redirect("/logout");
}
const row = data[index];
console.log(row[username]); // will be the number

API getting multiple Calls

My program in a nutshell. If the trigger word is detected in the message, my application creates invoices.
The issue: Multiple calls to the trigger function. All of the requests to the API are simultaneous. This causes my data to have problems.
I have added the async and await to wait for the trigger function to complete. But it seems my calls are still being called all together.
// Links to a Facebook Live.
export const fblive = async (liveid) => {
if (liveid != null) {
try {
const reg = new RegExp("\\d{5,}");
const found = liveid.match(reg);
if (found > 0) {
console.log(found, " || ", found[0]);
let activate = false;
var userid = "";
//var accesstoken = ''
var accesstoken =''
var videoID = found;
var live_url =
"https://streaming-graph.facebook.com/" +
videoID +
"/live_comments?access_token=" +
accesstoken +
"&comment_rate=one_hundred_per_second&fields=from{name,id},message";
var source = new EventSource(live_url);
source.onmessage = function (event) {
var result = JSON.parse(event["data"]);
let trigger_word = result["message"].search("#");
// looking at comments
readcomment(result["message"]);
if (result["from"] != null) {
console.log("FROM ! !:", result["from"]);
}
};
} else {
console.log("ZERO FOUND");
}
} catch (error) {
console.log("FB LIVE COMMENT IS NOT RUNNING");
}
} else {
console.log("Live ID not valid");
}
};
// Looking at every comment in a facebook live
export const readcomment = async (the_comment) => {
try {
console.log(" CALLING LIVE READ COMMENT ", the_comment);
let re = await new Promise((resolve) =>
setTimeout(
setTimeout(async function () {
console.log(the_comment);
if (the_comment.includes("#")) {
populatelist();
console.log(the_comment);
let new_string = the_comment.trim().split(" ");
console.log(new_string, " STRING SPLIT");
let customer_found = await findcust(new_string);
let item_found = await finditem(new_string);
console.log(customer_found, item_found, "WE FOUND ");
if (customer_found != false && item_found != false) {
console.log("THERE'S A TRIGGER SALE HERE");
let remove = await find_remov(new_string);
console.log(remove, "WE ARE LOOKING AT RMOVE ");
await comment_trigger(customer_found,item_found,remove)
console.log(the_comment)
console.log("promise for " , the_comment, " has been fullfilled")
}
}
}, 2000)
)
);
} catch (error) {
console.log(error.response)
}
};
// This is when a comment was found to be the triggers words (customer id and a item name)
export const comment_trigger = async (customer, item, rmv) => {
// FIND THE ITEM IN INVOICE.
const client = find(customer, customer_list1);
const real_item = find(item, item_list1);
try {
console.log(client, real_item);
if (client != false && real_item != false) {
let inv = await invoicesbycustomer(client.id);
console.log(inv);
if (inv == undefined || inv.length ==0) {
console.log(customer, item);
console.log(real_item.id);
let new_Invoice = new Invoice("", client);
let new_item = new Product(real_item.id, real_item.name, 1);
await new_Invoice.addItem(new_item);
console.log(new_Invoice);
await createInvoice(new_Invoice);
console.log("NO INVOICE WAS FOUND FOR THIS CLIENT");
} else {
console.log(inv);
// making sure there's a real invoice.
console.log("DATA TYPE IS ", typeof inv);
if (typeof inv !== "undefined") {
console.log(inv, "THIS IS INVOICE WITH CLIENT");
console.log(inv[0].node.items.length);
let oldItems = inv[0].node.items;
let NewInvoice = new Invoice(
inv[0].node.id,
inv[0].node.customer.id
);
let Itemsize = oldItems.length;
let found = false;
if (Itemsize > 0) {
//IF ITEMS EXIST ADD QTY.
// ELSE ADD THIS NEW ITEM.
for (let x in oldItems) {
if (real_item.id == oldItems[x].product.id) {
found = true;
}
}
if (found && rmv == "removeqty") {
await removeqtyitem(customer, item);
} else if (found && rmv == "removeAll") {
await removeitem(customer, item);
} else if (found) {
let aqi = await addqtyitem(customer, item);
} else {
// add item
await additems(customer, item);
}
} else {
await additems(customer, item);
}
}
}
} else {
let errmssg = "";
if (!client) {
errmssg = errmssg.concat(" ", " Client is not valid ");
console.log("client not found", errmssg);
}
if (!real_item) {
errmssg = errmssg.concat("", " Item not found");
}
console.log(errmssg);
console.error(errmssg);
}
} catch (error) {
console.error(error.response.data)
}
};
Here's an example of the api being called. this is using graphql
//DELETING INVOICE API CALL
export const deleteInvoice = async(id) => {
const invoiceId = id;
console.log(invoiceId, "THIS I S INVOICE DELET EDELETE DELETE DELTE ")
try {
const token = "zCtQa00zlorbFFum6I7Rlzc0QwMDoS";
const shema = `
mutation ($input: InvoiceDeleteInput !) {
invoiceDelete(input: $input) {
didSucceed
inputErrors {
path
code
message
}
}
}`;
//About to submit my shema to waveapps
const API_URL="https://gql.waveapps.com/graphql/public"
const bussID = "QnVzaW5lc3M6ZTIyZmVhODEtNjg5OC00N2ZiLTgzOGItYWMyYzllNDZiM2Jk";
let watch = await axios(API_URL, {
method: "POST",
headers: {
Authorization: token ? `Bearer ${token}` : "",
"Content-Type": "application/json",
},
data:{
query: shema,
variables: {
input:{
invoiceId: invoiceId,
}
},
},
})
console.log(watch.data)
} catch (error) {
console.log(error.response)
}
//console.log("return delete invoice complete")
};
I have used async/await and promises.
When multiple calls are made. The await and promises are still being called at the same time. Not sure what else to look at? any suggestions please. I have spent a week on this.

How to combine AND and OR with Knex?

I am unable to create the following SQL query in Knex:
SELECT * FROM tasks WHERE (code = 'export') AND (status = 'failed' OR status = 'complete')
Using the code:
const queryResult = await this.db('tasks')
.select('*')
.where(async function () {
if ('code' in query) {
this.where('code', query.code)
}
if ('status' in query) {
if (isArray(query.status)) {
return query.status.map(status => this.orWhere('status', status))
} else {
this.andWhere('status', query.status)
}
}
})
.orderBy('created_at', 'DESC')
When supplying an array of multiple statuses it disregards the "code = export" value and selects everything.
Use modify.
const queryResult = await this.db('tasks')
.select('*')
.modify(function(queryBuilder) {
if ('code' in query) {
queryBuilder.where('code', query.code)
}
if ('status' in query) {
if (isArray(query.status)) {
query.status.map(status => queryBuilder.orWhere('status', status))
} else {
queryBuilder.andWhere('status', query.status)
}
}
})
.orderBy('created_at', 'DESC')
const query = knex('tasks');
if ('code' in query) {
query.where('code', query.code);
}
if ('status' in query) {
query.where(builder => {
const statuses = isArray(query.status) ? query.status : [query.status];
for (let status of statuses) {
builder.orWhere('status', status);
}
});
}
const result = await query;

Run function if other end Vue, JS

I'm don't know how to run code if other end
Function showAvailableTable refresh item and add data to vuex $store
I need to run code from ////START to //// END if showAvailableTable() done correctly(axios add data to $store)
how should I do it correctly?
showAvailableTable () {
var obj = this.firstStepData
var nullCount = 0
var self = this
for (var key in obj) {
if (obj.hasOwnProperty(key) && obj[key] == null) {
nullCount++
}
}
if (nullCount === 0) {
var reservationId = this.firstStepData.restaurant.id
var restaurantSize = this.firstStepData.tableSize.value
var reservationDate = this.firstStepData.reservationDate
var reservationTime = this.firstStepData.reservationTime
axios
.get(self.$store.state.apiUrl + 'reservation/tables/?size=' + restaurantSize + '&restaurant_id=' + reservationId + '&date=' + reservationDate + '&hour=' + reservationTime)
.then(response => {
this.$store.commit('updateRestaurantTableList', response.data)
})
.catch(error => {
console.log(error)
})
this.$store.commit('updateShowTable', true)
}
},
Next function, this function booking table, I'm run this.showAvailableTable() to refresh data in $store
firstStepBook (event, id) {
this.showAvailableTable()
///////////////////START
var isResData = false
this.dataLoading = true
for (var obj in this.restaurantTableList) {
if (this.restaurantTableList[obj].id === id) {
if (this.restaurantTableList[obj].res_tab.length > 0) {
isResData = true
}
break
}
}
if (isResData && !event.currentTarget.classList.contains('isSelected')) {
alert('someone is booking this table, choose another one')
} else {
if (event.currentTarget.classList.contains('isSelected')) {
this.deleteTmpReservation(this.reservationTmp.id)
this.dataLoading = false
} else {
if (this.reservationTmp.id !== undefined) {
this.deleteTmpReservation(this.reservationTmp.id)
this.dataLoading = false
}
var self = this
axios.post(self.$store.state.apiUrl + 'reservation/', {
restaurant_table: id,
clients_number: self.firstStepData.tableSize.value,
reservation_time: self.firstStepData.reservationTime,
reservation_date: self.firstStepData.reservationDate
})
.then(function (response) {
self.showAvailableTable()
self.$store.commit('updateReservationTmp', response.data)
self.dataLoading = false
})
.catch(function (error) {
console.log(error)
})
//this.$store.commit('updateStep', 2)
}
}///////////////////END
},
thank you in advance
This might suit you if the mutation is only called within showAvailableTable()
Ref Vuex subscribe
mounted() {
this.$store.subscribe((mutation, state) => {
if (mutation.type === 'updateRestaurantTableList') {
///////////////////START
...
///////////////////END
}
})
},
methods: {
firstStepBook (event, id) {
// call to updateRestaurantTableList triggers above subscription
this.showAvailableTable()
}
}

Handle null return values in Promise in typescript

I am quite new to typescript and have following issue.
I have following code where I can't reach console.log('uid....' + uid); when the uid is null
deleteUser(email: string): Promise<User> {
let uid: string;
let p = new Promise<User>((resolve) => {
this.loginService.getUserIdByEmail(email).then((getUserResponse) => {
**********************************
******** do not reach here when getUserResponse is NULL**********************
************************
uid = getUserResponse;
console.log('uid....' + uid);
if (uid !== null) {
let actions = [
this.siteUserTableService.deleteByRowKey(uid),
this.userSiteTableService.deleteById(uid),
];
Promise.all(actions.map(this.reflect)).then(values => {
this.tableService.deleteById(uid).then((deleteResponse) => {
this.loginService.deleteUserByEmail(email);
});
});
}
}).catch((err) => {
// Something wrong
});
});
return p;
};
getUserIdByEmail(email: string): Promise<string> {
let searchParams = {
query: 'select UID from accounts where profile.email = "' + email + '"'
};
let p = new Promise<string>((resolve, reject) => {
login.accounts.search(searchParams).then((response) => {
if (response.errorCode === 0 && response.results.length > 0) {
resolve(response.results[0].UID);
} else {
console.log('No login user...');
reject('');
}
});
});
};
As I am not getting a return value from getUserIdByEmail function (return null) I cannot proceed with deleteUser function.
So how can I proceed even with null return value.
Thanks

Categories

Resources