I am trying to generate a unique voucher number on the _beforeInsert hook. I generate a number and try to look it up in the collection if it already exists. If not, generate a new number, until we found a unique one.
Well, I think I am struggling with Promises, because it won´t work as expected. I looked up the articles, put my .then´s and return´s in in the correct place, I think, but I´m doing something wrong.
Console.log 5 & 6 are never displayed. Collection name and field name are correct.
Somebody sees it?
Here is the code (data.js):
import wixData from 'wix-data';
export function Vouchers_beforeInsert(item, context) {
console.log("1: In beforeinsert");
let strRandomNum;
let boolVoucherExists = false;
do {
strRandomNum = getRandomNum(100000, 999999).toString();
console.log("2: strRandomNum after gen=" + strRandomNum);
chkIfExist(strRandomNum)
.then((VoucherExists) => {
boolVoucherExists = VoucherExists;
console.log("6: boolVoucherExists after db-check=" + boolVoucherExists);
});
}
while (boolVoucherExists === true);
console.log("7: Returning number to hook=" + strRandomNum);
item.fldVoucherId = strRandomNum;
return item;
}
function getRandomNum(min, max) {
return Math.floor(Math.random() * (max - min + 1)) + min;
}
function chkIfExist(strRandomNum) {
console.log("3: In chkIfExist");
console.log("4: strRandomNum before query= " + strRandomNum);
return wixData.query("Vouchers")
.eq("fldVoucherId", strRandomNum)
.count()
.then((amount) => {
let numCount = amount;
console.log("5: numCount=" + numCount);
let boolIdExists = (numCount > 0);
return boolIdExists;
})
.catch((err) => {
let errorMsg = err;
console.log("errorMsg=" + errorMsg);
});
}