NodeJs Restful Api Using MySQl - mysql

I have tried it through MongoDB, but I can't to use JOIN Query in mongoDB and my project is wide enough. So, Want to Create Restful API in node js in MySQL.
Can anyone suggest the solution

For creating REST API you can go with express JS
var express = require('express');
var app = express();
app.get('/', function (req, res) {
//BELOW-CODE
});
You can connect Mysql by following this code:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM customers", function (err, result, fields) {
if (err) throw err;
console.log(result);
);
});
Note: Install expressJS framework to get started
Happy coding :-)

For MySQL with NodeJS you can use Sequelize, it's an ORM kinda like doctrine in symfony
http://docs.sequelizejs.com/

`'user strict';
var sql = require('./db.js');
//Task object constructor
var Task = function(task){
this.task = task.task;
this.status = task.status;
this.created_at = new Date();
};
Task.createTask = function createUser(newTask, result) {
sql.query("INSERT INTO tasks set ?", newTask, function (err, res) {
if(err) {
console.log("error: ", err);
result(err, null);
}
else{
console.log(res.insertId);
result(null, res.insertId);
}
});
};
Task.getTaskById = function createUser(taskId, result) {
sql.query("Select task from tasks where id = ? ", taskId, function (err, res) {
if(err) {
console.log("error: ", err);
result(err, null);
}
else{
result(null, res);
}
});
};
Task.getAllTask = function getAllTask(result) {
sql.query("Select * from tasks", function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else{
console.log('tasks : ', res);
result(null, res);
}
});
};
Task.updateById = function(id, task, result){
sql.query("UPDATE tasks SET task = ? WHERE id = ?", [task.task, id], function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else{
result(null, res);
}
});
};
Task.remove = function(id, result){
sql.query("DELETE FROM tasks WHERE id = ?", [id], function (err, res) {
if(err) {
console.log("error: ", err);
result(null, err);
}
else{
result(null, res);
}
});
};
module.exports= Task;

Related

Node JS Express MySQL , can not get all users

I can't get all users, but if write manually it works.
class User {
static getAll(result) {
let sql = `SELECT * FROM users`;
sql.query(sql, (err, res) => {
if (err) {
console.log("error: ", err);
result(null, err);
return;
}
console.log("users: ", res);
result(null, res);
});
}
}
exports.findAll = (req, res) => {
User.getAll = (err, data) => {
if (err) return res.status(500).send({ message: err.message || "Some error occurred while retrieving users." });
res.send(data);
}
}
query() is a method of a mysql connection, you are using it as a string method:
let sql = 'SELECT * FROM users';
sql.query()
You should first create the connection with your database, and then use that connection object to make your queries, something like this:
var mysql = require('mysql');
var con = mysql.createConnection({
host: "localhost",
user: "yourusername",
password: "yourpassword",
database: "mydb"
});
con.connect(function(err) {
if (err) throw err;
con.query("SELECT * FROM users", function (err, result, fields) {
if (err) throw err;
console.log(result);
});
});

unable to return response after login in node js api

TypeError: res.send is not a function.
I am getting this error when I try to return response after user login successfully.
can anybody help me out from this error.
here is my code:-
exports.login = function(req, res, next) {
let q = "SELECT * from users WHERE email = ?";
let query = sql.query(q,req.body.email, (error, res) => {
if (res.length > 0) {
bcrypt.compare(req.body.password, res[0].password, function(err, result){
if(err) {
console.log('password dost not match');
console.log("error: ", err);
result(null, err);
}
if(result) {
console.log('pasword match');
const jwtToken = jwt.sign({
email: res[0].email,
id: res[0].id
},
'secret',
{
expiresIn: '2h'
});
//tk = jwtToken;
return res.status(200).json({
error:0,
message:'user login successfully',
token:jwtToken
});
}
});
} else {
console.log('error commit');
console.log("error: ", error);
result(null, error);
}
});
};
just change the res from the call back of sq.query to dataResult, because once you send the res.send... then for sure in your case res was the dataResult of the sql.
exports.login = function(req, res, next) {
let q = "SELECT * from users WHERE email = ?";
let query = sql.query(q,req.body.email, (error, dataResult) => {
if(error){
console.log('error commit');
console.log("error: ", error);
res.status(400).send({error});
}
if (dataResult && dataResult.length > 0) {
bcrypt.compare(req.body.password, dataResult[0].password,
function(err, result){
if(err) {
console.log('password dost not match');
console.log("error: ", err);
res.status(400).send({err});
}
if(result) {
console.log('pasword match');
const jwtToken = jwt.sign({
email: dataResult[0].email,
id: dataResult[0].id
},
'secret',
{
expiresIn: '2h'
});
//tk = jwtToken;
return res.status(200).json({
error:0,
message:'user login successfully',
token:jwtToken
});
}
}else{
res.status(400).send({error:'error occured no email
found'});
}
});
});
};

nodejs returning result from functions

Here's how I write my code
model\user.js
'user strict';
var sql = require('./../db.js');
//User object constructor
var User = function(user){
this.email = user.email;
this.name = user.name;
this.gender = user.gender;
this.profileImageType = user.profileImageType;
this.profileImage = user.profileImage;
this.accountType = user.accountType;
this.createdAt = new Date();
};
User.getCountByEmail = function (email, result) {
console.log("entering user.getCountByEmail with")
console.log(email)
sql.query("Select COUNT(*) AS userCount from users where email = ? ", email, function (err, res) {
if(err) {
console.log("error: ", err);
return result(err, null);
}
else{
console.log("user getCountByEmail returns")
console.log(res)
return result(null, res);
}
});
};
model\userController.js
'use strict';
var User = require('./user.js');
exports.list_all_users = function(req,res){
User.getAll(function(err,user){
console.log('controller')
if (err){
res.send(err);
}else{
console.log('res', user)
res.send(user)
}
});
};
exports.getCountByEmail = function(email,res){
User.getCountByEmail(email, function(err,user){
if (err){
console.log('error', err)
return res.send(err)
}else{
console.log('res', user)
console.log(user)
return user;
}
});
};
index.js
var userController = require('./../model/userController.js');
userController.getCountByEmail("miow#email.com",res,function(err,result) {
if (err){
console.log("34 err")
console.log(err)
}else{
console.log("imin userCount: " + result)
}
});
now in my index.js above, the line userController.getCountByEmail is executed, but I want the result to be accessible inside the function. Unfortunately, it seems the code
function(err,result) {
if (err){
console.log("34 err")
console.log(err)
}else{
console.log("imin userCount: " + result)
}
isn't being executed at all. I only got the line
res [ RowDataPacket { userCount: 1 } ]
imin
[ RowDataPacket { userCount: 1 } ]
which is inside userController.js. So how do I get the result from userController.js sent to index.js ?
function(err,result) {
if (err){
console.log("34 err")
console.log(err)
}else{
console.log("imin userCount: " + result)
}
is not executed because in your model/userController getCountByEmail your only pass two parameters (email, res). So when you call this function in your index.js your actually pass three parameters. with the third one being
function(err,result) {
if (err){
console.log("34 err")
console.log(err)
}else{
console.log("imin userCount: " + result)
}
I would do this:
model/userController
exports.getCountByEmail = function(email,res){
User.getCountByEmail(email, function(err,user){
if (err){
console.log('error', err)
return res.send(err)
}else{
console.log('res', user)
console.log(user)
res.send(user);
}
});
};
index.js
userController.getCountByEmail("miow#email.com",res)
But in general the controller take (req, res, next) as parameter and the res is used like a return because it returns a response to the server.

Do I need the promise in my MySQL statement?

Below is a MySQL statement in my Node.js app. I used a promise in MySQL function to get API endpoint to work. Is this a typical pattern for Node.js and MySQL?
const express = require('express');
const app = express();
app.use(express.static('client'));
const config = require('./config')
var mysql = require('mysql');
var con = mysql.createConnection({
host: config.HOST,
user: config.USER,
password: config.PASSWORD,
database: config.DATABASE
});
function GetConsumers(req, res) {
return new Promise(function (resolve, reject) {
con.connect(function (err) {
if (err) throw err;
con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
if (err) throw err;
//console.log(result);
resolve(result);
});
});
}).then(rows => res.send(rows));
}
app.get('/consumers', GetConsumers);
module.exports = app;
As George commented, you don't really need to return a promise here.
function GetConsumers(req, res) {
con.connect(function (err) {
if (err) {
res.send(err)
};
con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
if (err) {
res.send(err)
};
//console.log(result);
res.send(result)
});
});
}
If you really want to use promises, it is always a good practice to catch the exceptions.
function GetConsumers(req, res) {
return new Promise(function (resolve, reject) {
con.connect(function (err) {
if (err){
reject(err);
}
con.query("SELECT * FROM " + config.DATABASE + ".Contracts",
function (err, result, fields) {
if (err){
reject(err);
}
//console.log(result);
resolve(result);
});
});
})
}
Call GetConsumers function where ever you want it.
GetConsumers(req,res).then(rows => res.send(rows))
}).catch(err =>{
console.log("Handle your error here");
res.send("error")
})
Mysql npm has good documentation of how to use the module. You can refer it more here

If I console.log my results it shows up, but if I return it it doesn't

My return result doesn't make it all the way back to API endpoint.
Do you see what I'm doing wrong?
app.js
const express = require('express');
const app = express();
app.use(express.static('client'));
var GetContracts = require('./contractsService');
app.get('/contracts', async (req, res) => {
var results = await GetContracts.get();
console.log(results);
res.send(results);
});
module.exports = app;
contractsService.js
var mysql = require('mysql');
const config = require('./config')
var con = mysql.createConnection({
host: config.HOST,
user: config.USER,
password: config.PASSWORD,
database: config.DATABASE
});
exports.get = function () {
con.connect(function (err) {
if (err) {
throw new Error('Error by Rodney')
};
con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
if (err) {
throw new Error('Error by Rodney')
};
return result;
//console.log(result); //works
});
});
}
query method accepts error-first callback that isn't affected by returned value. GetContracts.get doesn't return a promise, and awaiting won't do anything.
It should be promisified in order to be used in promise control flow:
exports.get = function () {
return new Promise((resolve, reject) => {
con.connect(function (err) {
if (err) {
reject(new Error('Error by Rodney'))
};
con.query("SELECT * FROM " + config.DATABASE + ".Contracts", function (err, result, fields) {
if (err) {
reject(new Error('Error by Rodney'));
} else
resolve(result);
});
});
});
}
Or preferably, use existing promise-based MySQL library like promise-mysql, something like:
var mysql = require('promise-mysql');
const conPromise = mysql.createConnection({
host: config.HOST,
user: config.USER,
password: config.PASSWORD,
database: config.DATABASE
});
exports.get = async () => {
const con = await conPromise;
const result = await con.query("SELECT * FROM " + config.DATABASE + ".Contracts");
return result;
};