How load columns via ajax in tabulator - tabulator

I am trying to load columns in a tabulator 4.5 using the following:
var table = new Tabulator("#tables", {
ajaxURL:"worker.php?data",
ajaxRequestFunc:queryRealm,
cellEdited:cEdit,
history:true,
clipboard:true,
//autoColumns:true,
clipboardPasteAction:"replace",
layout:"fitData",
columns:getColumns,
});
function getColumns(){
return new Promise(function(resolve, reject){
$.ajax({
url: "worker.php?columns",
success: function(data){
resolve(data);
},
error: function(error){
reject(error);
}
})
});
}
But I get the error:
tabulator.min.js:4 Uncaught TypeError: this.options.columns.slice is not a function
at t.u._clearObjectPointers (tabulator.min.js:4)
at t.u._create (tabulator.min.js:4)
at new t (tabulator.min.js:4)
at (index):84
Tell me please, how can I load columns into a tabulator via ajax?

You cannot pass an async function into the columns parameter. It expects an array of columns.
So instead of passing getColumns into the columns option, you should get the value from getColumns and then pass that into the Tabulator options.
I re-arranged your code some, I believe this should work.
function getColumns(){
return new Promise(function(resolve, reject){
$.ajax({
url: "worker.php?columns",
success: function(data){
resolve(data);
},
error: function(error){
reject(error);
}
})
});
}
getColumns().then((columns) => {
var table = new Tabulator("#tables", {
ajaxURL:"worker.php?data",
ajaxRequestFunc:queryRealm,
cellEdited:cEdit,
history:true,
clipboard:true,
//autoColumns:true,
clipboardPasteAction:"replace",
layout:"fitData",
columns:columns,
});
});

Related

Error when trying to get the value of a MAX query in node-mysql

I need to get the last id from my database table, so I have to use MAX in order to achieve it, so this is the sql query I am using: SELECT MAX(id) FROM payments
The issue comes when I try to get the value from the object as it throws this error: id is not defined
server.js:
app.post('/sendMail', function(req, res) {
getLastPaymentId().then((data) => {
lastPaymentId = data.lastPaymentId;
console.log(lastPaymentId.MAX(id)); //here I want to get the value
});
res.redirect('/');
});
function getLastPaymentId() {
const idPayment = new Promise((resolve, reject) => {
dbConnection.getLastPaymentId().then(data => {
resolve(data)
})
});
return Promise.all([idPayment]).then(data => {
return {
lastPaymentId: data[0]
}
})
}
dbConnection.js:
function getLastPaymentId() {
return new Promise(function(resolve, reject) {
const sql = "SELECT MAX(id) FROM payments";
con.query(sql, function(err, result) {
if(err) throw err;
resolve(result);
});
});
}
module.exports.getLastPaymentId = getLastPaymentId;
Result when just printing the object (console.log(lastPaymentId)):
It is null because I have no rows in my database yet.
Result when printing the value (console.log(lastPaymentId.MAX(id))):
It should print null instead.
How can I fix this?
Fixed! I have just remembered that I had a similar issue in the past and the answer I got, has worked in this case as well: How to access to the value when doing a COUNT() using node-mysql?
Sorry and thanks anyway!

PayPal /v1/invoicing/invoices/ REST API not available

I'm using the node.js SDK to create and send invoices on sandbox. The first 8-15ish creations and 0-2 sends return this error:
The requested resource (/v1/invoicing/invoices/) is not available.
It's not the JSON being sent, as sometimes an invoice goes through and sometimes it doesn't. I'm wondering if this is a sandbox issue (API is rate-limited in some manner), or if there's some initialization I should be doing before hand?
Roughly, here's my code:
paypal.configure ...
program // Commander
.parse(process.argv)
.args.forEach(function (arg) {
fs.createReadStream(arg).pipe(
parse({ columns: true, delimiter: '\t' }, function (error, data) {
data.forEach(function (row) {
// create invoice from each row in data
var invoice = ...
invoice
.setShipping()
.then(
function (invoice) {
return new Promise(function (resolve, reject) {
paypal.invoice.create(invoice, function (error, invoice) {
if (null === error) {
resolve(invoice);
} else {
reject(error);
}
});
});
}
)
.then(
function (invoice) {
paypal.invoice.send( invoice.id, function (error, invoice) {
});
}
);
})
})
);
});
I ended up running this on PayPal live and didn't run in to the issue above. My best guess is it's some sort of limiting on Sandbox.

Is my sqlite request inside my async function also asynchronous?

I'm using node.js and npm's sqlite package and discord.js to make a discord bot.
I try to get a array back from a async function containing a sqlite request.
It seems like my sqlite request is also asynchronous cause I get the empty response before the request is executed. How do I have to form my request to get it executed first?
I already read this post: How do I return the response from an asynchronous call? but I still dont get it. It is not a duplicate cause the question in the link is about ajax and did not help me much. I hope that if I see it with my own code I'm able to understand it better.
This is what I'm having at the moment. I already tried it with callbacks without a result.
Promise approach:
This is my async function in dbHandler.js.
var Promise = require("bluebird");
getList: function(userID) {
return new Promise(function(resolve, reject) {
var array = [];
sql.each(`SELECT * FROM table WHERE userID = ?`, userID, (err, row) => {
if (err) {
return console.error(err);
} else {
console.log("row: " + row + " element: " + row.username);
array.push(row);
}
});
array.forEach(function(element) {
console.log("element: " + element.username);
});
console.log("array: " + array);
resolve(array);
});
}
And this is my call in list.js.
db.getList(uid)
.then(function(v) {
console.log("size: " + v.size);
})
.catch(function(v) {
console.log("failed: " + v);
});
In console I get this.
array:
size: undefined
row: [object Object] element: user1
row: [object Object] element: user2
row: [object Object] element: user3
Callback approach:
dbHandler.js
getList: function(userID, callback) {
var array = [];
sql.each(`SELECT * FROM warns WHERE userID = ?`, userID, (err, row) => {
if (err) {
return console.error(err);
} else {
array.push(row);
}
});
if (array) {
callback("", array);
} else {
callback("error", "");
}
},
list.js
db.getList(uid, function (err, response) {
if (err) {
console.log(err);
} else {
console.log(response.size);
}
});
With the callback approach I only get undefined in console.
since you get the following output:
row: [object Object] element: user1
row: [object Object] element: user2
row: [object Object] element: user3
I can only assume that you get results from the database, but accessing it is the issue. I'd suggest you try to dump the whole object and see it's structure before deciding on how to access it.
Below I have modified your code to dump a readable version of the object. Start from there and debug.
getList: function(userID) {
return new Promise(function(resolve, reject) {
var array = [];
sql.each(`SELECT * FROM table WHERE userID = ?`, userID, (err, row) => {
if (err) {
return console.error(err);
} else {
console.log(JSON.stringify(row)); //lets get the contents of the row object
array.push(row); console.log(JSON.stringify(array)); //also, lets know what array contains after adding all the rows
}
});

Query with 3 parameters to dynamodb with dynamoose

I am trying to consult a DynamoDB table with 3 parameters, but it does not work. However, with 1 parameter it works perfectly.
I'm work with NodeJs, DynamoDB, Dynamoose... and here is my code:
var params = {
TableName: "DifferentTermsPages",
KeyConditionExpression:"#providerName = :providerName and #productType = :productType and #language = :language",
ExpressionAttributeNames: {
"#providerName":"providerName",
"#productType":"productType",
"#language":"language"
},
ExpressionAttributeValues: {
":providerName":providerName,
":productType":productType,
":language":language
}
};
OcrController.getDifferencesFromDB(params)
.then(function(dataDB) {
console.log("DATA = ", dataDB);
}).catch(function(err) {
console.error(err);
});
Call to another function with a promise:
getDifferencesFromDB(params) {
return new Promise(function(resolve, reject) {
DifferentTermsPagesModel.scan(params).exec().then(function (err, data) {
if(err) {
reject(err);
}
else {
console.log("OK!!");
resolve(data);
}
});
});
}
The error that shows me...
TypeError: Cannot read property 'toDynamo' of undefined
at Scan.exec (/API/src/node_modules/dynamoose/lib/Scan.js:57:23)
at ...
Where is my error?? How can I resolve it? Or another form to make this...
As you are using the scan api, please use FilterExpression rather than KeyConditionExpression.
FilterExpression:"#providerName = :providerName AND #productType = :productType AND #language = :language",

Validating all data with DB before bulk insert mongoose/mongodb

I am trying to validate the array of objects before inserting them into the mongodb.
what i am trying to do is, lets say i have an object like below
var data= { prodDetails:
[
{ measured: 'Liters',
name: 'A',
prodCode: '713',
status: true },
{ measured: 'Liters',
name: 'B',
prodCode: '713',
status: true },
{ measured: 'Liters',
name: 'C',
prodCode: '674',
status: true }
]
};
before making a bulk insert call i want check whether the given prodCode is valid DB Code or not and name duplicated or not
i am using node bluebird promises.
i tried the following code to validate prodCode
var bulkOperations = {
bulkProdInsert: function (body) {
return new Promise(function (reslv, rej) {
if (body.prodDetails.length > 0) {
common_lg.getValueById(body, "typesProd", body.prodDetails[0].prodCode).then(bulkOperations.successCallback(reslv, rej, body)).catch(bulkOperations.errCallback(reslv, rej, body));
};
reslv();
});
},
successCallback: function (reslv, rej, body) {
return function (res) {
if (res) {
body.prodDetails.splice(0, 1);
if (body.prodDetails.length > 0) {
common_lg.getValueById(body, "typesProd", body.prodDetails[0].prodCode).then(bulkOperations.successCallback(reslv, rej, body)).catch(bulkOperations.errCallback(reslv, rej, body));
}
};
};
},
errCallback: function (reslv, rej, body) {
return function (err) {
body.prodDetails.splice(0, 1);
if (body.prodDetails.length > 0) {
common_lg.getValueById(body, "typesProd", body.prodDetails[0].prodCode).then(bulkOperations.successCallback(reslv, rej, body)).catch(bulkOperations.errCallback(reslv, rej, body));
};
};
}
};
but i want to do is insert all the objects/documents into DB when name and prodCode of all the objects/documents is validated.
how to achieve this.
thanks
It sounds like you want to check the input object and then make DB calls. I would suggest the .map method of bluebird.
var promise = require('bluebird');
var checkValues = promise.method( function(prod){
if( isValid(prod.prodCode) ){
return prod;
}
//something went wrong!
throw new Error('prodCode ' + prod.prodCode + ' is invalid');
}
promise.map( data.prodDetails, checkValues )
.then(function(){
//it worked! You can call the DB now.
})
.catch(function(error){
//something went wrong, look at that error (or pass along)
})
So long as your checkValues method is a promise, you can run it against every value in your input array, and use the success of .then to know things worked and call your DB!

Resources