Cannot require a class in NodeJs? - node.js

I have two files:
mysqlDAOFactory.js:
var mysql = require('mysql');
var mysqlUserDAO = require('./mysqlUserDAO');
var mysqlSessionDAO = require('./mysqlSessionDAO');
class mysqlDAOFactory {
static createConnection() {
var connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'QASys'
});
return connection;
}
static getDbInstance() {
return mysql;
}
getUserDAO() {
return new mysqlUserDAO();
}
getSessionDAO() {
return new mysqlSessionDAO();
}
}
module.exports = mysqlDAOFactory;
mysqlUserDAO.js:
var mysqlDAOFactory = require('./mysqlDAOFactory.js');
var bcrypt = require('bcryptjs');
var preparedStatements = require('./preparedStatements');
class mysqlUserDAO {
constructor() {
this.connection = mysqlDAOFactory.createConnection();
this.mysql = mysqlDAOFactory.getDbInstance();
}
}
module.exports = mysqlUserDAO;
When I run the file test.js:
var mysqlDAOFactory = require('./mysqlDAOFactory.js');
var UserDAO = mysqlDAOFactory.getUserDAO();
the program is not recognize the variable mysqlDAOFactory in the constructor of class in mysqlUserDAO.js although I require this variable before.
Can anyone explain to me why this happened?
results in chrome debugger tool

I have reviewed your cod and you made a mistake of circular dependencies due to that you fail to run a code.
I have temporary comment mysqlSession file because you did not post MySQL session file.
Please see the running example then please review link as well.
https://repl.it/#DipakC/SO-50542396cannot-require-a-class-in-nodejs
test.js:
//var mysqlDAOFactory = require('./mysqlDAOFactory');
const mysqlUserDAO = require("./mysqlUserDAO");
let objMysqlUserDAO = new mysqlUserDAO();
console.log("---- ---- ----");
console.log(objMysqlUserDAO);
console.log("---- ---- ----");
mysqlUserDAO.js
var mysqlDAOFactory = require('./mysqlDAOFactory');
var bcrypt = require('bcryptjs');
class mysqlUserDAO {
constructor() {
this.connection = mysqlDAOFactory.createConnection();
this.mysql = mysqlDAOFactory.getDbInstance();
}
}
module.exports = mysqlUserDAO;
mysqlDAOFactory.js
var mysql = require('mysql');
var mysqlUserDAO = require('./mysqlUserDAO');
//var mysqlSessionDAO = require('./mysqlSessionDAO');
class mysqlDAOFactory {
static createConnection() {
var connection = mysql.createConnection({
host:'localhost',
user:'root',
password:'',
database:'QASys'
});
return connection;
}
static getDbInstance() {
return mysql;
}
static getUserDAO() {
return new mysqlUserDAO();
}
/* getSessionDAO() {
return new mysqlSessionDAO();
} */
}
module.exports = mysqlDAOFactory;

Related

MongoError: Document must be a valid JavaScript object

I have a problem where MongoDB says that my object is not a valid JavaScript Object, Even though it is! This has been staying for days!
Basically, this is an account system that uses MongoDB's client, and the ObjectId for the ID.
I want to be able to fix the MongoError that says object (sent to updateOne, not filter) is not a valid JavaScript object.
Here is the code:
const { MongoClient, ObjectId } = require("mongodb");
const fs = require("node:fs");
const uri = "mongodb://127.0.0.1:27017";
if (!fs.existsSync("./db")) {fs.mkdirSync("./db")};
const client = new MongoClient(uri,{ useUnifiedTopology: true });
async function conn() {
await client.connect();
}
conn();
const database = client.db("login");
const accs = database.collection("accounts");
const myfil = {
_id: new ObjectId('63b6441832087ccc7e3edea2')
};
const users = accs.findOne(myfil);
const path = require("node:path");
const bcrypt = require('bcrypt');
const env = process.env;
var saltRounds = 10;
const AddSet = class AddSet {
constructor(user,pass) {
console.log(pass);
this.set = {[user]:pass};
this.set = Object.keys(this.set).reduce((acc, key) => {
acc[key.toString()] = this.set[key];
return acc;
}, {});
console.log(this.set);
return this.set;
}
}
const Account = class Account {
constructor(user,password) {
conn();
if (!users[user]) {
conn();
accs.updateOne(myfil,bcrypt.hash(password, saltRounds, function(err, hash)
{
try {
var a = ""+user;
return new AddSet(a.toString(),hash);
} catch(err) {
console.error("bcrypt",err);
}
}));
this.assetDir = path.join(path.join(env.SAVED_FOLDER,"/"+this.user),"/assets");
this.metaDir = this.assetDir + '/meta';
this.starterDir = path.join(path.join(env.SAVED_FOLDER,"/"+this.user),"/starters");
this.videoDir = path.join(path.join(env.SAVED_FOLDER,"/"+this.user),"/videos");
var fs = require('fs');
if (!fs.existsSync(this.assetDir)) fs.mkdirSync(this.assetDir, { recursive: true });
if (!fs.existsSync(this.starterDir)) fs.mkdirSync(this.assetDir, { recursive: true });
if (!fs.existsSync(this.videoDir)) fs.mkdirSync(this.assetDir, { recursive: true });
}
}
getAssetDir() {
return this.assetDir;
}
getStarterDir() {
return this.starterDir;
}
getVideoDir() {
return this.videoDir;
}
getMetaDir() {
return this.metaDir;
}
checkSession(pswd) {
conn();
bcrypt.compare(pswd, users[this.user], function(err, result) {
if (result) return true;
else return false;
});
}
}
module.exports = { Account, users };
I tried fixing it, making the keys strings, removing the $set, and it did not work.

getting error : Cannot read property 'findOne' of undefined in node js

i have created sample page, and when i run my page node airbnb-library.js i am getting error, Cannot read property 'findOne' of undefined can anyone please help me why i am getting this error ? here i have attached my code, can anyone please look my code and help me to resolve this issue ? any help will be really appreciated...
db.js
const config = require('../config.json');
const mysql = require('mysql2/promise');
const { Sequelize } = require('sequelize');
module.exports = db = {};
initialize();
async function initialize() {
// create db if it doesn't already exist
const { host, port, user, password, database } = config.database;
const connection = await mysql.createConnection({ host, port, user, password });
await connection.query(`CREATE DATABASE IF NOT EXISTS \`${database}\`;`);
// connect to db
const sequelize = new Sequelize(database, user, password, { host: host, port: port, dialect: 'mysql' });
// init models and add them to the exported db object
db.User = require('../users/user.model')(sequelize);
db.Airbnb = require('../users/airbnb.model')(sequelize);
// sync all models with database
await sequelize.sync();
}
airbnb-library.js
const http = require("http");
const requestapi = require('request');
const airbnb = require('airbnbapijs')
async function test() {
const airbnbdata = await airbnb.newAccessToken({ username: 'dino#pushideas.com', password: 'Christmas2016!'})
console.log(airbnbdata);
}
let airbnbdata = test();
main.js
const config = require('../../../config.json');
const airbnb = require('airbnbapijs')
const requestapi = require('request');
const http = require("http");
async newAccessToken({ username, password } = {}) {
try {
await this.airbnblogin({"email":username,"password":password});
} catch (e) {
console.log(e);
}
}
async airbnblogin(params) {
let account = await db.Airbnb.findOne({ where: { airbnb_email: params.email, } })
}

ReferenceError: name is not defined

I have a code in Controller
const getLocalDatabaseResule = async (searchURL, reqBody) => {
commonCode(reqBody);
console.log(name);
});
function commonCode(reqBody) {
var name = reqBody.name;
var phone= reqBody.phone;
var email = reqBody.email;
}
Any idea how to add common function in controller
You need to return the body from commonCode
const getLocalDatabaseResule = async (searchURL, reqBody) => {
const {name,phone,email} = commonCode(reqBody);
console.log(name);
};
function commonCode(reqBody) {
const name = reqBody.name;
const phone= reqBody.phone;
const email = reqBody.email;
return {name,phone,email}
}
getLocalDatabaseResule("searchURL", {name:"User",phone:"111", email:"mail#mail.com"})
Also this is possible
const getLocalDatabaseResule = async (searchURL, reqBody) => {
var x = commonCode(reqBody);
console.log(x.name);
});
function commonCode(reqBody) {
this.name = reqBody.name;
this.phone= reqBody.phone;
this.email = reqBody.email;
}

Pg-Promise problem connecting with sslrootcert specified

I am having issues trying to connect to a managed database on Digital Ocean which has sslmode=require.
The connection string I have been given to use is as follows:
postgresql://username:password#server:port/mydb?sslmode=require
my db.js file looks like this:
"use strict";
const fs = require('fs')
const pgPromise = require("pg-promise");
const {ConnectionString} = require('connection-string');
const path = require('path');
var options = {
// Initialization Options
};
let pgp = pgPromise(options);
const dotenv = require('dotenv');
dotenv.config();
const a = new ConnectionString('postgresql://username:password#server:port/mydb?sslmode=require')
var cert= fs.readFileSync(__dirname + '/certs/ca-certificate.crt', 'utf8')
a.setDefaults({
params: {
sslrootcert : cert
}
});
var connstring = a.toString();
let dbpool = pgp(connstring);
module.exports = { dbpool };
When I initially start the process, everything seems to go fine, but when I attempt to hit the database I get:
Error: ENOENT: no such file or directory, open 'C:\Users\Me\Documents\GitHub\tester\-----BEGIN CERTIFICATE----- certificate info -----END CERTIFICATE-----
if I change the pgp connection to accept the ConnectionString object instead
eg.
let dbpool = pgp(a); then I seem to connect with the server, but get authentication errors. Changing my connection string to point at my local db with let dbpool = pgp(a)results in me getting strange errors such as column does not exist. But pointing at local with let dbpool = pgp(connstring); seems to work fine. Due to this, I am presuming that I need to be using let dbpool = pgp(connstring);.
The rest of my relevant code (this is just a simple test project for connecting to the managed db) is as follows:
routes/index.js
"use strict";
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
const userrepository_1 = require("../repositories/userrepository");
var express = require('express');
var router = express.Router();
/* GET home page. */
router.get('/', function(req, res, next) {
res.render('index', { title: 'Express' });
});
/* HIT DATABASE. */
router.get('/testdb', (req, res) => __awaiter(void 0, void 0, void 0, function* () {
let userRepos = new userrepository_1.UserRepository();
let userid = yield userRepos.getuserbyusername("myusername");
if (userid == null) {
return res.status(404).send({ auth: false, message: 'No user found' });
}
res.render('dbtest', { userid: userid });
}))
module.exports = router;
repositories/userrepository.js
"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const dbProvider = require("../db");
class UserRepository {
constructor() {
this.db = dbProvider.dbpool;
}
getuserbyusername(username) {
return new Promise((resolve, reject) => { resolve(this.db.oneOrNone('SELECT * FROM users
where isdeleted=false AND username=$1', [username])); })
.then((user) => {
if (user != null) {
let uid = user.userid;
return uid;
}
else {
return null;
}
});
}
}
exports.UserRepository = UserRepository;
My directory structure is:
/bin
www
/certs
ca-certificate.crt
/node_modules
/public
/repositories
userrepository.js
/routes
index.js
/views
app.js
db.js
Like I say I think the issue is with let dbpool = pgp(connstring);
Okay, was a simple fix for this. Rather than reading the file with const cert = fs.readFileSync(__dirname + '/certs/ca-certificate.crt', 'utf8'), I just needed to specify the location. Hence:
const path = require('path');
const cs = new ConnectionString('postgresql://username:password#server:port/mydb?sslmode=require');
const sslrootcert = path.join(__dirname, 'ca-certificate.crt');
cs.setDefaults({
params: { sslrootcert }
});
const db = pgp(cs.toString());
(I also moved the certificate to my home directory)

Node.js, Express.js and sqllite3.js

I have a problem with object attributes in Node.js. While attributes are set as expected in the test object, the same doesn't work for my articles object. The difference I see is that the functions of articles are called asynchronously. I must confess that I am a bit lost...
Here is app.js, that instantiates the test object and the articles object.
/**
* Load express.
*/
var express = require('express');
var app = express();
/**
* Load articles.
*/
var articles = require('./article.js');
var l_articles = new articles.Articles();
var test = require('./test.js');
var l_test = new test.Test();
app.get('/', function (req, res) {
console.log(l_test.get());
l_test.set('it is', 'midnight');
console.log(l_test.get());
articles.Articles.get(1);
res.send('OK');
})
app.listen(3001, function () {
console.log(l_test.get());
l_test.set('goodbye', 'sunshine');
console.log(l_test.get());
})
Here is my fairly simple test.js :
var app = require('./app.js');
function Test() {
this.timestamp = new Date();
console.log(this.timestamp);
this.attribute1 = 'hello';
this.attribute2 = 'world';
}
Test.prototype.get = function() {
console.log(this.timestamp);
return (this.attribute1 + ' ' + this.attribute2);
}
Test.prototype.set = function(p_param1, p_param2) {
console.log(this.timestamp);
this.attribute1 = p_param1;
this.attribute2 = p_param2;
}
module.exports = {
Test: Test
};
Here is my fairly simple article.js :
var sqlite3 = require('sqlite3').verbose();
var app = require('./app.js');
function Articles(p_id) {
this.timestamp = new Date();
console.log(this.timestamp);
this.db = new sqlite3.Database('./gescom.sqlite');
if (p_id == undefined) {
this.db.all('SELECT * FROM T_ARTICLE', this.load);
} else {
this.db.all('SELECT * FROM T_ARTICLE WHERE id = ' & p_id, this.load);
}
}
Articles.prototype.load = function(p_err, p_rows) {
console.log(this.timestamp);
var ids = [];
var articles = [];
p_rows.forEach(function(p_row) {
ids.push(p_row.ID);
articles.push([p_row.ID, p_row.SHORT_NAME]);
});
this.ids = ids;
this.articles = articles;
console.log(this.ids.length + ' articles loaded from database.');
}
Articles.prototype.get = function (p_id) {
console.log(this.timestamp);
var l_return;
if ((this.ids == undefined) || (this.articles == undefined)) {
console.log('No articles loaded from database.');
} else {
console.log(this.ids.length + ' articles loaded from database.');
if (p_id == undefined) {
l_return = this.articles;
} else {
if (this.ids.indexOf(p_id) != undefined) {
l_return = (this.articles[this.ids.indexOf(p_id)]);
} else {
l_return = undefined;
}
}
}
return l_return;
}
module.exports = {
Articles: Articles
};

Resources