create and check unique name against existing - node.js

I wrote this to check a newly generated name against what already exists in the DB...
..it's working, but it feels poorly written. Any suggestions? just trying to learn, thanks.
function createNewName (){
const shortName = uniqueNamesGenerator({
dictionaries: [adjectives, colors, animals],
length: 3
});
return shortName;
};
async function checkNameExists(name){
//check name against DB
const nameExists = await User.findOne({'name':name},function(err,result){
});
if (nameExists){
return true;
} else {
return false;
};
};
async function checkNewName(name, exists=true){
while (exists==true) {
exists = await checkNameExists(name);
if (exists){
name = await createNewName();
};
}
};
let name = await createNewName();
await checkNewName(name,true);

Related

mongoose.Query.prototype.exec() patching not working with populate

This is the code I have written for implementing redis caching in queries:
mongoose.Query.prototype.exec = async function () {
if (!this.__useCache || !client.__connected) {
return exec.apply(this);
}
const key = JSON.stringify(
Object.assign({}, this.getQuery(), {
collection: this.mongooseCollection.name,
})
);
// see if key exists
const cachedValue = await client.HGET(this.__hashKey, key);
// if yes, return it
if (cachedValue) {
const doc = JSON.parse(cachedValue);
const result = Array.isArray(doc)
? doc.map((d) => new this.model(d))
: new this.model(doc);
console.log('result', result);
return result;
}
// if no, store it in redis and return
const result = await exec.apply(this);
if (typeof result === 'object') {
await client.HSET(this.__hashKey, key, JSON.stringify(result));
// cache will expire after 24 hrs by default
client.expire(this.__hashKey, this.__duration || 86400);
}
return result;
};
This works perfectly fine for all queries that doesn't 'populate'. But with populate it gets stuck at await exec.apply(this). Why does it happen and how do I fix it ?
I solved it by saving the reference to original exec() inside the Query object instead of just a local variable and calling that instead of the local variable. Like this :
mongoose.Query.prototype._exec = mongoose.Query.prototype.exec;
mongoose.Query.prototype.exec = async function () {
//redis functionality
.
.
.
return await mongoose.Query.prototype._exec.apply(this, arguments);
}

Dynamic function call from dynamic string using nodejs

I'm using express nodejs, in my project, one scenario occurred while doing work on a specific module. I have made different functions for different roles, so based on the logged-in user's role, dynamically calling the other function. I want a trick that code should be a minimum of lines. So please suggest me a good solution.
if (userRole.code === ROLE.REFERRINGPROVIDER) {
query = await referralUser(tabCode, userId, query);
} else if (userRole.code === ROLE.CONSULTINGPROVIDER) {
query = await consultingUser(tabCode, userId, query);
} else if (userRole.code === ROLE.PARENT) {
query = await parentUser(tabCode, userId, query);
} else if (userRole.code === ROLE.PHYSICIAN) {
query = await physicianUser(tabCode, userId, query);
}
As shown in the above example I have to write that code for different users, so I have to make it a simple one-line function.
You can use this solution :)
const userRole = { code: 'referral' };
async function referralUser(tabCode, userId, query){
console.log(tabCode, userId, query);
return "referralUser Called!";
}
async function consultingUser(tabCode, userId, query){
console.log(tabCode, userId, query);
return "consultingUser Called!";
}
async function parentUser(tabCode, userId, query){
console.log(tabCode, userId, query);
return "parentUser Called!"
}
let functionName = userRole.code + 'User';
eval(functionName)("tabCode", "userId", "query").then((results)=>{
console.log(results);
});
You can call functions by their string name. For instance:
function funcOne() {
console.log('funcOne');
}
function funcTwo() {
console.log('funcTwo');
}
function funcThree() {
console.log('funcThree');
}
function funcFour() {
console.log('funcFour');
}
function funcFive() {
console.log('funcFive');
}
const func: { [K: string]: Function } = {
funcOne,
funcTwo,
funcThree,
funcFour,
funcFive
};
// console log output: "funcOne"
func['funcOne']();
// console log output: "funcFour"
func['funcFour']();
// console log output: "funcTwo"
func['funcTwo']();
In your case, use ROLE to map its keys to functions:
const func: { [K: string]: Function } = {
[ROLE.REFERRINGPROVIDER]: referralUser,
[ROLE.CONSULTINGPROVIDER]: consultingUser,
[ROLE.PARENT]: parentUser,
[ROLE.PHYSICIAN]: physicianUser
};
query = await func[userRole.code](tabCode, userId, query);

async function doesn't wait of inside await in nodejs

I am implementing function monthlyRevenue.
Simply, it will return total monthly revenue,and it takes arguments of station array which will make revenues, month and year.
Problem
Inside of this function I have getStationPortion which will fetch the revenue portion of user's.
So I would like to make it return object like this.
stationsPortion = {station1 : 30, station2 : 20}
In the monthlyRevenue
const stationPortions = await getStationPortions(stations)
console.log("portion map", stationPortions //it will be shown very beginning with empty
getStationPortions
const getStationPortions = async (stations) => {
let stationPortions = {}
stations.map(async (value) => {
const doc = await fdb.collection('Stations').doc(value).get()
if (!doc.exists) {
console.log("NO DOC")
} else {
stationPortions[value] = doc.data().salesPortion
console.log(stationPortions) //it will be shown at the last.
}
})
return stationPortions
}
I thought that async function should wait for the result, but it does not.
I am kind of confusing if my understanding is wrong.
Thank you
(by the way, fdb is firebase admin(firestore)
Working code
const getStationPortions = async (stations) => {
let stationPortions = {}
await Promise.all(stations.map(async (value) => {
const doc = await fdb.collection('Stations').doc(value).get()
if (!doc.exists) {
console.log("NO DOC")
} else {
stationPortions[value] = doc.data().salesPortion
console.log(stationPortions)
}
}))
return stationPortions
}
module.exports = router;

sql.close() Is it still necessary if object = sql.connect and object destroyed at the end? (Node.js Express)

I have a function which returns an object that is essentially sql.connect(<constring>). I’m using that function to create a new object (new connection) every time that I need (for example const newPool = await startPool()
My questions is this:
I’m not using sql.close because I assumed that the newPool object is destroyed when the function in which is used is finished. Is this right?
I'm using this to define the connection:
let newPool = null;
async function startDatabase() {
try {
newPool =await sql.connect(sqlConfig);
} catch (err) {
console.log(err.message);
errorMsg ='database connection error';
}
}
async function startPool(){
if(!newPool) await startDatabase();
return newPool;
}
module.exports = {
startPool,
startDatabase,
}
.. and this is an example where I use it
const newPool = await startPool();
const result = await newPool.request()
.input('email',sql.NVarChar(100),email)
.query('select SID, active, blockedTemp,hps,slt, SERFid, fName, lName from usr where [email] = #email')

sequelize.js - Find by id and return result

I have a function,
var findUserDevice = function(userDeviceId){
var device = db.DeviceUser.find({
where: {
id: userDeviceId
}
}).then(function(device) {
if (!device) {
return 'not find';
}
return device.dataValues;
});
};
but this function does not return anything...
var UserDevice = findUserDevice(req.body.deviceUserId);
console.log(UserDevice);// undefined
The operation you are trying to do is async, which means that you need to use a callback. Since sequelize is build on top of Promises, you should actually write your code like this :
var findUserDevice = function(userDeviceId){
// return the promise itself
return db.DeviceUser.find({
where: {
id: userDeviceId
}
}).then(function(device) {
if (!device) {
return 'not find';
}
return device.dataValues;
});
};
And later use it like :
findUserDevice(req.body.deviceUserId).then( function(UserDevice) {
console.log(UserDevice);
});
It's 2020, async & await are becoming more popular. You can change your code to:
const findUserDevice = async function (userDeviceId) {
const device = await db.DeviceUser.findOne({
where: {
id: userDeviceId
}
});
if (device === null) {
return 'device not found';
}
return device.dataValues;
};
(async () => {
// ...
const UserDevice = await findUserDevice(req.body.deviceUserId);
console.log(UserDevice);
// ...
})()
IMHO, the code above is way more readable.
If you are getting undefined instead of 'not find' on the console, it means your function is returning a value. The problem might be dataValues is actually undefined. You need to check for the content of device.
Hint: Try returning just device or device.id
PS. If you want to do the search based on id, should go for findById() function of your model.
var device = db.DeviceUser.findById(userDeviceId).then(function(device) {
if (!device) {
return 'not find';
}
return device.dataValues;
});
This function received params id, this worker for me:
const { customer } = require('../models');
const get = async function(req, res){
let id = req.params.id;
[err, singleCustomer] = await to(customer.findByPk(id, { raw : true }));
return ReS(res, { message :'Obtener cliente: : ', data : JSON.stringify(singleCustomer) });
}

Resources