I got lets say 100.000 records in array:
var eData = { "id": "1001", "type": "Regular" },
{ "id": "1002", "type": "Chocolate" },
{ "id": "1003", "type": "Blueberry" },
{ "id": "1004", "type": "Devil's Food" }
And so on...
When I fire the node.js script below
var db = require('/QOpenSys/QIBM/ProdData/OPS/Node6/os400/db2i/lib/db2a');
var DBname = "*LOCAL";
var dbconn = new db.dbconn();
dbconn.conn(DBname);
var sqlA = new db.dbstmt(dbconn);
eData.forEach(function(eRow, i) {
var sql = "INSERT INTO lib.table VALUES( xx x x x) WITH NONE"
sqlA.exec(sql, function(rs, err) {
console.log("Execute Done.");
console.log(err);
});
});
The data will be mixed up in DB. Same id and type will be there 10 times, but it will hit the exact number of insertet records.
If I change to execSync, everything turns out right, but seams a bit slow. What am I missing to do async inserts?
What is the fastest way doing huge inserts?
There will be a optimal number of async operations to have processing at any one time. The easiest way to limit the number of async operations is with the excellent async.js module.
https://caolan.github.io/async/docs.html#eachLimit
var async = require('async')
var db = require('/QOpenSys/QIBM/ProdData/OPS/Node6/os400/db2i/lib/db2a');
var DBname = "*LOCAL";
var dbconn = new db.dbconn();
dbconn.conn(DBname);
var sqlA = new db.dbstmt(dbconn);
async.eachLimit(eData, 100, function(eRow, cb) {
var sql = "INSERT INTO lib.table VALUES( xx x x x) WITH NONE"
sqlA.exec(sql, function(rs, err) {
console.log("Execute Done.");
cb(err)
});
}, function (error) {
if (error) {
console.error(error)
} else {
console.log('Done')
}
})
Related
const cc = DataStudioApp.createCommunityConnector();
function getAuthType() {
return cc.newAuthTypeResponse()
.setAuthType(cc.AuthType.USER_TOKEN)
.setHelpUrl('https://api.sigecloud.com.br/swagger/ui/index#/')
.build();
}
function resetAuth() {
var userTokenProperties = PropertiesService.getUserProperties();
userTokenProperties.deleteProperty('dscc.username');
userTokenProperties.deleteProperty('dscc.password');
}
function isAuthValid() {
var userProperties = PropertiesService.getUserProperties();
var userName = userProperties.getProperty('dscc.username');
var token = userProperties.getProperty('dscc.token');
var res = UrlFetchApp.fetch(`https://api.sigecloud.com.br/request/Pedidos/GetTodosPedidos&Authorization-Token${token}&User=${userName}&page=12&App=API APP`, { 'muteHttpExceptions': true });
return res.getResponseCode() == 200;
}
function getConfig() {
}
function getSchema() {
}
function getData() {
}
This is Manifest:
{
"timeZone": "America/Sao_Paulo",
"dependencies": {},
"exceptionLogging": "STACKDRIVER",
"runtimeVersion": "V8",
"dataStudio":{
"name": "Two Dogs Connector with Sige",
"description": "The unofficial conecctor to acess Sige Data",
"company": "Mateus C Rocha",
"logoUrl": "https://images.sympla.com.br/62ea7b9d69ec5.png",
"addOnUrl": "https://twodogs.com/br/quem-somos/",
"supportUrl": "https://twodogs.com/br/quem-somos/"
}
}
This error appears when I add the implementation ID generated when I select the test implementation option, in the google script
My api needs to receive: Page, user(constant value), token(constant value) and App(constant value)...
I don't know how it works, but I was hoping it wouldn't show errors, as I followed the documentation https://developers.google.com/looker-studio/connector/get-started
I'm fairly new to Node.Js and JS in general. I was trying to create a SQL query for a table. After that, I create a separate query to get one/multiple rows from another table that have the same ID (in here LGID) as the row from the first query. Like a JOIN command but I need the results from the second query as a separate object.
I am using the "node-firebird" client.
Everything works, except "the entire code from the second query"
My expected Output would be something like this:
{
"KDNR": "1",
"NUMBER": "+49123456789",
"NAME1": "John",
"NAME2": "Doe,
"STRASSE": "Musterstrasse 38",
"PLZ": "12345",
"ORT": "Musterstadt",
"TEL": "+49123456787",
"TNK": {
{"NAME": "TANK1"},
{"NAME": "TANK2"},
}
}
db.query('SELECT * FROM LG WHERE NAME1 = ?', [req.userData.orga], (err, lgResult) => {
if (err)
throw err;
lgResult.forEach((row) => {
row.KDNR = ab2str(row.KDNR);
row.NUMBER = ab2str(row.NUMBER);
row.NAME1 = ab2str(row.NAME1);
row.NAME2 = ab2str(row.NAME2);
row.STRASSE = ab2str(row.STRASSE);
row.PLZ = ab2str(row.PLZ);
row.ORT = ab2str(row.ORT);
row.TEL = ab2str(row.TEL);
console.log('test');
db.query('SELECT * FROM TNK WHERE LGID = ?', [1], (errN, tnkResult) => {
if (errN)
return res.status(500).json({ error: 'Error queryisssng DB' });
console.log('another test');
row.TNK.push(tnkResult);
});
return res.status(200).json(lgResult);
});
I can see the test multiple times in the console, but not the another test.
I hope this is enough code for you to help.
I have a bit of problems with my code :
[
{
"key": 0,
"server": 0
},
{
"key": 0,
"server": 1
},
{
"key": 1,
"server": 0
}
]
how i can result to :
[
{ key: 0 , server:[0,1] },
{ key: 1 , server:[0] }
]
I'm using _.groupBy but it does not return results as expected.
How merge mutil object in array with lodash?
One solution would be to use a combination of groupBy, map, and mergeWith.
So first, you group the items by key, so in this example it will return an object with 0 and 1 as the keys which will contain the grouped items.
Then you use .map to iterate through the returned object and get the grouped values.
Finally, you use .mergeWith with a customizer function which you can use to customize the how the values of the server key is merged.
const servers = [{
"key": 0,
"server": 0
},
{
"key": 0,
"server": 1
},
{
"key": 1,
"server": 0
}
];
function customizer(objValue, srcValue, key, fourth) {
if (key === 'server') {
if (!_.isArray(objValue)) objValue = [objValue];
return objValue.concat(srcValue);
}
}
let test = _(servers)
.groupBy('key')
.map((values, key) => {
if (values.length === 1) {
values[0].server = [values[0].server];
return values[0];
}
return _.mergeWith(...values, customizer);
})
.value();
console.log(test);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.11/lodash.min.js"></script>
new Vue({
el: "#app",
data: {
needMergedArray: [
{
key: 0,
server: 0
},
{
key: 0,
server: 1
},
{
key: 1,
server: 0
}
],
},
methods: {
mergeObject() {
let merged = [];
this.needMergedArray.map(item => {
let found = false;
merged.map(element => {
if(item.key === element.key) {
found = true;
if(!element.server) {
//const myserver = [item.server];
element.server =[item.server];
} else {
element.server.push(item.server);
}
}
});
if(!found) {
const myserver = [item.server];
merged.push({key: item.key, server: myserver});
}
found = false;
});
return merged;
}
}
})
// one loop solution: https://jsfiddle.net/haianhnc/2mhsquad/78
mergeObject() {
let merged = {};
this.needMergedArray.map(item => {
merged = {...merged, [item.key]: {key: [item.key], server: (merged[item.key] && merged[item.key].server || []).concat(item.server)}};
});
return Object.values(merged);
}
}
Haven't tested yet
arr.reduce(function(acc,value){
const isExists = acc.findIndex(({key})=>key===value.key)
if(!isExists){
acc.push(value)
} else {
let servers = acc[isExists].server
if(!Array.isArray(servers))
servers = [servers]
servers.push(value.server)
servers = _.uniq(servers)
acc[isExists].server = servers
}
return acc
},[])
I have an forEach loop as follows:
let result_test = [];
forEach(result_to_upload, value => {
if (value.picturepath) {
let body = new FormData();
const photo = {
uri: value.picturepath,
type: 'image/jpeg',
name: value.pictureguid + '.jpg',
};
body.append('image', photo);
let xhr = new XMLHttpRequest();
xhr.open('POST', data_url + "/manager/transport/sync/picture/?pictureguid=" + value.pictureguid);
xhr.onload = (e) => {
if (xhr.readyState === 4) {
if (xhr.status === 200) {
result_test.push(
{
"vehicle_id": value.vehicle_id,
"slot_id": value.slot_id,
"area": value.area,
"zone": value.zone,
"aisle": value.aisle,
"side": value.side,
"col": value.col,
"level": value.level,
"position": value.position,
"timestamp": value.timestamp,
"picturepath": value.picturepath,
"pictureguid": value.pictureguid,
"reason": value.reason,
"handled": value.handled,
"uploaded": 1
}
);
}
}
};
xhr.onerror = (e) => console.log('Error');
xhr.send(body);
} else {
result_test.push(
{
"vehicle_id": value.vehicle_id,
"slot_id": value.slot_id,
"area": value.area,
"zone": value.zone,
"aisle": value.aisle,
"side": value.side,
"col": value.col,
"level": value.level,
"position": value.position,
"timestamp": value.timestamp,
"picturepath": value.picturepath,
"pictureguid": value.pictureguid,
"reason": value.reason,
"handled": value.handled,
"uploaded": 1
}
)
}
});
AsyncStorage.setItem('vehicle_slot', JSON.stringify(result_test), () => s_cb())
And result to upload is as follows:
[
{
aisle:""
area:""
category_text: "CT"
col:2
color_text:"Argent"
comment:""
handled:0
level:0
make_text:"Peugeot"
model_text:"208"
pictureguid:"88e6a87b-b48b-4bfd-b42d-92964a34bef6"
picturepath:
"/Users/boris/Library/Developer/CoreSimulator/Devices/E5DB7769-6D3B-4B02-AA8F-CAF1B03AFCB7/data/Containers/Data/Application/DBCFB503-F8E1-42FF-8C2B-260A713AF7BC/Documents/2D840EFA-014C-48C0-8122-53D9A0F4A88E.jpg"
position:0
reason:"ENTER"
reference:""
registration:""
side:"E"
slot_id:2358
tag_text:""
timestamp:"201705021714"
uploaded:0
vehicle_id:1
vin:"123456"
zone:"A"
},
{
aisle:""
area:""
category_text: "CT"
col:2
color_text:"Argent"
comment:""
handled:0
level:0
make_text:"Golf"
model_text:"208"
pictureguid:"88e6a87b-b48b-4bfd-b42d-92964a34bef6"
picturepath:""
position:0
reason:"ENTER"
reference:""
registration:""
side:"B"
slot_id:2358
tag_text:""
timestamp:"201705021714"
uploaded:0
vehicle_id:1
vin:"123456"
zone:"A"
}
]
But for some reason is AsyncStorage.getItem("vehicle_slot").then(json => console.log(JSON.parse(json)) only the second object, the first one is not added to storage.
Any advice?
your XMLHttpRequest is going to run asynchronously. It's perfectly possible that your code might get to the
AsyncStorage.setItem('vehicle_slot', JSON.stringify(result_test), () => s_cb())
before the onload event has occurred, since that only happens when the request is done. You should add the setItem as a callback.
resultToUpload.forEach(result => {
if (result.picturepath) {
// handle stuff here
let xhr = new XMLHttpRequest();
xhr.onload = (e) => {
// handle other stuff
result_test.push(/* data */);
await storeInAsyncStorage(result_test, () => s_cb());
};
} else {
// handle even more stuff
result_test.push(/* different data */);
await storeInAsyncStorage(result_test, () => s_cb());
}
});
function storeInAsyncStorage(data, callback) {
if(callback) {
return AsyncStorage.setItem(JSON.stringify(data), callback);
} else {
return AsyncStorage.setItem(JSON.stringify(data));
}
}
You should also be aware that AsyncStorage.setItem is asynchronous. The item does not get set immediately, and the setItem method returns a promise that resolves when the item is set. Try using await AsyncStorage.setItem if you're not passing it into some other function.
Im trying to get the MSSQL nodejs package to return the results of a stored procedure from Microsoft SQL server using the code below. However the error I get is...
[TypeError: Cannot read property 'type' of undefined]
I'm not sure I have done the inputs correctly as I couldn't find an example with more than one input anywhere online.
Any ideas?
exports.executeSqlStoredProd = function (callback) {
var conn = new sqlDb.Connection(settings.dbConfig)
conn.connect().then(function () {
var req = new sqlDb.Request(conn);
req.input('ProductEntryID', req.Int, 3299);
req.input('LoginEntryID', req.Int, 4);
req.input('TempLoginEntryId', req.Int, -1);
req.input('AddToWishList', req.Bit, 0);
req.input('WebPortalId', req.Int, 0);
req.execute('J_ViewAProduct').then(function(err, recordsets) {
console.log(recordsets);
callback(recordsets)
})}).catch(function(err){
console.log(err);
callback(null, err);
});
}
I did the request sucessfully using the package "Seriate" but would prefer to use mssql. The code that worked for "Seriate" is below.
exports.getVAP = function(req, resp, pid) {
sql.execute({
procedure: "J_ViewAProduct",
params: {
ProductEntryID: {
type: sql.INT,
val: pid
},
LoginEntryID: {
type: sql.Int,
val: 4
},
TempLoginEntryId: {
type: sql.Int,
val: -1
},
AddToWishList: {
type: sql.Bit,
val: 0
},
WebPortalId: {
type: sql.Int,
val: 0
}
}
}).then(function(results){
console.log(results)
httpMsgs.sendJSON(req, resp, results)
//httpMsgs.sendJSON(req, resp, results[0])
resp.end();
}), function(err){
httpMsgs.show500(req, resp, err)
}
};
I think the line's
req.input('ProductEntryID', req.Int, 3299);
req.input('LoginEntryID', req.Int, 4);
req.input('TempLoginEntryId', req.Int, -1);
req.input('AddToWishList', req.Bit, 0);
req.input('WebPortalId', req.Int, 0);
which has req.input thats wrong it seems.
Please try this code
var sql = require('mssql');
var config = {
user: 'sa',
password: '---',
server: 'localhost', // You can use 'localhost\\instance' to connect to named instance
database: 'Test'
}
var getCities = function() {
var conn = new sql.Connection(config);
conn.connect().then(function(conn) {
var request = new sql.Request(conn);
request.input('City', sql.VarChar(30), 'Cbe');
request.input('NameNew', sql.VarChar(30), 'Cbe');
request.execute('spTest').then(function(err, recordsets, returnValue, affected) {
console.dir(recordsets);
console.dir(err);
}).catch(function(err) {
console.log(err);
});
});
}
getCities();
I tried this myself and its giving the results.
I don't know if this would be helpful or not but this is how I did
let executeQuery = async (value, country) => {
try {
let pool = await sql.connect(dbConfig);
let results = await pool.request()
.input('input_parameter', sql.Int, value)
.input('Country', sql.VarChar(50), country)
// .output('output_parameter', sql.VarChar(50))
.execute('procedure_name')
console.dir(results);
} catch (err) {
res.json({
"error": true,
"message": "Error executing query"
})
}
}
executeQuery(value, country);
I've used async and await method to make it more readable.