Promise or Callback, which one is better to use with NodeJS? - mysql

I found that there are 2 different ways to write node functions using promise or callback, the first way is like following defining the findByEmail function:
class Users{
static async findByEmail(email: any ) : Promise<Users | undefined>{
const user: any = await Pools.execute(
"SELECT * FROM users WHERE email = ?",
[email])
.then(rows => {
return rows[0];
})
.catch(err => console.log(err) );
return user;
};
}
router.post(
"/api/users/signin",
async (req: Request, res: Response , next: NextFunction) => {
const { email, password } = req.body;
const existingUser = await Users.findByEmail(email);
});
And the second way would be like:
declare global {
namespace Express {
interface Response {
user?: Users;
}
}
}
static async findByEmail(req: Request, res: Response) {
const user = await Pools.execute(
"SELECT * FROM users WHERE email = ?",
[req.body.email])
.then(rows => {
res.user = rows[0];
})
.catch(err => console.log(err) );
};
router.post(
"/api/users/signin",
async (req: Request, res: Response , next: NextFunction) => {
await Users.findByEmail(req, res);
const existingUser = res.user;
});
I am not sure if this is a "opinion based" question or not? However my purpose of asking this is to know which way is a better practice and why? According to performance and other possible issues?
In particular I like to know either it is better to write functions with the return value or using response object to add the returning value to that inside the then() function, like .then(res.user = user) instead of const user = await pool.execute(SELECT ...) ?

Here's a way to impalement that makes the following improvements:
Makes findByEmail() into a utility function that is independent of the req and res objects and thus can be used generally.
Properly propagates all errors from findByEmail() back to the caller.
Implements some validation checks on incoming email field and makes separate error path for that.
Log all errors on the server
Check for all error conditions from the database request
Not mixing .then() and await.
Here's the code:
// resolves to null if email not found
// rejects if there's a database error
static async findByEmail(email) {
const rows = await Pools.execute("SELECT * FROM users WHERE email = ?", [email]);
if (!rows || !rows.length || !rows[0]) {
return null;
}
return rows[0];
};
router.post("/api/users/signin", async (req: Request, res: Response, next: NextFunction) => {
try {
// validate incoming parameters
if (!req.body.email) {
let errMsg = "No email value present in incoming signin request";
console.log(errMsg);
res.status(400).send(errMsg);
return;
}
let user = await Users.findByEmail(req.body.email);
if (!user) {
// do whatever you would do if user tries to signin with non-existent email
// presumably return something like a 404 status
} else {
// do whatever you wanted to do here with the user object after login
}
} catch(e) {
// some sort of server error here, probably a database error, not the client's fault
console.log(e);
res.sendStatus(500);
}
});

Related

How to pass updated set State value in axios request as params

I'm a beginner in react native, I'm trying to get user information from mysql database through an axios API get request.
Once logged in, I stored email address in AsyncStorage and later want to use that email address from AsyncStorage as params or parameters to get the user details.
I wrote a code which set initial state of the setState as 'na'. Please help me how I can pass the email address from AsyncStorage as params or parameters.
Here is my code.
// to load email address
const [SessionEmail, setSessionEmail] = useState('na');
// to load users info
const [users, setUsers] = useState([]);
useFocusEffect(
React.useCallback(() => {
getUsername();
getUsersInfoFromAPI();
}, [])
);
// to get the session username from localstorage
const getUsername = async () => {
try {
const username = await AsyncStorage.getItem('Username')
if (username !== null) {
setSessionEmail(username);
}
} catch (e) {
console.log(e);
}
}
// API Calling user details
const getUsersInfoFromAPI = async () => {
await axios.get(`https://myapi.co.in/api/user/?email=${SessionEmail}`)
.then(response => {
setUser(response.data);
})
.catch(error => {
console.log(error);
});
}
After the page is rendered, and I load page from metro, I can see the parameters have been sent to server.
Update your code in this way:
useFocusEffect(
React.useCallback(() => {
getUsername();
}, [])
);
Instead of saving your email to state, sent it to function directly but if you are using it for other reason you can still save it but call function while getting username from AsyncStorage with username parameter like below.
// to get the session username from localstorage
const getUsername = async () => {
try {
const username = await AsyncStorage.getItem('Username')
if (username !== null) {
getUsersInfoFromAPI(username);
}
} catch (e) {
console.log(e);
}
}
// API Calling user details
const getUsersInfoFromAPI = async (email) => {
await axios.get(`https://myapi.co.in/api/user/?email=${email}`)
.then(response => {
setUser(response.data);
})
.catch(error => {
console.log(error);
});
}
const [users, setUsers] = useState([]);
here you can use like this
const [users, setUsers] = useState();
hope this will help you

Where should data-validation happen using Express (and MySQL)?

I'm currently learning MySQL by creating an REST API using Express. I've opted for validating data on the server instead of the database. My question is, WHERE on the server should I do that?
Should I validate data (for example minimum and maximum length for the username)...
...using a middleware before the controller file?
...in the controller file, after reciving the request and before sending the data to the models file? (example file below)
...the models file before querying? (example file below)
...some completely other solution I haven't thought of?
./controllers/authController.js
const register = async (req, res) => {
const { username, email, password } = req.body;
**// Validating input data here?**
// TODO hash password
const activationToken = generateActivationToken(48);
const newUser = await User.create(
{ username, email, password, activationToken },
(err, result) => {
console.log(err);
if (err)
return res.status(400).json({
msg: err.message || "Some error has occured. Please try again.",
});
else res.json({ result });
}
);
};
./models/User.js
var db = require("../dbconnection");
// constructor for User object
const User = function (user) {
this.username = user.username;
this.email = user.email;
this.password = user.password;
this.activationToken = user.activationToken;
};
User.create = (newUser, result) => {
**// Validating input data here?**
db.query("INSERT INTO users SET ?", newUser, (err, res) => {
if (err) return result(err, null);
console.log("Created user.");
result(null, { id: res.insertId });
});
};
module.exports = User;
What's the usual/best practice way of doing this? If there isn't a best practice, how do YOU do it? (I validate data on the front-end too of course.) Do you know of any good example projects I could take a look at?
Thank you for your time!
In OOP there's a principle called as:
"The information Expert principle"
According to this principle we should assign responsibilities / methods inside the objects that contain the most information to fulfil the task
(It helps us create cohesive classes).
So, you should probably put the validation logic inside the User model.

how to read properly a json string in react native

I sent to asyncStorage all the info as stringify,
i tried to parse it.
this is what i get from console log:
"{\"metadata\":{\"lastSignInTime\":1610728860334,\"creationTime\":1610728860334},\"phoneNumber\":null,\"displayName\":null,\"isAnonymous\":false,\"providerData\":[{\"email\":\"ad#ad.com\",\"phoneNumber\":null,\"uid\":\"ad#ad.com\",\"photoURL\":null,\"displayName\":null,\"providerId\":\"password\"}],\"email\":\"ad#ad.com\",\"emailVerified\":false,\"providerId\":\"firebase\",\"photoURL\":null,\"uid\":\"3lkoKoMxQSMKeSxFOyysESt3oKh1\"}"
and i need to get email and uid seperate.
how do I get in that object? i tried user.email or user.providerData.email non of them work.
any suggestion?
edited:
here is the object I get from firebase
let res = await auth().createUserWithEmailAndPassword(Email, Password)
if (res) {
console.log( "?", res)
this.setState({ userData: JSON.stringify( res.user) });
this.storeToken(JSON.stringify(res.user));
then I store the token in async:
async storeToken(user) {
console.log('set user register: ', user)
try {
await AsyncStorage.setItem("userData", JSON.stringify(user));
} catch (error) {
console.log("Something went wrong", error);
}
}
and I get the object from above.
const readData = async () => {
console.log('data === ')
try {
const data = await AsyncStorage.getItem('userData')
let _data = JSON.parse(data);
console.log('data === ', data)
If you share code block it'll be easy for us.
Here is general answer.
Console log shows its still in string format. I use this separate file to read and write json to AsyncStorage. You can either use this OR match to see your mistake.
import AsyncStorage from '#react-native-community/async-storage';
const Api = {
storeData: async function (name, value) {
try {
await AsyncStorage.setItem(name, value);
return true;
} catch (error) {
return false;
}
},
readData: async function (name) {
let value = null;
try {
value = await AsyncStorage.getItem(name)
return JSON.parse(value);
} catch (e) {
return [];
}
},
}
export default Api;
after few console log I was able to get it by double parsing the object.
let _data = JSON.parse(JSON.parse(data));
console.log('data === ', _data.email)
and seem to work.

how to make a post request inside async function?

At the end of the waterfall-dialog in "summary" (i.e., the last if statement) i want to automatically make a post request without making an API call in Postman, is eventListener the way? How to include it?
async summaryStep(step) {
if (step.result) {
// Get the current profile object from user state.
const userProfile = await this.userProfile.get(step.context, new UserProfile());
userProfile.name = step.values.name;
//the same for other step values(email, doctor, date)
let msg = `you want a date with dr. ${userProfile.doctor} , and your name is ${userProfile.name}.`;
if (userProfile.date !== -1) {
msg += `you have an appointment the: ${userProfile.date}.`;
}
await step.context.sendActivity(msg);
let msg1 = `"${userProfile.date}"`;
if (msg1) {
let z = JSON.stringify(userProfile.name);
//and also the other rows to go in the database(email, doctor, date)
var name = JSON.parse(z);
//and also the other rows to go in the database(email, doctor, date)
//this actually works but only if i use postman
var urlencoded = bodyparser.urlencoded({ extended: false });
app.post('/id', urlencoded, (req, res) => {
app.use(express.json());
app.use(express.urlencoded({ extended: true }));
mysqlConnection.query("INSERT INTO users(name, email, doctor, date) VALUES('" + userProfile.name + "','" + userProfile.password + "','" + userProfile.doctor + "','" + userProfile.date + "')", function (err, result, rows) {
if (err) throw err;
console.log("Yeah! record inserted");
console.log(name);
res.send(result);
});
});
const port = process.env.PORT || 8080;
app.listen(port, () => console.log(`Listening on port ${port}..`));
}
} else {
await step.context.sendActivity('Thanks. Your profile will not be kept. Push enter to return Menu');
}
return await step.prompt(CONFIRM_PROMPT3, `is that true? ${step.result}`, ['yes', 'no']);
// this if statement should "fire" the post request...
if (step.result == 'yes') {
return await step.context.sendActivity(`we will contact you soon ${userProfile.password}.`);
}
return await step.endDialog();
}
Per my understanding , you want to know how to call an POST API from Azure bot async function. Pls try the code below in your async summaryStep function to send the post request based on your requirement.
var rp = require('request-promise');
var options = {
method: 'POST',
uri: 'http://localhost:8080/id',
body: {
fieldCount:0,
affectedRows:1,
//your other body content here...
},
json: true,
headers: {
'content-type': 'application/json' //you can append other headers here
}
};
await rp(options)
.then(function (body) {
console.log(body)
})
.catch(function (err) {
console.log(err)
});
}
Hope it helps .
A
nd if there is any further concerns or misunderstand , pls feel free to let me know.
The answer is to move your app.post API endpoint to your index.js file where your bot is already running on a server. Simply spin up a new "server" and "port" making the endpoint available. Then, in your summaryStep (axiosStep in my example), make your API call using Axios, request-promise, or what have you, to post your data. When the API is hit, the data will be passed in and processed.
In the code below, when the API is hit the passed in data is used in a sendActivity posted back to the bot. In your case, your passed in data would be used for the database call in which you could use the returned response in the sendActivity.
Your code would look something like the following. Please note, the post actions are simplified for the sake of the example. You would need to update the post actions to make your mySql queries. This sample also makes use of restify for the server (standard for Bot Framework bots) and uses the same port as the bot, but this can easily be updated to use Express and/or another port.
Hope of help!
index.js
[...]
const conversationReferences = {};
const bodyParser = require('body-parser');
server.post('/id', async (req, res) => {
const { conversationID, data, name } = req.body;
const conversationReference = conversationReferences[ conversationID ];
await adapter.continueConversation(conversationReference, async turnContext => {
var reply = `${ data }. Thanks, ${ name }`;
await turnContext.sendActivity(reply);
});
res.writeHead(200);
res.end();
});
mainDialog.js
async axiosStep ( stepContext ) {
const conversationID = stepContext.context.activity.conversation.id;
try {
const response = await axios.post(`http://localhost:3978/id`, {
data: "Yeah! Record inserted",
name: "Steve",
conversationID: conversationID
})
console.log(response);
} catch (error) {
console.log(error);
}
return stepContext.next();
}

Node.js - Use asynchronous function to get a return value in a synchronous way without callbacks

I have a function to retrieve a list of UserID's from a mysql database.
function GetUsers(callback) {
UpdateLogFile('Function Call: GetUsers()')
var users = []
Database.execute( connectionStr,
database => database.query('select UserID from Users')
.then( rows => {
for (let i = 0; i < rows.length; i++){
users.push(rows[i].UserID)
}
return callback(users)
})
).catch( err => {
console.log(err)
})
}
For Reference:
Database class which came from here
const mysql = require( 'mysql' )
class Database {
constructor( config ) {
this.connection = mysql.createConnection( config )
}
query( sql, args ) {
return new Promise( ( resolve, reject ) => {
this.connection.query( sql, args, ( err, rows ) => {
if ( err )
return reject( err )
resolve( rows )
})
})
}
close() {
return new Promise( ( resolve, reject ) => {
this.connection.end( err => {
if ( err )
return reject( err )
resolve()
})
})
}
}
Database.execute = function( config, callback ) {
const database = new Database( config )
return callback( database ).then(
result => database.close().then( () => result ),
err => database.close().then( () => { throw err } )
)
}
After hours of learning about promises and callbacks, I was finally able to get GetUsers() to at least work and return what I'm looking for. However, I seem to only be able to use it as such:
GetUsers(function(result){
// Do something with result
})
But I would really like to be able to have a traditional return statement in the function so that I could use it like this: var users = GetUsers(). I have seen posts saying that this is impossible due to the nature of asynchronous functions but I am still hopeful since I would really like to be able to avoid callback hell. I tried the code below but "users" just results as undefined after execution. So, my main goal is to be able to get the return value from GetUsers() without chaining callbacks together since I have other functions that behave similarly. Is this possible?
var users
GetUsers(function(result){
users = result
})
console.log(users)
This is a very confusing topic, and it took me a while to really understand why what you are asking simply is not possible (at least, in the exact way you are asking). For the examples I will using python Django and Node.js to compare.
Sync
def synchronous():
print('foo') //this will always print first
print('bar')
def getUsers():
with connection.cursor() as cursor:
cursor.execute('SELECT * FROM USERS') //this query is executed
users = cursor.fetchall()
print('foo') //this doesn't trigger until your server gets a response from the db, and users is defined
print(users)
Async
function asynchronous() {
console.log('foo'); //this will also always print first
console.log('bar');
}
function getUsers() {
var connection = mysql.createConnection(config);
connection.query('SELECT * FROM USERS', function(error, users) { //this is a "callback"
console.log(users); //this will print
//everything inside of here will be postponed until your server gets a response from the db
});
console.log('foo') //this will print before the console.log above
console.log(users); //this will print undefined
//this is executed before the query results are in and will be undefined since the "users" object doesn't exist yet.
}
A callback is simply the function that your server is supposed to run once you get a response. We typically use the actual word "callback" like this:
function getUsers(callback) {
var connection = mysql.createConnection(config);
connection.query('SELECT * FROM USERS', function(error, users) {
if (error) throw error; //always do your error handling on the same page as your query. Its much cleaner that way
callback(users) //server asks what to do with the "users" object you requested
});
}
Now on somewhere else on your server:
getUsers(function(users) {// the callback gets called here
console.log(users); //do what you want with users here
});
The getUsers function takes some other function (ie a callback) as its argument and executes that function after you perform your query. If you want to do the same thing without using the word "callback", you can use an await/async function like fsociety, or you explicitly write out your code and not make functions that take other functions as their arguments.
This is functionality identical to the code from above:
var connection = mysql.createConnection(config);
connection.query('SELECT * FROM USERS', function(error, users) {
if (error) throw error;
console.log(users);
});
Callback hell is inevitable, but it really Isn't too bad once you get the hang of it.
Use an async-await function instead.
async function GetUsers(callback) {
try {
UpdateLogFile('Function Call: GetUsers()')
var users = []
let rows = await Database.execute( connectionStr,
database => database.query('select UserID from Users')
for (let i = 0; i < rows.length; i++){
users.push(rows[i].UserID)
}
return callback(users)
} catch(err) {
console.log(err)
}
}
Hope this helps!