Node- Unable to require in an module.export - javascript

I am working with a RabbitMQ connection and exporting the channel after creating the same to import it in the routes file in my nodejs code.
But for some reason, it is undefined when imported in the routes.js file.
Export
let connection;
let channel;
const connect = async () => {
try {
const amqpServer = 'amqp://localhost:5672';
connection = await amqp.connect(amqpServer);
channel = await connection.createChannel();
await channel.assertQueue('product');
console.log('Product service connected to RABBITMQ');
} catch (error) {
console.log(error);
}
};
connect();
module.exports.connection = connection;
module.exports.channel = channel;
routes.js
const { channel } = require('./index');
console.log(channel) // 👈 undefined
Idk what is it that I am missing here.

CommonJS require is synchronous so you should write something like this:
Export
const connect = async () => {
try {
const amqpServer = 'amqp://localhost:5672';
const connection = await amqp.connect(amqpServer);
const channel = await connection.createChannel();
await channel.assertQueue('product');
console.log('Product service connected to RABBITMQ');
return [connection, channel];
} catch (error) {
console.log(error);
}
};
module.exports = connect();
routes.js
const [connection, channel] = await require('./index');
console.log(channel) // 👈 defined 🎉🎉🎉

Try it this way
let connection;
let channel;
const connect = async () => {
try {
const amqpServer = 'amqp://localhost:5672';
connection = await amqp.connect(amqpServer);
channel = await connection.createChannel();
await channel.assertQueue('product');
console.log('Product service connected to RABBITMQ');
} catch (error) {
console.log(error);
}
};
connect();
exports.connection = connection;
exports.channel = channel;

Related

discordjs/voice simple request help for works

(sry for my English)
I just want to make a simple reaction message, connection to vocal where user use one word as "exemple" in this "it is an exemple", and play one song.mp3, after the bot deconnect when he finish this song.mp3.
This is my index.js
const { Client, VoiceChannel, Intents } = require('discord.js');
const client = new Client({ intents: 32767 });
const dotenv = require('dotenv'); dotenv.config();
const {
joinVoiceChannel,
createAudioPlayer,
createAudioResource,
entersState,
StreamType,
AudioPlayerStatus,
VoiceConnectionStatus,
} = require ('#discordjs/voice');
const { createDiscordJSAdapter } = require ('./?');
const player = createAudioPlayer();
client.login(process.env.DISCORD_TOKEN);
function playSong() {
const resource = createAudioResource('./music/try.mp3', {
inputType: StreamType.Arbitrary,
});
player.play(resource);
return entersState(player, AudioPlayerStatus.Playing, 5e3);
};
client.on('ready', async () => {
console.log('Discord.js client is ready!');
try {
await playSong();
console.log('Song is ready to play!');
} catch (error) {
console.error(error);
}
});
async function connectToChannel(channel = VoiceChannel) {
const connection = joinVoiceChannel({
channelId: channel.id,
guildId: channel.guild.id,
adapterCreator: createDiscordJSAdapter(channel),
});
try {
await entersState(connection, VoiceConnectionStatus.Ready, 30e3);
return connection;
} catch (error) {
connection.destroy();
throw error;
}
};
client.on('messageCreate', async (message) => {
if (!message.guild) return;
if (message.content === '-join') {
const channel = message.member?.voice.channel;
if (channel) {
try {
const connection = await connectToChannel(channel);
connection.subscribe(player);
await message.reply('Playing now!');
} catch (error) {
console.error(error);
}
} else {
void message.reply('Join a voice channel then try again!');
}
}
});
I have this error :
Screenshot of console error
This error is here in my index.js :
const { createDiscordJSAdapter } = require ('./?');
I just don't know how import this function createDiscordJSAdapter ....
I have my .env file true, (the bot is connected to my server).
I have my folder music with my song name "try.mp3".
And this index.js :D
If someone can help me to build this simple exemple,
Thx !
Sunclies

How to call a javascript function inside another function in node js

I have a file index.js as below. Where I am trying to call a async function getConn in other function createThumbnails. But I am getting the error as "failed to connect to DEDC: 1433 - self signed certificate" in the catch block.
const sharp = require('sharp');
const sql = require('mssql')
// CONNECTION CONFIGURATION OF BASE DB
async function getConn() {
try {
const config = {
user: 'sa_user',
password: '*******',
server: 'DEDC',
database: 'DEMO_BASE'
}
const pool = await new sql.ConnectionPool(config)
const req=await pool.connect()
const conn = await req.request()
return conn;
} catch (err) {
return err;
}
};
const createThumbnails = async() => {
try{
var conn = await getConn();
const query = `exec DBBASE.get_client_info`
var clientusers = await conn.query(query);
} catch (err) {
return err;
}
}
createThumbnails()
How do I exactly call the function getConn inside createThumbnails. Please help. Thanks in advance
It's because you are using variable with the same name as the function.
Try different name:
var conn = await getConn();
const query = `exec DBBASE.get_client_info`
var clientusers = await conn.query(query);
You encounter what called hoisting. Kyle Simpson has a great explaination on this topic
var getConn = await getConn();
which means getConn will be initialized first, before assignment, which equivalents to
var getConn // initialized
getConn = await getConn() // assignment
Then turned out that you got the error
Solution here is to store it in a different variable name, like
var conn = await getConn();
async function getConn() {
return {
query: async () => {
console.log("query called");
},
};
}
const createThumbnails = async () => {
try {
var conn = await getConn();
const query = `exec DBBASE.get_client_info`;
var clientusers = await conn.query(query);
} catch (err) {
console.log(err);
}
};
createThumbnails();
We need to use trustServerCertificate: true in DB configuration i.e in const config

How to call a function directly through cmd to fetch and update records into database through Node js

I have a file CreateNewUserID.js, which has the code as below.
const Connection = require('./database/Connection')
const createNewUserID = async(connData, userId) => {
try{
var getConn = await Connection.get().getConn();
const query = `exec BaseDB.get_client_info`
var clientusers = await getConn.query(query);
var getConn1 = await Connection.get().getConnection(connData)
var res = await getConn1.execute('BaseDB.get_all_existing_users');
res.recordsets[1].map(async (val) => {
try{
var newid = val.id+'NEWID';
var getConn2 = await Connection.get().getConnection(connData)
getConn2.input('userid', userid)
getConn2.input('updatedid', newid)
var res2 = await getConn2.execute(`BaseDB.update_users_with_newid`)
} catch (err) {
console.log(err)
return { err, message: 'First DB Connection' }
}
})
} catch (err) {
console.log(err)
return { err, message: 'Second DB Connection' }
}
}
const connData = {
"clientuserid": "12345"
}
createNewUserID(connData)
Also I have a Connection.js where I have made DB connection configurations of Base Database and client DB.The client DB Database will be dynamic. So, for now I am passing the DB name through constant connData. I have defined connData in the same file above in CreateNewUserID.js.
My Connection.js is below:
const sql = require('mssql')
class Connection {
// CONNECTION CONFIGURATION OF CLIENT DB
getConnection = async (conData) => {
const connData = JSON.parse(conData)
try {
// sql.close();
const config = {
user: process.env.SQL_USER,
password: process.env.SQL_PASSWORD,
server: process.env.SQL_SERVER,
database: connData.clientuserid
}
const pool = await new sql.ConnectionPool(config)
const req=await pool.connect()
const conn = await req.request()
// const req = await sql.connect(config)
// const conn = await req.request()
return conn;
} catch (err) {
return err;
}
};
// CONNECTION CONFIGURATION OF BASE DB
getConn = async () => {
try {
// sql.close();
const config = {
user: process.env.SQL_USER,
password: process.env.SQL_PASSWORD,
server: process.env.SQL_SERVER,
database: process.env.SQL_DATABASE
}
const pool = await new sql.ConnectionPool(config)
const req=await pool.connect()
const conn = await req.request()
// const req = await sql.connect(config)
// const conn = await req.request()
return conn;
} catch (err) {
return err;
}
};
}
Connection.__instance = null;
Connection.get = () => {
if (!Connection.__instance) {
Connection.__instance = new Connection();
}
return Connection.__instance;
};
module.exports = Connection;
When I try to run the file through CMD with command node CreateNewUserID.js I am getting the error as unexpected token 0 in json at position 1 at first catch with message "First DB connection".
Why am I getting the error and how to resolve it. Please help. Thanks in advance

Transaction numbers are only allowed on storage engines that support document-level locking - MongodbMemoryServer/Mochai/Chai/Supertest

FIXED: USER storageEngine: "wiredTiger"
I use Mocha / Chai / Supertest and Mongodb-Memory-Server to test my app. But's I received error: Transaction numbers are only allowed on storage engines that support document-level locking
In real database and test by postman, it's working well.
My code:
In database.js
const mongoose = require('mongoose')
const { MongoMemoryReplSet } = require('mongodb-memory-server')
mongoose.set('useFindAndModify', false);
const connect = async () => {
try {
let url = process.env.MONGO_URL
let options = {
//Something
}
if (process.env.NODE_ENV === 'test') {
const replSet = new MongoMemoryReplSet();
await replSet.waitUntilRunning();
const uri = await replSet.getUri();
await mongoose.connect(uri, options)
//log connected
} else {
await mongoose.connect(url, options)
//log connected
}
} catch (error) {
//error
}
}
I have two model: Company and User. I made a function to add a member to company with used transaction. My code
const addMember = async (req, res, next) => {
const { companyId } = req.params
const { userId } = req.body
const session = await mongoose.startSession()
try {
await session.withTransaction(async () => {
const [company, user] = await Promise.all([
Company.findOneAndUpdate(
//Something
).session(session),
User.findByIdAndUpdate(
//Something
).session(session)
])
//Something if... else
return res.json({
message: `Add member successfully!`,
})
})
} catch (error) {
//error
}
}
Here's router:
router.post('/:companyId/add-member',
authentication.required,
company.addMember
)
Test file:
const expect = require('chai').expect
const request = require('supertest')
const app = require('../app')
describe('POST /company/:companyId/add-member', () => {
it('OK, add member', done => {
request(app).post(`/company/${companyIdEdited}/add-member`)
.set({ "x-access-token": signedUserTokenKey })
.send({userId: memberId})
.then(res => {
console.log(res.body)
expect(res.statusCode).to.equals(200)
done()
})
.catch((error) => done(error))
})
})
And i received error: Transaction numbers are only allowed on storage engines that support document-level locking'
How can I fix this?
Add retryWrites=false to your database uri. Example below:
mongodb://xx:xx#xyz.com:PORT,zz.com:33427/database-name?replicaSet=rs-xx&ssl=true&retryWrites=false

How to get the log messages in the order I need?

How do I prevent Service running ... msg from getting logged first? I would like the messages inside testDBConnection fn. to be logged first instead. When DB is not running I would like the Looks like DB is not running msg to be kept getting logged and once the DB kicks in the DB connection has been established and Service running ... msgs should follow. I tried multiple things, but I was not able to come up with proper code. Thanks for your help.
index.js
import app from './config/express';
import config from './config/config';
import logger from './config/winston';
import { initDbConnection } from './server/db';
app.listen(config.port, () => {
initDbConnection();
logger.info(`Service running and listening on port ${config.port}`);
});
db.js
import knex from 'knex';
import config from '../config/config';
import logger from '../config/winston';
const { db } = config;
let pool;
const testDBConnection = (client) => {
const intervalId = setInterval(async () => {
try {
await client.select(1);
logger.info('DB connection has been established');
clearInterval(intervalId);
} catch (error) {
logger.error('Looks like DB is not running');
}
}, 2000);
};
export const initDbConnection = (mock) => {
if (mock) {
pool = knex({});
} else {
pool = knex({
client: 'pg',
version: '7.4.2',
connection: db,
debug: true
});
testDBConnection(pool);
}
};
export const getDb = () => pool;
You could use async/await for that.
import app from './config/express';
import config from './config/config';
import logger from './config/winston';
import { initDbConnection } from './server/db';
app.listen(config.port, async () => {
await initDbConnection();
logger.info(`Service running and listening on port ${config.port}`);
});
db.js:
import knex from 'knex';
import config from '../config/config';
import logger from '../config/winston';
const { db } = config;
let pool, connected;
const testDBConnection = (client) => {
return new Promise(resolve => {
const intervalId = setInterval(async () => {
try {
await client.select(1);
if (connected) {
return;
}
connected = true;
logger.info('DB connection has been established');
clearInterval(intervalId);
resolve('success');
} catch (error) {
logger.error('Looks like DB is not running');
}
}, 2000);
});
};
export const initDbConnection = (mock) => {
if (mock) {
pool = knex({});
} else {
pool = knex({
client: 'pg',
version: '7.4.2',
connection: db,
debug: true
});
return testDBConnection(pool);
}
};
export const getDb = () => pool;
This way, the logger inside the app.listen cb won't be called until the initDbConnection is resolved. Another way would be to just use the promise then.

Categories

Resources