Compare data after sequelize asynchronous query - node.js

I have this code :
VerificationKey.getCode = async (visitorData, visitorCode, res) => {
console.log("Verif model visitorCode" + visitorCode);
const data = visitorData;
const testCode = visitorCode;
const findVisitor = await VerificationKey.findOne({ where: { data } })
.catch((err) => {
console.log(err);
})
.then(() => {
if (testCode == findVisitor.key) {
res.status(200).json({ response: true });
}
});
};
What I need is to compare testCode and findVisitor.key values.
If they are equal, I want to return a boolean to the front end.
But I can't write it like this because it is not possible to access findVisitor.key before initialization.

I believe you have to change your code to use async/await syntax only - without then and catch:
VerificationKey.getCode = async (visitorData, visitorCode, res) => {
console.log("Verif model visitorCode" + visitorCode);
const data = visitorData;
const testCode = visitorCode;
try {
const findVisitor = await VerificationKey.findOne({ where: { data } });
if(!findVisitor) {
res.status(404).json({ response: false });
} else if(testCode == findVisitor.key) {
res.status(200).json({ response: true });
} else {
res.status(403).json({ response: false });
}
} catch(err) {
console.log(err);
}
};

Related

Get qldb ledger table data in javascript object

So my issue is simple yet challenging. I am trying to transfer data from one ledger to another. Now for that, I am reading a whole table of data then creating an object for every document than inserting these documents one by one into the other ledger table
Ledger#1 Table1 -> get all data -> convert all data to array of objects -> transfer to Ledger#2 Table1 one by one
The problem is that I cannot create the object from the document. I do this manually by using prototype functions and reading field type and then creating a thing that is messy and causes some data to become null. So I was wondering if there was a better way that is less prone to errors.
I asked a question of migrating ledger but had no luck in getting any response. Please help me in this.
Following is my code. Please copy and paste it inside an IDE so you can better understand
const getValueOfField = (field) => {
const name = field.getType().name;
switch (name) {
case "string":
return field.stringValue();
case "int":
return field.numberValue();
case "null":
return null;
default:
return null;
}
};
const enterDataInNewLedger = async (tableData, tableName) => {
const awsProductionDriver = awsProduction();
console.log(`Starting to insert data inside table ${tableName}`);
try {
for (const data of tableData) {
await awsProductionDriver.executeLambda(async (txn) => {
await txn.execute(`INSERT INTO ${tableName} ?`, data);
});
}
console.log(`Done inserting data inside ${tableName}`);
return { success: true };
} catch (err) {
console.log(err.message);
return { success: false, message: err.message };
}
};
const dataTransferOfTable = async (table) => {
const prodDriver = awsProd();
try {
const allTableData = await prodDriver.executeLambda(async (txn) => {
const result = await txn.execute(`SELECT * FROM ${table.name}`);
const resultList = result.getResultList();
let completeResults = [];
for (const doc of resultList) {
let newDoc = {};
const fields = doc.fields();
for (const field of fields) {
newDoc[field[0]] = getValueOfField(field[1]);
}
completeResults.push(newDoc);
}
return completeResults;
});
const response = await enterDataInNewLedger(allTableData, table.name);
checkForErrors(response);
return { success: true };
} catch (err) {
console.log(err.message);
return { success: false, message: err.message };
}
};
const startDataTransferFromOneLedgerToAnother = async () => {
try {
for (let table of tableName) {
const response = await dataTransferOfTable(table);
checkForErrors(response);
}
} catch (err) {
console.log(err.message);
}
};
startDataTransferFromOneLedgerToAnother();
So apparently I could've done this easily. I was just checking it and figured out the solution.
I can insert the whole fetched document and it will be same so my converted code is as follows
const { awsMainFunction: awsProd } = require("./awsProdConfig");
const { awsMainFunction: awsProduction } = require("./awsProductionConfig");
const { tableNamesAndIndeces: tableName, checkForErrors } = require("./utils");
const enterDataInNewLedger = async (tableData, tableName) => {
const awsProductionDriver = awsProduction();
console.log(`Starting to insert data inside table ${tableName}`);
try {
for (const data of tableData) {
await awsProductionDriver.executeLambda(async (txn) => {
await txn.execute(`INSERT INTO ${tableName} ?`, data);
});
}
console.log(`Done inserting data inside ${tableName}`);
return { success: true };
} catch (err) {
console.log(err.message);
return { success: false, message: err.message };
}
};
const dataTransferOfTable = async (table) => {
const prodDriver = awsProd();
try {
const allTableData = await prodDriver.executeLambda(async (txn) => {
const result = await txn.execute(`SELECT * FROM ${table.name}`);
return result.getResultList();
});
const response = await enterDataInNewLedger(allTableData, table.name);
checkForErrors(response);
return { success: true };
} catch (err) {
console.log(err.message);
return { success: false, message: err.message };
}
};
const startDataTransferFromOneLedgerToAnother = async () => {
try {
for (let table of tableName) {
const response = await dataTransferOfTable(table);
checkForErrors(response);
}
} catch (err) {
console.log(err.message);
}
};
startDataTransferFromOneLedgerToAnother();

display questions based on user type MERN

I have two collections from one questions for admin comes and from other questions for user comes.
I am unable to show the questions in React using redux store.
store/action
import { QUESTIONS } from '../../constants/actionTypes';
import * as api from '../../services/api';
import * as paths from '../../constants/apiPaths';
const TOTAL_QUESTIONS = 60;
export const fetcQuestions = (router) => async (dispatch) => {
try {
const user = await api.get(paths.FETCH_USER);
const userType = user.type;
console.log(userType + "userType");
if((userType === "Student") || (userType === "STUDENT"))
{
const {questions, assessment, options} = await api.get(paths.FETCH_QUESTIONS);
console.log(api.get(paths.FETCH_QUESTIONS) + "Question path");
dispatch({ type: QUESTIONS, questions, assessment, options });
if(assessment.responded === TOTAL_QUESTIONS) {
router.push('/advice');
}
}
else
if((userType === "Admin") || (userType === "ADMIN"))
{
console.log(userType + "type of user");
const {questions, assessment, options} = await api.get(paths.FETCH_QUESTIONS);
console.log(api.get(paths.FETCH_QUESTIONS) + "Question path");
dispatch({ type: QUESTIONS, questions, assessment, options });
if(assessment.responded === TOTAL_QUESTIONS) {
console.log("thank you");
}
}
} catch (error) {
console.log(error);
}
};
export const postAssessment = (data, router) => async (dispatch) => {
try {
const {questions, assessment, options} = await api.post(paths.POST_ASSESSMENT, data);
console.log(paths.POST_ASSESSMENT + "assessment");
dispatch({ type: QUESTIONS, questions, assessment, options });
if(assessment.responded === TOTAL_QUESTIONS) {
console.log("Thank you");
}
} catch (error) {
console.log(error);
}
};
please help me looking out whats wrong I am doing here. Thank You.
Reducer:
import * as actionType from '../../constants/actionTypes';
const assessmentReducer = (state = { questions: null, assessment: null, options: null }, action) => {
switch (action.type) {
case actionType.QUESTIONS:
return { ...state, questions: action?.questions, assessment: action?.assessment, options: action?.options, loading: false, errors: null };
default:
return state;
}
};
export default assessmentReducer;
NodeJS controller:
const TOTAL_QUESTIONS = 120;
export const fetchQuestions = async (req, res) => {
try {
const user = await db.findOne('USER', { _id: req.userId});
console.log(user + "user data");
let answerdQuestions = [];
let nextQuestions;
let assessment;
if (user.assessment) {
assessment = await db.findOne('ASSESSMENT', { user: req.userId });
answerdQuestions = assessment.responses.map(response => response.number)
}
nextQuestions = getNextQuestions(answerdQuestions);
if ((user.type === "STUDENT") || (user.type === "student")) {
console.log(user.type + "type");
const questions = await db.find('QUESTIONG', { number: { $in: nextQuestions } });
console.log(questions.number + "quesstudent");
res.status(200).json({ questions, assessment: { id: assessment?._id, responded: answerdQuestions.length }, options: options });
return answerdQuestions;
}
else {
console.log(user.type + "typegh");
const questions = await db.find('QUESTION', {number: { $in: nextQuestions }});
console.log(questions.question + "quesdata");
res.status(200).json({ questions, assessment: { id: assessment?._id, responded: answerdQuestions.length }, options: options });
return answerdQuestions;
}
} catch (err) {
console.log(err)
res.status(500).json({ message: "Something went wrong" });
}
};
export const postResponses = async (req, res) => {
try {
let responses = req.body.responses;
let assessmentId = req.body.id;
responses = responses.map(response => {
return {
score: Number(response.value),
number: response.number,
category: response.category,
question: response._id
}
});
const user = await db.findOne('USER', {_id: req.userId});
console.log( user.type + "typeofuser");
let assessment = await db.findOne('ASSESSMENT', { _id: assessmentId });
if (assessment?.responses.length === TOTAL_QUESTIONS) {
res.status(200).json("completed");
}
if (!assessment) {
//
let response = {
user: req.userId,
responses: responses,
responded: responses.length
}
assessment = await db.create('ASSESSMENT', response);
await db.findOneAndUpdate('USER', { _id: req.userId }, { assessment: assessment._id });
} else {
assessment = await db.findOneAndUpdate('ASSESSMENT', { _id: assessment._id }, { $push: { responses: { $each: responses } } });
}
let answerdQuestions = assessment.responses.map(response => response.number);
const nextQuestions = getNextQuestions(answerdQuestions);
if (answerdQuestions.length === TOTAL_QUESTIONS) {
console.log("You win");
]
}
if((user.type === "STUDENT") || (user.type==="student") ){
console.log("type" + user.type);
const questions = await db.find('QUESTIONG', { number: { $in: nextQuestions } });
res.status(200).json({ questions, assessment: { id: assessment?._id, responded: answerdQuestions.length }, options: options });
} else
{
console.log(user.type + "typeg");
const questions = await db.find('QUESTION', { number: { $in: nextQuestions } });
res.status(200).json({ questions, assessment: { id: assessment?._id, responded: answerdQuestions.length }, options: options });
}
}catch (err) {
console.log(err)
res.status(500).json({ message: "Something went wrong" });
}
};
//export default fetchQuestions;
I have added reducer and NodeJS controller also, Based on user type the questions are to be shown. Please help. If type is student then the questions are not getting displayed else condition the questions are getting displayed
What I can see is, you have mentioned wrong database when you are trying to fetch data for usertype student. Here is your code:
if (user.type === 'STUDENT' || user.type === 'student') {
console.log(user.type + 'type');
const questions = await db.find('QUESTIONG', { number: { $in: nextQuestions } });
You need to correct the database name, and everything will work fine:
const questions = await db.find('QUESTION', { number: { $in: nextQuestions } });
Hope this works!!!

Asynchronicity issue: why does the second part of my function run before a loop event finishes?

I have a route on an Express server that updates a User profile. The User profile is updated before I have finished to parse the data to update. How so?
I want to update two const: newProfilePicture & newOtherPictures. They are correctly updated, but after the user has been updated, so it's useless. How to fix this asynchronicity issue?
Here is the function:
router.post("/upload-images", upload.array("image"), async (req, res) => {
const { userId } = req.body;
try {
if (req.files) {
let newProfilePicture = null;
let newOtherPictures = [];
req.files.forEach(({ path, originalname }) => {
cloudinary.uploader.upload(
path,
{
resource_type: "image",
public_id: `myapp/users/${userId}/${originalname}`,
crop: "scale",
quality: "auto",
},
(err, res) => {
if (err) {
return fs.unlinkSync("./" + path);
}
fs.unlinkSync("./" + path);
if (originalname === "main") {
return (newProfilePicture = res.secure_url);
}
return newOtherPictures.push({
id: originalname,
url: res.secure_url,
});
}
);
});
// THIS PART IS COMPLETE BEFORE THE req.files.forEach IS DONE
const user = await User.findById(userId);
const { otherPictures, profilePicture } = updatePictures(
newProfilePicture,
newOtherPictures,
user
);
User.findByIdAndUpdate(
userId,
{ profilePicture, otherPictures },
{ new: true }
);
res.send("upload images success");
}
} catch (err) {
console.log("err", err);
return res.status(500).send("upload images failed");
}
});
It happens because cloudinary.uploader.upload() runs asynchronously. Since you mentioned it doesn't have promise interface, you can convert the callback to promise using NodeJS's util.promise function as it's error first callback.
const { promisify } = require("util");
const fs = require("fs");
const cloudinaryUpload = promisify(cloudinary.uploader.upload.bind(cloudinary.uploader))
router.post("/upload-images", upload.array("image"), async (req, res) => {
try {
if (!req.files) {
return res.send("no images in the request body");
}
let newProfilePicture = null;
let newOtherPictures = [];
for (const { path, originalName } of req.files) {
try {
const response = await cloudinaryUpload(path, {
resource_type: "image",
public_id: `myapp/users/${userId}/${originalName}`,
crop: "scale",
quality: "auto",
});
await fs.promises.unlink("./" + path);
if (originalname === "main") {
newProfilePicture = response.secure_url;
continue;
}
newOtherPictures.push({
id: originalName,
url: response.secure_url,
});
} catch (error) {
//do what you want if there is an error
//throw error if you want
await fs.promises.unlink("./" + path);
}
}
const user = await User.findById(userId);
const { otherPictures, profilePicture } = updatePictures(
newProfilePicture,
newOtherPictures,
user
);
//use User.updateOne() as you don't need the doc back
await User.findByIdAndUpdate(
userId,
{ profilePicture, otherPictures },
{ new: true }
);
return res.send("upload images success");
} catch (error) {
console.log("err", err);
return res.status(500).send("upload images failed");
}
});

Trouble with promise in firebase functions

This code either runs once or a max of 100 times. I have a dummy data file with 6000 records as this is the average that it will have to handle.
Currently using the Blaze plan.
The code was working somewhat, I set up a new project and now I get this issue.
export const uploadPatrons = functions.storage
.object()
.onFinalize((object, context) => {
let patronPromise: any[];
patronPromise = [];
if (object.name === 'patrons/upload.csv') {
admin
.storage()
.bucket()
.file('/patrons/upload.csv')
.download({})
.then(data => {
Papa.parse(data.toString(), {
header: true,
skipEmptyLines: true,
complete: result => {
result.data.forEach(x => {
x.inside = false;
x.arrived = false;
x.img = false;
x.arrivedTime = null;
const newPromise = admin
.firestore()
.collection('patrons')
.add({ ...x })
.then(doc => {
console.log(doc);
})
.catch(err => {
console.log(err);
});
patronPromise.push(newPromise);
});
}
});
})
.catch(err => {
console.log(err);
});
}
return Promise.all(patronPromise)
.catch(err => {
console.log(err);
});
});
All it has to do is read the file from the storage, parse it and add each record to the firebase collection
Function returned undefined, expected Promise or value
This is the error I get in the logs
Because of your first promise may be shutdown even it not finish. So try to follow the rule promise/always-return
export const uploadPatrons = functions.storage
.object()
.onFinalize((object, context) => {
if (object.name === 'patrons/upload.csv') {
return admin.storage().bucket()
.file('/patrons/upload.csv')
.download({})
.then(data => {
let patronPromise: any[];
patronPromise = [];
Papa.parse(data.toString(), {
header: true,
skipEmptyLines: true,
complete: result => {
result.data.forEach(x => {
x.inside = false;
x.arrived = false;
x.img = false;
x.arrivedTime = null;
const newPromise = admin.firestore()
.collection('patrons')
.add({
...x
})
patronPromise.push(newPromise);
});
}
});
return Promise.all(patronPromise)
})
.then(result=>{
//return Promise.resolve or something
})
.catch(err=>{
console.log(err)
})
}
else{
//also return if it's nothing
}
});
You're ignoring the promise that admin.storage().bucket().file('/patrons/upload.csv').download({}) returns, which means that the function may get aborted.
I think it should be closer to this:
export const uploadPatrons = functions.storage
.object()
.onFinalize((object, context) => {
let patronPromise: any[];
patronPromise = [];
if (object.name === 'patrons/upload.csv') {
return admin.storage().bucket()
.file('/patrons/upload.csv')
.download({})
.then(data => {
Papa.parse(data.toString(), {
header: true,
skipEmptyLines: true,
complete: result => {
result.data.forEach(x => {
x.inside = false;
x.arrived = false;
x.img = false;
x.arrivedTime = null;
const newPromise = admin.firestore()
.collection('patrons')
.add({
...x
})
patronPromise.push(newPromise);
});
// TODO: return the Promise.all(patronPromise) here
}
});
})
}
});

Code executes before i get the response from the database

I am new to Express and writing the code to get the list from my database. I'm trying to update the quantity of the items in my list. Now there can be multiple items and quantity for those items needs to be updated accordingly. The problem I am facing is when I try to get the list and update item accordingly, before my for loop executes to update the item it doesn't update the item's quantity in the database and saves the order. What am I doing wrong?
I have used async functions, promises and flags to update the items quantity in the database but none helps.
This is my code for to get and update the item's quantity
const Express = require("express");
const app = Express.Router();
const Menu = require("../../models/Menu");
const Order = require("../../models/order");
const User = require("../../models/user");
app.post(
"/create",
async function(req, res) {
var myorder = {};
var orderList = [];
var ordDetail = [];
var UpdateMenus = [];
orderList = JSON.parse(JSON.stringify(req.body["OD"]));
if(orderList.length>0){
const user = await User.findOne({ _id: req.user.id })
.then(user => {
if (!user) {
return res.status(400).json({ error: "User Not Found" });
}
})
.then(() => {
var order = Order({
user: req.user.id
});
myorder = order;
(async function loop() {
for (i = 0; i < orderList.length; i++) {
const ordt = new Object({
menu: orderList[i]["menuId"],
order: myorder.id,
prize: orderList[i]["prize"],
quantity: orderList[i]["quantity"]
});
await Menu.findOne({ _id: orderList[i]["menuId"] })
.exec()
.then(menu => {
if (menu) {
if (menu.quantity >= ordt.quantity) {
menu.quantity = menu.quantity - ordt.quantity;
const editmenu = menu;
(async function updateTheMenu() {
await Menu.findOneAndUpdate(
{ _id: menu.id },
{ $set: editmenu },
{
new: true,
useFindAndModify: false
}
).then(updateMenu => {
console.log(updateMenu);
ordDetail.push(ordt);
});
})();
} else {
return res.status(400).json({
error:
menu.MenuText +
"" +
ordt.quantity +
" Qunatity Is Not Available"
});
}
}
});
}
})();
}).then(()=>{
order
.save()
.then(order => {
if (!order) {
return res.json({ error: "Order is not saved" });
}
res.status(200).json(order);
})
.catch(error => {
return res
.status(400)
.json({ error: "Fields are Not Correct" });
});
});
}
}
);
There are few things wrong with your code:
If you use await then you don't need to use then. You can just assign to a variable. Example:
const menu = await Menu.findOne({ _id: orderList[i]["menuId"] })
You don't need to wrap your loop and every await call in async functions. They are already in an async function.
You can write your response handler like this:
app.post('/create', async function(req, res) {
var myorder = {};
var orderList = [];
var ordDetail = [];
var UpdateMenus = [];
orderList = JSON.parse(JSON.stringify(req.body['OD']));
if (orderList.length > 0) {
const user = await User.findOne({ _id: req.user.id });
if (!user) {
return res.status(400).json({ error: 'User Not Found' });
}
var order = Order({
user: req.user.id
});
myorder = order;
for (i = 0; i < orderList.length; i++) {
const ordt = new Object({
menu: orderList[i]['menuId'],
order: myorder.id,
prize: orderList[i]['prize'],
quantity: orderList[i]['quantity']
});
const menu = await Menu.findOne({ _id: orderList[i]['menuId'] });
if (menu) {
if (menu.quantity >= ordt.quantity) {
menu.quantity = menu.quantity - ordt.quantity;
const editmenu = menu;
const updateMenu = await Menu.findOneAndUpdate(
{ _id: menu.id },
{ $set: editmenu },
{
new: true,
useFindAndModify: false
}
);
console.log(updateMenu);
ordDetail.push(ordt);
} else {
return res
.status(400)
.json({
error:
menu.MenuText +
'' +
ordt.quantity +
' Qunatity Is Not Available'
});
}
}
}
try {
const savedOrder = await order.save();
if (!savedOrder) {
return res.json({ error: 'Order is not saved' });
}
res.status(200).json(savedOrder);
} catch (error) {
return res.status(400).json({ error: 'Fields are Not Correct' });
}
}
});

Resources