How to store log using Winston logger in Mysql DB? - mysql

I have written according to winston-mysql document. I have described a table in mysql db for storing logs but it's not working.The below is my logger.js -
const winston = require('winston');
const winston_mysql = require('winston-mysql')
var options_default = {
host: process.env.DB_HOST,
user: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
table : 'log',
fields : { level: 'info', meta: 'metadata', message: 'source', timestamp: 'addDate'}
};
var logger = new (winston.createLogger)({
transports: [
new winston_mysql(options_default)
]
});
module.exports = logger;
And this is my controller file where I am using winston.After customer is created it should create a log file into the db. I am not getting any error as such but its not storing into db.What mistake I am doing?
const createCustomer = async(req,res,next) => {
try{
var id = Math.floor(Math.random()*9000000) + 10000000;
var db = req.con;
const data = {
"id": id,
"first_name": req.body.first_name,
"last_name": req.body.last_name ,
"username": req.body.username,
"email": req.body.email,
"password": req.body.password,
"mobile": req.body.mobile,
"address": req.body.address,
"created_date": CurrentTime,
};
console.log(data)
const salt = await bcrypt.genSalt(20);
data.password = await bcrypt.hash(data.password, salt);
var pass = data.password;
console.log(pass)
if (!req.file.filename)
return res.status(400).send('No files were uploaded.');
let filename = fs.readdirSync('./src/template-store/temporaryImage/')
console.log(filename)
var file = req.files
let result = db.query(`INSERT INTO customer set ?`,[data],function(err,rows){
if(err){
res.json({
success:0,
message:"An error occurred",
err
})
}
else{
logger.log({level:'info',message : 'customer'}) // here I am using logger
res.json({
status:1,
message:"Inserted",
data: data
})
// mailer(req.body.username,req.body.email,req.body.password)
}
})
}
catch(error){
res.json({
status:0,
message:"An error occured",
error:error
})
}
}

Related

Add Data in Mongodb and Mysql in single button click

In this application i am adding data in mongodb which is working fine but at same time i need to implement Mysql. So when i register a user it should get save in Mongodb and in Mysql. My Code for Mysql Data Connection is sucessfull but data pushing is not happening(Mysql). Can anyone help me out yr. Thank you very much.
const {Sequelize} =require('sequelize');
const mysql= require('mysql');
var path1 = require('path');
var root_path = path1.dirname(require.main.filename);
var models = require(root_path+'/models');
router.post("/users", function(req, res) {
console.log("First In");
var user_id=req.query.user_id
var flag;
var userData = [];
var body_data =req.body.data;
//Mysql Start
const con = mysql.createConnection({
host: 'localhost',
user: 'root',
password: 'root',
database: 'tcexam'
});
con.connect((err) => {
if(err){
console.log('Error connecting to Db',err);
return;
}
console.log('Connection established');
});
models.userMysl.find({
email: body_data.email.toLowerCase()
})
console.log("Email---------->>>",email);
.then(function(country){
models.userMysl.create({
name: body_data.user_firstName,
lastname : body_data.user_lastname,
mother_name : body_data.motherName,
surname : body_data.Surname,
email: body_data.userEmail.toLowerCase(),
username:body_data.user_name,
password:body_data.user_password,
}).then(function(user) {
if(error){
console.log("Error",error);
}else {
res.send({
status: 200,
data:userData
});
}
});
});
});
//Mysql End
userModel.find({
"role": req.query.user_type
}).then(function(users) {
users.forEach(user => {
if(user.doc_id==''){
var user = {
id: user._id,
name: user.fullName,
status: user.status,
role: user.role,
email:user.email,
lastLoginDate: user.lastLoginDate,
lastLoginTime: user.lastLoginTime,
flag:'0'
}
userData.push(user);
}
else{
var usr = {
id: user._id,
name: user.fullName,
picture: `${filelink}/api/usersData/download?document_id=${user.doc_id}`,
status: user.status,
role: user.role,
email:user.email,
lastLoginDate: user.lastLoginDate,
lastLoginTime: user.lastLoginTime,
flag:'1'
}
userData.push(usr);
}
})
res.send({
status: 200,
data: userData
})
})
"use strict";
module.exports = function(sequelize, DataTypes) {
var userMysql = sequelize.define("tce_users", {
user_name: DataTypes.STRING(100),
user_password: DataTypes.STRING,
surname: DataTypes.STRING(100),
user_email: DataTypes.STRING(100),
user_firstName:DataTypes.STRING(100),
user_lastname:DataTypes.STRING(100),
user_birthdate:DataTypes.String(17),
user_birthplace:Datatypes.STRING(100),
user_regnumber:DataTypes.STRING(100),
user_ssn:DataTypes.STRING(100),
user_level:DataType.STRING(100),
user_verifycode:Datatypes.STRING(100)
});
return userMysql;
};
Since, Node JS is single threaded, after insertion into mysql line of code executes before establishment of connection with mysql db. Somehow connecting with mysql require time therefore next block code executes before connection happen.
Firstly, you need to change approach where you need to connect mysql,
Connection string probably should not be in the post api itself,
it's needs to be connect when application starts using some config utility.
Either you can choose promise to resolve the execution of insertion into
mysql or can use async await approach to insert the data after mysql
connection established.

Cannot use .query commands leaves to an error in nodejs

Problem:
I have created a node application there I am adding admin to the database like this in userModal.js file.
var bcrypt = require('bcryptjs');
var sql = require('../db.js');
module.exports.save_admin = (new_admin,callback) =>{
bcrypt.genSalt(10,(err, salt)=> {
bcrypt.hash(new_admin.password, salt, (err, hash)=> {
new_admin.password = hash;
if(err){
throw err;
}
else{
console.log(new_admin.password);
sql.query("INSERT INTO administrators set ?", new_admin, callback);
}
});
});
}
This is how I am calling this function from the controller.
var admin = {
first_name: req.body.first_name,
last_name: req.body.last_name,
organization: req.body.organization,
admin_level: req.body.admin_level,
user_identity: req.body.identity,
username: req.body.username,
password: req.body.password
};
User.save_admin(admin, (err,user) => {
if (!err) {
res.json({ state: true, msg: "data Inserted" });
} else {
res.json({ state: false, msg: "data Is Not Inserted" });
}
});
This is how I have configured the database in db.js file.
'user strict';
var mysql = require('mysql');
//local mysql db connection
var connection = mysql.createConnection({
host : 'localhost',
user : 'root',
password : '',
database : 'mydatabase'
});
connection.connect(function(err) {
if (!err){
console.log("Database connection succeeded...!");
}
else{
console.log('Error in DB connection :'+JSON.stringify(err,undefined, 2));
}
});
module.exports = connection;
module.exports = {
"secret": "myapplicationsecret"
};
This setup leaves me this error.
sql.query("INSERT INTO administrators set ?", new_admin, callback);
^
TypeError: sql.query is not a function

Node unhandel promises and imports oop

My code have an obj name SQLFeeter that need to do the sql interaction which get the data post it and pass it along I have some problem which is one imports. The babel doesn't work second while I try to get the data and pass it
const express = require('express');
const router = express.Router();
const mysql = require('mysql')
/*
--------------------------------------
This will handel all get requests
--------------------------------------
*/
/*
//sqlInteractuin test
const SqlDataGetter = require('../../sqlInteraction/GetData');
//import SqlDataGetter from "./sqlInteraction/GetData";
let SqlGetter = new SqlDataGetter
*/
class SqlDataGetter {
constructor()
{
this.con = mysql.createConnection({
host: "localhost",
user: "XXX",
password: "XXX",
database: "APP"
});
}
GetClients()
{
let con = mysql.createConnection({
host: "localhost",
user: "XXX",
password: "AAA",
database: "APP"
});
let resultFromSql = null;
con.connect(function(err) {
if (err) throw err;
let sql_query = "SELECT * FROM contacts"
con.query(sql_query , function (err, result, fields) {
if (err) throw err;
//console.log(fields);
console.log(result);
resultFromSql = result;
});
return resultFromSql;
});
}
Tester()
{
//return this.con
//console.log(this.con)
return 'hello world'
}
}
router.get('/' , async (req , res) =>
{
//Need to make an obj that take the data and do all the querys
res.status(200).send("DataBack");
});
router.get('/Clients' , async (req , res) =>
{
let sql_getter = new SqlDataGetter();
const Clients = sql_getter.GetClients();
console.log(Clients);
SqlDataGetter.GetClients()
res.status(200);
res.send({ respond : Clients});
});
While I am trying to run this at first it works on stand alone but when I create the ajax request it saying GetClients is not a function. And when I try to make the connection to be a property of this object as this.con when I activate this.con.query undifend property query of undifend.
If you use promise-mysql instead of mysql then you'll get promises from the method calls, which will make it easier to work with:
const mysql = require('promise-mysql');
Then your class would look like this:
class SqlDataGetter {
constructor() {
this.conPromise = mysql.createConnection({
host: "localhost",
user: "XXX",
password: "XXX",
database: "APP"
});
}
async GetClients() {
const con = await this.conPromise;
const result = await con.query("SELECT * FROM contacts");
console.log(result);
return result;
}
}
Finally, you'd use that class as follows:
router.get('/Clients' , async (req , res) => {
let sql_getter = new SqlDataGetter();
const clients = await sql_getter.GetClients();
console.log(clients);
res.status(200);
res.send({ respond : clients});
});

Router is not recieving JSON from model?

I'm trying to pass an object from a model to my route so I can finish my login system but I'm not recieving anything.
Model code:
const AWS = require('aws-sdk');
const bcrypt = require('bcryptjs');
const config = require('../config/config.json');
var dynamoose = require('dynamoose');
const express = require('express');
var Schema = dynamoose.Schema;
const USER_SCHEMA = new Schema({
username: {
type: String,
required: true
},
firstName: {
type: String
},
lastName: {
type: String
},
email: {
type: String,
required: true
},
credential: {
type: String
},
password: {
type: String,
required: true
}
})
const USER = module.exports = dynamoose.model('Usuarios', USER_SCHEMA);
module.exports.getUserByUsername = function (user, callback) {
var docClient = new AWS.DynamoDB.DocumentClient();
var params = {
TableName: "Users",
KeyConditionExpression: "#us = :uuuu",
ExpressionAttributeNames: {
"#us": "username"
},
ExpressionAttributeValues: {
":uuuu": user
}
};
docClient.query(params, function (err, data) {
if (err) {
console.error("Unable to query. Error:", JSON.stringify(err, null, 2));
} else {
data.Items.forEach(function (user, callback) {
console.log(user.username + ": " + user.password + user.email + user.firstName);
});
}
callback(null, user);
});
}
This is working fine, I can print user.username, user.password and so on, but for some reason my router is not importing the JSON
router.post('/authenticate', (req, res, next) => {
const username = req.body.username;
const password = req.body.password;
USER.getUserByUsername(username, (err, user) => {
if (err) throw err;
if (!user) {
return res.json({
success: false,
"msg": "User not found"
});
}
USER.comparePassword(password, user.password, (err, isMatch) => {
if (err) throw err;
if (isMatch) {
const token = jwt.sign({
username: user
}, secret.secret, {
expiresIn: 86400
});
res.json({
success: true,
token: 'JWT ' + token,
user: {
user: user.username,
password: USER.password,
email: user.email
}
});
} else {
return res.json({
success: false,
msg: 'Wrong password'
})
}
});
});
});
The res.json from comparePassword should be the object from the route (which is the user model) but is not recieving a thing. I have tried with USER.username/email/etc user.username/email/etc but nothing works.
I know I must be missing something somewhere, but where?
Edit: Also tried with module.export.user = user; inside the model

Store JSON data in MySQL table

I have a problem with storing JSON data in MySQL table using NodeJS.
JSON data looks like this:
{
"header":
{
"file1":0,
"file2":1,
"subfiles":{
"subfile1":"true",
"subfile2":"true",
}
},
"response":
{
"number":678,
"start":0,
"docs":[
{
"id":"d3f3d",
"code":"l876s",
"country_name":"United States",
"city":"LA"
},
{
"id":"d2f2d",
"code":"2343g",
"country_name":"UK",
"city":"London"
}
]
}
}
and I want to store only fields in docs array (or response object).
I'm trying to get data and store in mysql in this way:
var express = require('express');
var mysql = require('mysql');
var request = require("request");
var app = express();
app.use('/', express.static('../client/app'));
app.use('/bower_components', express.static('../client/bower_components/'));
var server = require('http').createServer(app);
var bodyParser = require('body-parser');
app.jsonParser = bodyParser.json();
app.urlencodedParser = bodyParser.urlencoded({ extended: true });
//mysql connection setup
var connection = mysql.createConnection({
host : "localhost",
port: "3306",
user : "root",
password : "root",
database : "db",
multipleStatements: true
});
request('http://url.com', function (error, response, body) {
if (!error && response.statusCode == 200) {
//console.log(body) //
}
var data = body.toString();
console.log(string);
var query = connection.query('INSERT INTO table SET ?', data, function(err, result) {
// Finish
});
console.log(query.sql);
});
server.listen(3000, function () {
'use strict';
});
In log I got
INSERT INTO table SET '{\n \"header\":{\n \"file1\":0,\n \"file2\":1,\n \"subfiles\":{\n \"subfile1\":\"true\",\n \"subfile2\":\"true\"}},\n \"response\":{\"number\":678,\"start\":0,\"docs\":[\n {\n \"id\":\"d3f3d\",\n \"code\":\"l876s\",\n....
output message, but I don't have data in MySQL table.
Do I need to specify every column in query?
at your //Finish comment you should have added some console.log(err) to see why there was no data inserted.
Here the solution:
var data = JSON.parse(body);
var responseJson = JSON.stringify(data.response);
var query = connection.query('INSERT INTO table SET column=?', [responseJson], function(err, result) {
if(err) throw err;
console.log('data inserted');
});