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;
Related
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.
I am working on a script where the objective is to read data from excel and parse it into XML. There is a need for mapping a few of the details under one node if it exists. Considering the below data, I am looking to map the spouse under the subscriber if member id of both of them matches.
expected output:
<Member>
<MemberDetail>
<FIRSTNAME>Kevin</FIRSTNAME>
<LASTNAME>Adams</LASTNAME>
<ID>1</ID>
<Dependent>
<FIRSTNAME>Kelly</FIRSTNAME>
<LASTNAME>Adams</LASTNAME>
<ID>1</ID>
</Dependent>
</MemberDetail>
</Member>
current output:
<Member>
<MemberDetail>
<FIRSTNAME>Kevin</FIRSTNAME>
<LASTNAME>Adams</LASTNAME>
<ID>1</ID>
</MemberDetail>
<MemberDetail>
<Dependent>
<FIRSTNAME>Kelly</FIRSTNAME>
<LASTNAME>Adams</LASTNAME>
<ID>1</ID>
</Dependent>
<MemberDetail>
</Member>
code:
const xlsxFile = require('read-excel-file/node');
const builder = require('xmlbuilder');
const fs = require('fs');
const doc = builder.create('Member');
const serializer = new (require('xmldom')).XMLSerializer;
xlsxFile('./data/file.xlsx', { sheet: 'Details' }).then((rows) => {
const typeColumn = rows[0].indexOf('MEMBER TYPE');
rows.forEach((row, rowIndex) => {
if (rowIndex !== 0) {
const detail = employeeList.ele('MemberDetail').att('for', 'subscriber')
if (row[typeColumn] == 'SUBSCRIBER') {
row.forEach((cellValue, cellIndex) => {
detail.ele(rows[0][cellIndex].split(" ").join(""))
.txt(cellValue ? cellValue.toString() : 'empty')
.up()
})
}
else {
const dependentDetail = detail.ele('Dependent').att('for', 'dependent')
row.forEach((cellValue, cellIndex) => {
dependentDetail.ele(rows[0][cellIndex].split(" ").join(""))
.txt(cellValue ? cellValue.toString() : 'empty')
.up()
})
}
}
})
fs.writeFile('./test.xml', serializer.serializeToString(doc), function (error) {
if (error) {
console.log('Error', error)
}
else {
console.log('Your file has been saved')
}
})
})
.catch(err => console.log(err))
[1]: https://i.stack.imgur.com/giOUj.png
My only suggestion would be to isolate the element that you are mapping 'MemberDetail' as a constant and add dependentDetail to that.
try this
const xlsxFile = require('read-excel-file/node');
const builder = require('xmlbuilder');
const fs = require('fs');
const doc = builder.create('Member');
const serializer = new (require('xmldom')).XMLSerializer;
xlsxFile('./data/file.xlsx', { sheet: 'Details' }).then((rows) => {
const typeColumn = rows[0].indexOf('MEMBER TYPE');
rows.forEach((row, rowIndex) => {
if (rowIndex !== 0) {
const detail = employeeList.ele('MemberDetail').att('for', 'subscriber')
row.forEach((cellValue, cellIndex) => {
if (row[typeColumn] == 'SUBSCRIBER') {
const subscriber = detail.ele(rows[0][cellIndex].split(" ").join(""))
.txt(cellValue ? cellValue.toString() : 'empty')
.up()
row.forEach((cellValue, cellIndex) => {
if (row[typeColumn] !== 'SUBSCRIBER') {
const dependentDetail = subscriber.ele('Dependent').att('for', 'dependent')
dependentDetail.ele(rows[0][cellIndex].split(" ").join(""))
.txt(cellValue ? cellValue.toString() : 'empty')
.up()
}
})
}})
fs.writeFile('./test.xml', serializer.serializeToString(doc), function (error) {
if (error) {
console.log('Error', error)
}
else {
console.log('Your file has been saved')
}
})
}})
.catch(err => console.log(err))})
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);
})
}
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
I am trying to query a Firebase database. I have the following code, but it returns an empty list, when there is matching data.
loadData() {
this.firelist = this.af.database.list('/chat/', {
query: {
orderByChild: 'negativtimestamp'
}
}).map(items => {
const filtered = items.filter(item => {
item.memberId1 === this.me.uid;
});
return filtered;
});
// if me not in firelist then create new chat
if (this.me && this.me.uid) {
let chatFound: boolean = false;
console.log('this.firelist', this.firelist);
this.firelist.forEach(chatItems => {
console.log('chatItems', chatItems);
for (let i = 0; i < chatItems.length; i++) {
console.log('chatItems['+i+']', chatItems[i]);
let memberId1: string = chatItems[i].memberId1;
let memberId2: string = chatItems[i].memberId2;
if (memberId1 === this.me.uid || memberId2 === this.me.uid) {
chatFound = true;
break;
}
}
if (!chatFound) {
//this.createChat();
}
});
}
}
I think my problem is with the filter.
The following code creates a chat successfully:
createChat(img1: string, img2: string) {
this.af.database.list('/chat/').push({
memberId1: this.me.uid,
memberId2: this.you.uid,
img1: img1,
img2: img2,
displayName1: this.me.displayName,
displayName2: this.you.displayName,
lastMsg_text: 'todo',
timestamp: Date.now(),
negativtimestamp: -Date.now()
})
}
The following filter works:
this.firelist = this.af.database.list('/chat/', {
query: {
orderByChild: 'negativtimestamp'
}
}).map(items => {
const filtered = items.filter(
item => item.memberId1 === this.me.uid
);
return filtered;
});