Callback skipped a part - javascript

I have some trouble with my js callback, I can't understand why my callback of my function don't want execute all the code, just to give you an idea :
class LogsPortail {
static SetLogs(pool, req, res, callback) {
console.log('start log ');
var bCallBack = false;
var now = new Date();
var endpoint = req.originalUrl
endpoint = endpoint.split("?")[0]
endpoint = endpoint.replace("/", "")
var query = "INSERT INTO LOGS_PORTAIL (ENDPOINT, TYPE, DATE_HEURE_LOGS, LOGIN) VALUE ('" + endpoint + "','" + req.method + "','" + now.toISOString().slice(0, 19).replace('T', ' ') + "','" + 'API' + "')";
var queryParam = "INSERT INTO LOGS_PORTAIL_PARAM (IDLOGS_PORTAIL, NOM, VALEUR) VALUE ";
console.log('query 1 log ');
pool.query(query, function(err, results) {
if (err) {
console.log("Error : " + query);
bCallBack = true;
callback();
} else {
console.log('query log 2');
//On a bien inséré le logs portail, maintenant on ajout tous les paramètres
for (var key in req.query) {
if (queryParam != "INSERT INTO LOGS_PORTAIL_PARAM (IDLOGS_PORTAIL, NOM, VALEUR) VALUE ")
queryParam += ","
queryParam += " (" + results.insertId + ",'" + key.toLowerCase() + "', '" + req.query[key] + "')"
}
for (var key in req.body) {
if (queryParam != "INSERT INTO LOGS_PORTAIL_PARAM (IDLOGS_PORTAIL, NOM, VALEUR) VALUE ")
queryParam += ","
queryParam += " (" + results.insertId + ",'" + key.toLowerCase() + "', '" + req.body[key] + "')"
}
pool.query(queryParam, function(err, resultsParam) {
if (err) {
console.log("Error : " + queryParam);
console.log(err);
bCallBack = true;
callback();
} else {
bCallBack = true;
callback();
}
});
}
});
while (bCallBack === false) {}
console.log('call back end ');
//callback();
}
}
To explain you, my first query will be executed perfectly, and after that, the callback will not go through the condition but will go at the end where (for the test) I put an infinity while where my code will never exit.
This is what my log shows - we never see the logs "query log 2"
Thanks for your help

Related

Web API Controller POST & PUT & DELETE not working correctly

I keep getting results as false when running my POST & PUT & DELETE methods.
When I used POSTMAN I get 200 OK but my response returns as false?
Here's what I get when i use POST:
https://i.stack.imgur.com/fytB1.png
Here's what I get when i use UPDATE:
https://i.stack.imgur.com/y3vdv.png
Here's what I get when i use DELETE:
https://i.stack.imgur.com/hSNjy.png
Here is my controller code:
[HttpPost("AddNewOwner")]
public Boolean AddNewOwner(Owner theOwner)
{
DBConnect objDB = new DBConnect();
string strSQL = "INSERT INTO HomeOwnership_T (HomeOwnerID, FirstName, LastName, Address, City, State, ZipCode, TelNo, Email, BlockNo, LotNo, SaleDate, SalePrice, IsSold) " +
"VALUES ('" + theOwner.HomeOwnerID + "', '" + theOwner.FirstName + "', '" +
theOwner.LastName + "', '" + theOwner.Address + "', '" + theOwner.City +
"', '" + theOwner.State + "', '" + theOwner.ZipCode + "', '" + theOwner.TelNo + "', '"
+ theOwner.Email + "', '" + theOwner.BlockNo + "', '" + theOwner.LotNo + "', '"
+ theOwner.SaleDate + "', '" + theOwner.SalePrice + "', '" + theOwner.IsSold + "')";
//Execute the INSERT statement in the database
int result = objDB.DoUpdate(strSQL);
if (result > 0)
{
string command = "SELECT TOP 1 HomeOwnerID FROM HomeOwnership_T ORDER BY DESC";
DataSet ds = objDB.GetDataSet(command);
Tax taxInfo;
foreach (DataRow record in ds.Tables[0].Rows)
{
taxInfo = new Tax();
taxInfo.HomeOwnerID = int.Parse(record["HomeOwnerID"].ToString());
string strSQL2 = "INSERT INTO TaxInfo_T (AccessedVal, LandVal, AdditionalVal, TaxRate, TaxPerYear, RealEstateTax, HomeOwnerID)"
+ "VALUES (0.0, 0.0, 0.0, 0.0, 0.0, 0.0, '" + taxInfo.HomeOwnerID + "')";
objDB.DoUpdate(strSQL2);
}
return true;
}
else
{
return false;
}
}
[HttpPut]
public Boolean Update(Owner theOwner)
{
DBConnect objDB = new DBConnect();
HomeTax owner = new HomeTax();
string strSQL = "UPDATE HomeOwnership_T SET HomeOwnerID = " + theOwner.HomeOwnerID +
", FirstName = '" + theOwner.FirstName + "', LastName: '" + theOwner.LastName +
"', Address = '" + theOwner.Address + "', City = '" + theOwner.City +
"', City = '" + theOwner.City + "', State = '" + theOwner.State +
"', ZipCode = '" + theOwner.ZipCode + "', TelNo = '" + theOwner.TelNo +
"', Email = '" + theOwner.Email + "', BlockNo = " + theOwner.BlockNo +
", LotNo = " + theOwner.LotNo + "', SaleDate = '" + theOwner.SaleDate +
"', SalePrice = " + theOwner.SalePrice + ", IsSold = '" + theOwner.IsSold +
" WHERE HomeOwnerID = " + theOwner.HomeOwnerID;
int result = objDB.DoUpdate(strSQL);
if (result > 0)
{
return true;
}
else
{
return false;
}
}
[HttpDelete("{id}")]
public Boolean Delete(int id)
{
DBConnect objDB = new DBConnect();
string strSQL = "DELETE * FROM HomeOwnership_T INNER JOIN TaxInfo_T " +
"ON HomeOwnership_T.HomeOwnerID = TaxInfo_T.HomeOwnerID WHERE HomeOwnerID = " + id;
int result = objDB.DoUpdate(strSQL);
if(result > 0)
{
return true;
}
else
{
return false;
}
}
Here are my ajax calls:
$(document).on("click", "#btnAddHomeOwner", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/AddNewOwner";
$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("btnAddHomeOwner selected");
var owner = new Object();
owner.HomeOwnerID = $("#txtHomeOwnerID").val();
owner.FirstName = $("#txtFirstName").val();
owner.LastName = $("#txtLastName").val();
owner.Address = $("#txtAddress").val();
owner.City = $("#txtCity").val();
owner.State = $("#txtState").val();
owner.ZipCode = $("#txtZipCode").val();
owner.TelNo = $("#txtTelNo").val();
owner.Email = $("#txtEmail").val();
owner.BlockNo = $("#txtBlockNo").val();
owner.LotNo = $("#txtLotNo").val();
owner.SaleDate = $("#txtSaleDate").val();
owner.SalePrice = $("#txtSalePrice").val();
owner.IsSold = $("#txtIsSold").val();
var strInput = JSON.stringify(owner);
// Make an AJAX request to get a home and store the response in the appropriate div.
$.ajax({
type: "POST",
url: strURL,
contentType: "application/json", // set the data type sent to the Web Service.
dataType: "json", // set the data type expected from the Web Service.
data: strInput, // send an empty JSON object (no input required).
success: function (data) { // set callback function used to update the page/
console.log(data);
var result = data;
if (result == true)
$("#msg").text("The record was successfully added to the database.");
else
$("#msg").text("The record was not added to the database. Try again later.");
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); // end of btnStoreHomeOwner click event
$(document).on("click", "#btnDelete", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/";
var param = $("#txtHomeOwnerID").val();
$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("Delete button selected.");
$.ajax({
type: "DELETE",
url: strURL + param,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{5}",
success: function (data) {
console.log(data);
var result = data;
if (result == true) {
$("#msg").text("The record with HomeOwnerID: " + param + " was deleted.");
alert("Deleted!");
}
else {
$("#msg").text("The record with HomeOwnerID: " + param + " was not deleted.");
alert("Not Deleted");
}
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); // end of btnDelete click event
$(document).on("click", "#btnUpdateAll", function () {
var strURL = "https://localhost:44395/api/ServiceDeed/Update";
// Clear the divs contents.
//$("#display").html("");
//$("#msg").html("");
$("#update").html("");
$("#updateResult").html("");
console.log("Update home owner button selected.");
var owner = new Object();
owner.HomeOwnerID = $("#txtHomeOwnerID").val();
owner.FirstName = $("#txtFirstName").val();
owner.LastName = $("#txtLastName").val();
owner.Address = $("#txtAddress").val();
owner.City = $("#txtCity").val();
owner.State = $("#txtState").val();
owner.ZipCode = $("#txtZipCode").val();
owner.TelNo = $("#txtTelNo").val();
owner.Email = $("#txtEmail").val();
owner.BlockNo = $("#txtBlockNo").val();
owner.LotNo = $("#txtLotNo").val();
owner.SaleDate = $("#txtSaleDate").val();
owner.SalePrice = $("#txtSalePrice").val();
owner.IsSold = $("#txtIsSold").val();
var strInput = JSON.stringify(owner);
//Make an AJAX request to get a home owner and display the response in the appropriate div
$.ajax({
type: "PUT",
url: strURL,
contentType: "application/json; charset=utf-8",
dataType: "json",
data: strInput,
success: function (data) {
console.log(data);
var owner = data;
$("#display").html("<hr><p>".concat("HomeOwnerID: ", owner.HomeOwnerID,
"<br>FirstName: ", owner.FirstName, "<br>LastName: ", owner.LastName,
"<br>Address: ", owner.Address, "<br>City: ", owner.City,
"<br>State: ", owner.State, "<br>ZipCode: ", owner.ZipCode,
"<br>Telephone Number: ", owner.TelNo, "<br>Email: ", owner.Email,
"<br>Block Number: ", owner.BlockNo, "<br>Lot Number: ", owner.LotNo,
"<br>Date of Sale: ", owner.SaleDate, "<br>Sale Price: $", owner.SalePrice,
"<br>Sold Status: ", owner.IsSold, "<br>Accessed Value: $", owner.AccessedVal,
"<br>Land Value: $", owner.LandVal, "<br>Additional Value: $", owner.AdditionalVal,
"<br>Tax Rate: $", owner.TaxRate, "<br>Tax Per Year: $", owner.TaxPerYear,
"<br>Real Estate Tax: $", owner.RealEstateTax, "</p >"));
if (owner == true)
$("#updateResult").text("The record was successfully updated to the database.");
else
$("#updateResult").text("The record was not updated to the database. Try again later.");
},
error: function (req, status, error) { // sets the error callback function used when an error occurs.
alert("Error: " + req.responseText + " | " + status + " | " + error);
}
}); //end of ajax method
}); //end of btnUpdate
check your sql string when you set the homeownerid is it suppose to be "SET hoID = '" + theOwner.HomeOwnerID + "', ownerName = '" + theOwner.ownerName + "'....etc

Sqlite Select query with where condition doesn't return any value

I've tried all possible formats for the select query:
var queryCust = "SELECT * FROM customers WHERE CustBarcode = '" + CustomerBarcode + "';";
or
var queryCust = "SELECT * FROM customers WHERE CustBarcode like '" + CustomerBarcode + "';";
or
var queryCust = "SELECT * FROM customers WHERE cast(CustBarcode as text) = '" + CustomerBarcode "';";
or with and without ' ' but nothing works, the query didn't return any value!
I've even tried
db.executeSql('SELECT * FROM customers WHERE CustBarcode = ?', [ CustBarcode ], function(rs) {...
but didn't worked, even when tried to convert with javascript CustBarcode to string or integer.
below is the function:
alert(queryCust);
db.executeSql(queryCust, [], function(rs) {
alert(rs.rows.item(0).CustBarcode);
var DescCust = "";
if (rs.rows.item(0).Status == 'NEW'){
DescCust = rs.rows.item(0).Desc + ' ' + rs.rows.item(0).Address;
} else {
DescCust = rs.rows.item(0).CustCode + ' ' + rs.rows.item(0).Desc + ' ' + rs.rows.item(0).Address;
}
document.getElementById("custDesc").innerHTML = DescCust;
}, function(error) {
alert('SELECT SQL statement ERROR while building DescCust: ' + error.message);
});

javascript league api combinedTick callback

async run(message, args) {
LolApi.init('censored', 'na');
LolApi.setRateLimit(10, 500);
var input = '';
args = args.toLowerCase();
LolApi.Summoner.getByName(args, function (err, summoner) {
if (!err) {
Name = summoner[args].name;
Name = Name.toLowerCase();
Id = summoner[Name].id;
Level = summoner[Name].summonerLevel;
input += "Name: " + summoner[Name].name + '\n' +
"Level: " + Level + "\n";
console.log(input);
//message.reply(input);
process.nextTick(LolApi.getLeagueData);
}
else {
message.reply('Error fam.');
}
});
setTimeout(function(){console.log('Waiting...')},2000);
LolApi.getLeagueData(Id,'NA', function (err, summoner) {
if (!err) {
Tier = summoner[Id][0].tier;
Division = summoner[Id][0].entries[0].division;
input += "Tier: " + Tier + '\n' +
"Division: " + Division;
message.reply(input);
} else {
console.log(Name);
console.log(err);
message.reply('Error Fam' + Id + "test");
}
});
}
When i run this code up get an error 404 running the second part. It gives me an saying combinedTickCallback but im not sure what this means because i am a noob. I use node.js if that helps with anything

sqlite not saving french accents like à as $agrave

When i will save into my database "C'est tout à fait juste.", sqlite will remove the & from &agrave, becouse it can't maybe handle utf-8.
var sql += "INSERT INTO Test(TestId,Text) Values(1, "C'est tout à fait juste.");
I tried for every insert to replace the $agrave with à, but I think there will be a better solution.
Is there a better way to solve this?
Thanks for any help...
UPDATE
This is my code to create my sqlite database:
function initDb($cordovaSQLite, logService) {
var defcorrect = $.Deferred();
try {
logger = logService;
db = window.sqlitePlugin.openDatabase({ name: "xxx.db", location: 0 }, successCB, errorCB);
$cordovaSQLite.execute(db, "CREATE TABLE IF NOT EXISTS Card(CardId UNIQUEIDENTIFIER PRIMARY KEY, CardSetId UNIQUEIDENTIFIER NOT NULL, FrontText NVARCHAR(4000) NOT NULL, BackText NVARCHAR(4000) NULL, ControlType INT NOT NULL, CardLevel INT NOT NULL, IsDirty bit NOT NULL, ChangedAt INT NOT NULL, Active bit default 'true')").catch(function (err) {
logService.writeAppError("00000000-0000-0000-0000-000000000000", "Could not init Table Card: ErrorNo: " + startGUIDLog + " ErrorMessage: " + err.message);
window.location = "#/error/" + startGUIDLog;
});
$cordovaSQLite.execute(db, "CREATE UNIQUE INDEX IF NOT EXISTS Card_Index on Card (CardId)").catch(function (err) {
logService.writeAppError("00000000-0000-0000-0000-000000000000", "Could not init INDEX Card_Index on Card: ErrorNo: " + startGUIDLog + " ErrorMessage: " + err.message);
window.location = "#/error/" + startGUIDLog;
});
defcorrect.resolve(db);
} catch (err) {
logService.writeAppError("00000000-0000-0000-0000-000000000000", "Could not init Database: ErrorNo: " + startGUIDLog + " ErrorMessage: " + err.message);
window.location = "#/error/" + startGUIDLog;
}
return defcorrect.promise();
}
And with this code I insert the data
function saveCard(cardList, userId, db) {
var defcorrect = $.Deferred();
truncateTable("Card", db, userId).done(function () {
if (cardList.length !== 0) {
var sql = "";
cardList.forEach(function (card) {
sql += "INSERT INTO Card(CardId,CardSetId,FrontText,BackText,ControlType,CardLevel,IsDirty,ChangedAt,Active) VALUES (" + JSON.stringify(card.CardId) + "," + JSON.stringify(card.CardSetId) + "," + JSON.stringify(Card.FrontText) + "," + JSON.stringify(Card.BackText) + "," + card.ControlType + ", " + card.CardLevel + ",'" + card.IsDirty + "'," + card.ChangedAt + ",'" + card.Active + "');";
});
var successFn = function (count) {
logService.writeAppInfo(userId, "Sync Save Card Successfully imported " + count + " SQL statements to DB");
defcorrect.resolve();
};
var errorFn = function (error) {
logService.writeAppError(userId, "Sync Save Card Error: " + error);
$('#statusOverview').hide();
$('#syncError').show();
};
var progressFn = function (current, total) {
$("#statusText").text("Importiere " + current + "/" + total + " Karten");
};
cordova.plugins.sqlitePorter.importSqlToDb(db, sql, {
successFn: successFn,
errorFn: errorFn,
progressFn: progressFn,
batchInsertSize: 500
});
} else {
defcorrect.resolve();
}
});
return defcorrect.promise();
}
In the debug mode I can see, that the data comes in the right way like "C'est tout à fait juste." and after insert when i read out this data it comes like this: "C'est toutagrave; fait juste."
For me this solution worked:
var elemfolderName = document.createElement('textarea');
elemfolderName.innerHTML = "C'est tout à fait juste.";
var folderName = elemfolderName.value;
And then I save folderName to sqlite3 db...

Unit testing a function and simulating an event emitter response

I am currently writing some tests against the code shown below in node.js using mocha. I want to simulate the response from the event emitter 'check_user'. I have sinon.js but I can't get my mind in the right place to work out the best way to simulate the response.
Anyone able to offer some advice on how to go about this?
TgCustomCommand.contact = new Command("contact", "Will send you a users contact card to add to your contact list. Usage is .contact nick", function (input, callback) {
var payload = input;
//Switch our contact to payload.to as this is what our checkuser function looks at
//Check the command over
if (payload.command_args === false) {
payload.response = 'msg ' + payload.to + ' ' + this.description;
return callback(null, payload);
} else {
payload.return = payload.to;
payload.to = payload.command_args; //Set up ready for nick check
//Check the nick exists
emitter.emit('check_user', payload, function (err, result) {
if (err) return callback(err, null);
payload = input; //Reset our payload so we have correct payload.to
//Check how many users we returned
if (result.length === 0) { //Not in our contact list
payload.response = 'msg ' + payload.return + ' I do not have that person in my contact list!';
return callback(null, payload);
} else if (result.length === 1) {
payload.to = result[0].Nick;
payload.response = "send_contact " + payload.return + ' ' + result[0].Phone + ' ' + result[0].Nick + " _";
return callback(null, payload);
}
else {
//loop through our object and create a list of those returned
payload.response = "msg " + payload.return + " I know multiple people with a similar nick: ";
for (var i = 0; i < result.length; i++) {
log.debug(result[i].Nick);
payload.response = payload.response + result[i].Nick + " ";
}
return callback(null, payload);
}
});
}
;
});

Categories