Node js - Global variables to be used in different files - node.js

I have a main file called index.js. Here, I want to do some global stuff which can be used by different js file:
const algoliasearch = require('algoliasearch');
const firebase = require('firebase');
const firebaseAdmin = require('firebase-admin');
var dotenv = require('dotenv');
var app = require('express')();
const express = require('express')
const scheduler = require('node-schedule')
const dateFormat = require('dateformat');
const OneSignal = require('onesignal-node');
const client = new OneSignal.Client('XXX', 'XXX');
const path = require('path')
const PORT = process.env.PORT || 5000
// load values from the .env file in this directory into process.env
dotenv.load();
firebaseAdmin.initializeApp({
databaseURL: process.env.FIREBASE_DATABASE_URL
});
firebase.initializeApp({
apiKey: 'XXX',
projectId: 'XXX'
});
const algolia = algoliasearch(
process.env.ALGOLIA_APP_ID,
process.env.ALGOLIA_API_KEY
);
var database = firebase.firestore();
const constant = require('./Constant.js')
const tournamentDataAccessService = require('./TournamentDataAccessService.js')
const tournamentParticipationDataAccessService =
require('./TournamentParticipationDataAccessService.js')
constant = new Constants()
My problem occurs in line constant = new Constants()
Here we need to check the Constants.js
class Constants {
constructor() {
console.log(database) // database is defined in index.js file
}
}
Compiler complains about database;. To be more precise, database can't be found. How can I access the database variable in the index.js? file? I could pass the variable as a parameter to the constructor of Constants.js but is there a different solution?

Related

Mongoose not fetching data in nodejs

No data is fetched while using mongoshell, it is working fine
server.js file
const express = require('express')
const app = express()
const cors = require('cors')
const mongoose = require('mongoose')
const topicRoute = require('./routes/topicRoute')
app.use(cors())
app.use(express.json())
const dbUri = "mongodb+srv://rohan:password#db_name.qg229.mongodb.net/db_name"
mongoose.connect(dbUri)
app.use("/",topicRoute)
app.listen(3001,function(){
console.log("Server started")
})
routes/topicRoute.js file, no error is catched here & object Object is returned
const express = require('express')
const router = express.Router()
const Topic = require('../models/topicModel')
router.route("/topics").get((req,res)=>{
Topic.find().then(fetchedTopics => res.json(fetchedTopics))
})
module.exports = router
models/topicModel.js file
const mongoose = require('mongoose')
const topicSchema = {
topic_id: String,
topic_name: String,
topic_description: String,
}
const Topic = mongoose.model('topics',topicSchema)
module.exports = Topic
Try with this code for database connection
// database connection
const { MongoClient, Collection } = require('mongodb');
const url = 'mongodb://localhost:27017' const database = 'ecom' // database name define here const collectionName = 'reviews'; //database collection define here const client = new MongoClient(url);
async function getData(){
let result =await client.connect();
let db = result.db(database)
let collection = db.collection(collectionName)
let response = await collection.find({}).toArray()
console.log(response); }
getData();

TypeError: mongodb_1.ObjectID is not a constructor with GridFsStorage

I'm new to nodejs along with mongoDB, can anyone please help me to solve this issue. i used to multer, multer-gridfs-storage, gridfs-stream for uploading file and images.
But i'm getting this TypeError: mongodb_1.ObjectID is not a constructor in resolve() inside the promise in GridFsStorage. i have shared the code below.
const express = require('express');
const app = express();
require('dotenv').config()
const PORT = process.env.PORT;
const morgan = require('morgan');
const multer = require('multer');
const {GridFsStorage} = require('multer-gridfs-storage');
const Grid = require('gridfs-stream');
const methodOverride = require('method-override');
const mongoose = require('mongoose');
const path = require('path');
const crypto = require('crypto');
const MongoURI = "atlas url";
app.use(methodOverride('_method'));
app.use(express.json())
app.use(morgan(':method :status :url'));
const connectDB = mongoose.createConnection(MongoURI,{useUnifiedTopology:true,useFindAndModify:false, useNewUrlParser:true,useCreateIndex: true})
let gfs;
connectDB.once('open',()=>{
console.log("dbConnected....")
gfs = Grid(connectDB.db,mongoose.mongo)
gfs.collection('uploads');
})
const storage = new GridFsStorage({
url:MongoURI,
file:(req,file)=>{
return new Promise((resolve, reject)=>{
crypto.randomBytes(16,(err,buf)=>{
console.log("buf",buf)
if(err){
return reject(err);
}
const filename = buf.toString('hex') + path.extname(file.originalname);
console.log("filename",filename)
const fileInfo = {
filename:filename,
bucketName:'uploads'
};
resolve(fileInfo)
})
})
}
})
app.listen(PORT,()=>{
console.log(`port connected....${PORT}`)
})
const upload = multer({storage:storage})
app.post('/uploadfile',upload.single('file'),async(req,res)=>{
res.json({
file:req.file
})
})
My solution is to change the mongodb_1.ObjectID() inside its node module's gridfs.js file into mongodb_1.ObjectI"d"() and everything works. I guess the author is writing for the old version of mongodb, but in my case it's the newer version so "d" should be lowercase.
Update:
Someone just post an issue to the author's github, you can follow this page for official solutions.
You must call mongodb.ObjectId and not ObjectID, and then you can have a const with that name. But with ObjectId everything will work.
Keep on coding.
Visit https://github.com/devconcept/multer-gridfs-storage/issues/352#issue-946945336 Changing the method name from ObjectID() to ObjectId() of mongodb_1 class worked for me, looks like a compatibility issue in gridfs.js file in node_modules.

TypeError: puppeteer.use(...) is not a function when trying to run my code

Here is my code that I currently have. For some reason it was working and I switched it to a new folder and am now getting this error. All the modules were re-installed under the package.json file. Is there anyway of fixing this.
const puppeteer = require('puppeteer');
const get = require('http');
const Server = require('https');
const pathToFileURL = require('url');
const path = require ('./path.json');
const shippinginfo = require('./shippinginfo.json');
const Discord = require('discord.js');
const fs = require('fs');
const { prefix, token} = require('./config.json');
const client = new Discord.Client();
client.commands = new Discord.Collection();
const config = require('./config.json');
const puppeteer2 = require("puppeteer-extra")
const webhookClient = new Discord.WebhookClient(config.webhookID, config.webhookToken);
const fetch = require('node-fetch');
const cookies = fs.readFileSync('./cookies.json', '');
const RecaptchaPlugin = require('puppeteer-extra-plugin-recaptcha');
const captchatoken = require("./token.json");
const request = require('request-promise-native');
const poll = require('promise-poller').default;
const StealthPlugin = require('puppeteer-extra-plugin-stealth')
const apiKey = config.apikey
var userAgent = require('user-agents');
puppeteer2.use(
RecaptchaPlugin({
provider: { id: '2captcha', token: "aa40e25b217d84b26ba0e4b3928bc51d" },
visualFeedback: true // colorize reCAPTCHAs (violet = detected, green = solved)
})
)
puppeteer2.use(StealthPlugin())
puppeteer.use(require('puppeteer-extra-plugin-stealth')())

How I can do a module.exports for a Pool of Postgres

I have been getting a problem when I want to module.export the pool variable to use it in other files. I have this program in src\db\index.js:
const {Pool} = require('pg');
const express = require('express');
//Initialize
const path = require('path');
const app = express();
const fetch = require('fetch');
const PORT = process.env.PORT || 5000;
//Global Variables
const pool = new Pool({
connectionString: process.env.DATABASE_URL,
ssl:true
});
//Setting
app.use(express.static(path.join(__dirname, 'public')));
//Routes
app.use(require('../Routes/logIn'));
app.use(require('../Routes/singIn'));
app.use(require('../Routes/forgotPass.js'));
app.listen(PORT, () => console.log(`Listening on ${PORT}`));
module.exports = pool;
And then I want to require the const pool in this file src\Routes\LogIn.js:
const express = require('express');
const pool = require('../db');
const router = express.Router();
router.get('/usuario/:user', function (req, res) {
//console.log("GET usuario");
var user = req.params.user;
pool.query(
`select * from users where email = '${user}' limit 1`,
function (error, resq, fields) {
if (error) {
console.log(error);
} else {
console.log(user);
res.send(resq.rows);
}
}
);
});
module.exports = router;
But when I run the index.js and go to the route ulr/usuario/:user, in the logs I see that the program has an error that says "pool.query is not a function". I want to know how i could export the const pool to use it in other files.
You can use
module.exports = {
query: (text, params) => pool.query(text, params),
}
Use express-promise-router
const Router = require('express-promise-router')
const db = require('../db')
const router = new Router()
Use
await db.query(`
SELECT * from local
`)
instead of pool.query in your router.get or router.post
The above should solve your issue - You can check the same reference here
https://node-postgres.com/guides/async-express

json-server with express/ db.json is not reflecting changes

We are having a simple json-server setup, loading it as a module.
However, when making a POST/PUT request, the data is not being injected into the db.json.
const jsonServer = require("json-server");
const source = require("./db.json");
const repl = require("replify");
const bodyParser = require("body-parser");
const paginationMiddleware = require("./middlewares/pagination");
const filterByAccessRightFor = require("./middlewares/filterByAccessRightFor");
const searchMiddleware = require("./middlewares/search");
const delayMiddleware = require("./middlewares/delay");
const createdAt = require("./middlewares/created_at");
const daterange = require("./middlewares/daterange");
const absence = require("./middlewares/absence");
const bankAccount = require("./middlewares/bankAccount");
const sort = require("./middlewares/sort");
const fileUpload = require("express-fileupload");
const withUser = require("./responseEnhancers/withUser");
const withAbsenceType = require("./responseEnhancers/withAbsenceType");
const withIndexData = require("./responseEnhancers/withIndexData");
const withNationalStateHolidayOverride = require("./responseEnhancers/withNationalStateHolidayOverride");
const withRoleRestrictions = require("./responseEnhancers/withRoleRestrictions");
const compose = require("lodash/fp/compose");
const initSickImagesEndpoint = require("./features/sicks/images/initEndpoint");
const initLoginEndpoint = require("./features/login/initEndpoint");
const path = require("path");
const express = require("express");
const createCalendarEntry = require("./_helpers/createCalendarEntry");
process.on("createCalendarEntry", createCalendarEntry);
const server = jsonServer.create();
const defaultMiddlewares = jsonServer.defaults({
static: path.join(path.resolve(process.cwd()), "server", "files")
});
const router = jsonServer.router(source, {
foreignKeySuffix: "_id"
});
router.render = (req, res) => {
res = compose(
withIndexData(req),
withUser,
withAbsenceType,
withNationalStateHolidayOverride(req),
withRoleRestrictions(req, db)
)(res);
res.jsonp(res.locals.data);
};
const db = router.db;
if (process.env.NODE_ENV === "production")
server.use(express.static(path.join(__dirname, "../build")));
server
.use(
jsonServer.rewriter({
"/de/*": "/$1"
})
)
.use(bodyParser.json())
.use(fileUpload())
.use(defaultMiddlewares)
.use(paginationMiddleware)
.use(searchMiddleware)
.use(delayMiddleware)
.use(createdAt)
.use(daterange)
.use(absence)
.use(bankAccount)
.use(sort);
initLoginEndpoint(server, db);
initSickImagesEndpoint(server, db);
server.route("/sicks").all(filterByAccessRightFor(db));
server.route("/vacations").all(filterByAccessRightFor(db));
server.use(router);
server.listen(3001, "0.0.0.0", () => {
console.log("JSON Server is running");
});
repl("db", server, { db });
exports.db = db;
module.exports = server;
This is our index.js and apart from the db.json not updating, everything is working fine as expected. We have a script that is seeding the db, and when accessing a resource via GET the correct data gets retrieved.
Any ideas on that one?
Instead of providing a JSON object using require for the db.json file, you should provide a path to the json file.
// const source = require("./db.json");
const source = path.join(__dirname, 'db.json')
const router = jsonServer.router(source, {
foreignKeySuffix: "_id"
});

Resources