nodejs connecting to db only once - database

I have a db.js file that has this line in the top to connect to the database.. i call this file to run queries from inside other js files:
var sqlite3 = require('sqlite3').verbose();
var db = new sqlite3.Database('./mydatabase');
db.serialize(function() {
db.each("SELECT rowid AS id, info FROM lorem", function(err, row) {
console.log(row.id + ": " + row.info);
});
db.close();
If i require() this above file 4 times in different files, does this mean sqlite database will be initialized that many times?
I want to initalize it only the first time..
Is this inefficient? Is there a more efficient way?

Official documentation: https://github.com/mapbox/node-sqlite3/wiki/Caching
Sqlite3 module can do caching internally if you use require('sqlite3').cached, i.e. it won't create new connections on new sqlite3.cached.Database(file) as long as string held by file is identical, but reuse existing ones. See in the source for yourself here:
https://github.com/mapbox/node-sqlite3/blob/master/lib/sqlite3.js
However, you should not depend on that. Do some kind of dependency injection, it will save many headaches along the way. In simplest form it will be writing your modules that they export functions accepting database object as their argument:
//module1.js
module.exports = function(db){
db.serialize(...)
//dostuff
}
//start.js
var sqlite3 = require('sqlite3').verbose();
var module1 = require('./module1.js');
var db = new sqlite3.Database('./mydatabase');
module1(db);

Related

test database for react-native app development

I'm in the early stages of developing an app with react-native, and I need a DB implementation for for testing and development. I thought that the obvious choice would be to use simple JSON files included with the source, but the only way I see to load JSON files requires that you know the file name ahead of time. This means that the following does not work:
getTable = (tableName) => require('./table-' + tableName + '.json') // ERROR!
I cannot find a simple way to load files at runtime.
What is the proper way to add test data to a react-native app?
I cannot find a simple way to load files at runtime.
In node you can use import() though I'm not sure if this is available in react-native. The syntax would be something like:
async function getTable(tableName){
const fileName = `./table-${tableName}.json`
try {
const file = await import(fileName)
} catch(err){
console.log(err
}
}
though like I said I do not know if this is available in react-natives javascript environment so ymmv
Unfortunately dynamic import not supported by react-native but there is a way so to do this
import tableName1 from './table/tableName1.json';
import tableName2 from './table/tableName2.json';
then create own object like
const tables = {
tableName1,
tableName2,
};
after that, you can access the table through bracket notation like
getTable = (tableName) => tables[tableName];

Ionic 3 I can't call data with SQLite

I am using SQLite on the project. I perform events like insert operations in database operations successfully. But I do not know how to reach the data when it brings the data. I am trying to create a list of the following code fragment. I'm waiting for your help.
GRUPLISTESI : any;
GRUPLAR(){
var sql = "SELECT * FROM 'GRUPLAR'";
this.db.executeSql(sql, {}).then((data)=>{
this.GRUPLISTESI = data["rows"]; //What should I write here?
});
}
You can access the data from your Ionic sqlite database like this:
db.executeSql("SELECT * FROM test")
.then(result => {
console.log(result.rows.item(0).id);
});
So abstract it would look like so: result.rows.item([row]).[column_label].
For some deeper examples on how to use sqlite for Ionic, you can use this repository: https://github.com/didinj/ionic3-angular4-cordova-sqlite-example

Mapping relational MongoDB data in website : help needed

I run an Android app which locates OBJECTS with attributes like ID, Name, Owner, Type, Place_ID which are linked to PLACES, on a map. PLACES have attributes like ID, Latitude, Longitude, Opening Hour, Closing Hour,... The data is stored in a MongoDB on Back4App and I want to keep that way. I have one class for OBJECTS and one class for PLACES. The relation between OBJECTS and PLACES is not "a MongoDB relation", it is just a common String field in the OBJECTS and PLACES classes.
In order to allow offline access to the data and to minimize DB server requests, the app synchronizes a local SQLITE database on the device with the MongoDB online database. In the Android App, the queries are passed to the SQLITE DB.
I'm trying to make a website which does the same job as the app, which is displaying filtered data from the MongoDB.
I started with a simple html and javascript website using the Parse SDK, but I'm facing a few difficulties.
A simple query is to list all the OBJECTS in a 50km radius, i.e. I need the OBJECTS and the PLACE where they are located. However, where I could get this easilty with a SELECT...JOIN in SQLITE, I cannot get this information through a simple Parse query because I want to know the OBJECTS too. And I cannot run 2 asynchronous queries in a for loop.
What website architecture and/or languages would you recommend for this type of website ?
How would you recommend to proceed ?
Thanks in advance for your help.
EDIT: ZeekHuge opened my eyes on the bad design of not using pointers. After implementing pointers in my MongoDB, here's the lines of codes which did it for me :
Parse.initialize("", "");
Parse.serverURL = '';
var eiffel = new Parse.GeoPoint(48.858093, 2.294694);
var myScores = '';
var Enseigne = Parse.Object.extend("ENSEIGNE");
var Flipper = Parse.Object.extend("FLIPPER");
var query = new Parse.Query(Flipper);
var innerquery = new Parse.Query(Enseigne);
innerquery.withinKilometers("ENS_GEO",eiffel,500);
query.equalTo("FLIP_ACTIF", true);
query.include("FLIP_ENSPOINT");
query.include("FLIP_MODPOINT");
query.matchesQuery("FLIP_ENSPOINT", innerquery);
query.find({
success: function(results) {
for (var i = 0; i < results.length; i++) {
var object = results[i];
myScores += '<tr><td>' + object.get('FLIP_MODPOINT').get('MOFL_NOM')
+ '</td><td>' + object.get('FLIP_ENSPOINT').get('ENS_NOM')
+ '</td><td>' + object.get('FLIP_ENSPOINT').get('ENS_GEO').latitude
+ '</td><td>' + object.get('FLIP_ENSPOINT').get('ENS_GEO').longitude
+ '</td></tr>';
}
(function($) {
$('#results-table').append(myScores);
})(jQuery);
},
error: function(error) {
alert("Error: " + error.code + " " + error.message);
}
});
Solved by replacing the database keys by pointers and using the Innerquery and include functions. See exemple mentionned in question.

Updating Redux with Sqlite3 in an Electron application

I am writing an Electron application and I want to display some data from a local sqlite3 database file. I am using React as my front-end framework and Redux to update the table data. However I am having trouble figuring out what's the best way to query from the .db file and update Redux with the new data. Can someone give me some insights on what is the best way to go about it?
I was able to load a .db file using the node module sqlite3 and included a javascript function as such:
var sqlite3 = require('sqlite3').verbose();
let dbSrc = 'processlist.db';
var fetchDBData = (tablename) => {
var db = new sqlite3.Database(dbSrc);
var queries = [];
db.each("SELECT * FROM " + tablename, function(err, row) {
queries.push(row);
});
db.close();
return queries;
};
Since I am using React and Redux for my front end, I was able to invoke this function by calling
window.fetchDBData(tablename);

How to Encrypt data in JMeter script

I am writing a simple script in Jmeter to pass username and password to the logging page of a website. I want password to be encrypted but I am not sure if Selenium Webdriver API provide any functions to encerypt data before passing it into the sendKeys() function.
Here's what my script looks like:
WDS.sampleResult.sampleStart()
WDS.browser.get('url')
var pkg = JavaImporter(org.openqa.selenium, org.openqa.selenium.support.ui)
var wait = new pkg.WebDriverWait(WDS.browser, 5000)
var user = WDS.browser.findElement(pkg.By.id('userName'))
user.sendKeys(['username])
var pass = WDS.browser.findElement(pkg.By.id('password'))
pass.sendKeys(['password'])
PS: I know the approach to pass data from CSV but that's not exactly encryption.
Put the jar that contains the encryption algorithm in jmeter/lib.
Suppose this class is in class com.foo.utils.encryption.EncryptionUtils, you would do:
var pkg = JavaImporter(com.foo.utils.encryption)
var encryptUtils = new pkg.EncryptionUtils()
vars.put("result", encryptUtils.method(inputString));
You can then use the ${result} variable.

Resources