unable to log data into database table using node js - javascript

DatabaseConnection.prototype.add_user_transaction =function(tournamenId,userId, callback ){
var dbConn = this;
var insertObject = {
//data
};
var ticketModel = dbConn.rummyConnection.model('tournament_user_transactions');
var transactionPromise = ticketModel.update(insertObject ,{where: {tournament_id: tournamenId, user_Id: userId}}).then(function(result) {
callback({status:"SUCCESS", result: result});
}).catch(function(err){
debug(err.stack);
var error = new Error('Error ');
callback({status:"ERROR", error:error});
});
};
// On debug result is[0], record is not inserting into table.

Related

images won't properly display on tls server

When I go to an image all I get is a square box
This is running latest node as of today I've tried opening the binary file in utf8 and tried not specifying the encoding
var fs = require("fs");
var net = require("net");
var tls = require("tls");
var config = require("config");
var clients = [];
mount = ";";
function get(data) {
var r = /GET\s(.+)\sHTTP/gms;
var rt = r.exec(data)
if (rt != null) { return rt[1] }
}
function handle_data(data, socket) {
if (get(data) == "/") {
var read = fs.readFile("index.html", function(err, data) {
if (err){
console.log(err);
}
var data = data.toString();
var content = data.replace("{port}", config.JCasterPort).replace("{mount}", mount);
var length = content.length
var header = config.HTTP_RESP.replace("{length}", length).replace("{cts}", content).replace("{type}", "text/html");
socket.write(header)
});
}
if (get(data) == "/img/content-bg.png") {
var read = fs.readFile("img/content-bg.png", "utf8", function(err, data) {
if (err){
console.log(err);
}
var data = data.toString();
var content = data;
var length = content.length
var header = config.HTTP_RESP.replace("{length}", length).replace("{cts}", content).replace("{type}", "image/png");
socket.write(header)
});
}
if (get(data) == "/img/background.gif") {
var read = fs.readFile("img/background.gif", "utf8", function(err, data) {
if (err){
console.log(err);
}
var data = data.toString();
var content = data;
var length = content.length
var header = config.HTTP_RESP.replace("{length}", length).replace("{cts}", content).replace("{type}", "image/gif");
socket.write(header)
});
}
if (get(data) == "/img/background.jpg") {
var read = fs.readFile("img/background.jpg", function(err, data) {
if (err){
console.log(err);
}
var data = data.toString()
var content = data;
var length = content.length
var header = config.HTTP_RESP.replace("{length}", length).replace("{cts}", content).replace("{type}", "image/jpg");
socket.write(header)
});
}
}
if (config.JCasterSSL) {
var key = config.JCasterKey;
var cert = config.JCasterCert;
var options = {
key: fs.readFileSync(key),
cert: fs.readFileSync(cert)
};
var server = tls.createServer(options, function(socket) {
socket.on("data", function(data) {
var data = data.toString();
handle_data(data, socket)
});
});
server.listen(config.JCasterPort, function(){
console.log("Listening on port: " + config.JCasterPort)
});
} else {
}
//HTTP_RESP = HTTP/1.1 200 OK\r\nContent-Type: {type}\r\nContent-Length: {length}\r\n\r\n{cts}
My goal is to display the images I know I can use the built in http/https library but I need it to be able to broadcast audio data
the only thing I haven't tried was encoding to ASCII

adding mongodb data value filed using node js

Hello all I have to need to add two field values {type:Number} of one collection from MongoDB using node js
and store the result in the same collection of MongoDB
1st node js query fetching the data value from MongoDB inside my controller.
2nd trying to add the fetched value.
3rd store the result in the same collection of MongoDB using node js.
1). Node js
var levelScoreQuiz = require('../models/levelscoreSchema.js');
try{
var queryObj = {};
var projection = '-id child.quiz_level.score_pre';
var projection2 = '-id child.quiz_level.score_curr';
var a = levelScoreQuiz.findOne(queryObj,projection);
var b = levelScoreQuiz.findOne(queryObj,projection2);
//console.log(a);
//console.log(b);
var add = a + b;
//console.log(add);
res.send(add);
var userObj = {
level_pre:req.params.add
};
var user = new levelScoreQuiz(userObj);
user.save(function(err, result){
if (err) {
console.log('Error While Saving the reuslt ' +err)}
else{
//console.log("User score saved successfully");
console.log("User Previous score saved successfully");
res.json(result);
}
});
}catch(err){
console.log('Error While Saving the reuslt ' +err);
return next(err);
}
2). MongoDB Schema
var userScore = new Schema({
child: {
quiz_level:{
current_level:{type:Number},
score_pre:{type:Number},
score_curr:{type:Number}
}
}
});
3). Result: it shows me object in my browser
"[object Object][object Object]"
var levelScoreQuiz = require('../models/levelscoreSchema.js');
try{
var queryObj = {};
var projection = {id: 0, 'child.quiz_level.score_pre': 1};
var projection2 = {id: 0, 'child.quiz_level.score_curr': 1};
var a = levelScoreQuiz.findOne(queryObj,projection);
var b = levelScoreQuiz.findOne(queryObj,projection2);
//console.log(a);
//console.log(b);
var add = a.child.quiz_level.score_pre +
b.child.quiz_level.score_curr;
//console.log(add);
res.send(add);
var userObj = {
child: {quiz_level: { score_pre: req.params.add}}
};
var user = new levelScoreQuiz(userObj);
user.save(function(err, result){
if (err) {
console.log('Error While Saving the reuslt ' +err)}
else{
//console.log("User score saved successfully");
console.log("User Previous score saved successfully");
res.json(result);
}
});
}catch(err){
console.log('Error While Saving the reuslt ' +err);
return next(err);
}

aws lambda function how to use responses to perform calculation

Trying to create a lambda function that lists tagged ec2 and tagged rds and performs an action thereafter. This is the first time i have used javascript and would appreciate some help.
Please see my example below
var aws = require('aws-sdk');
var ec2 = new aws.EC2();
var rds = new aws.RDS();
aws.config.region = 'us-east-1';
exports.handler = function(event,context) {
if (event) {
console.log(event.id);
}
//setup params for rds call
var rdsparams = {
DBInstanceIdentifier: 'master',
};
//setup params for ec2 call
var ec2params = {
Filters: [
{
Name: 'tag:role',
Values: [
'app'
],
}
]
};
//Get ec2 instances with app tag, may need to add a condition on running so pulled it into hash
ec2.describeInstances(ec2params, function(err, appdata) {
if (err) {
console.log(err);
return;
}
else {
var apparray={};
for(var i = 0; i < appdata.Reservations.length; i++) {
var ins = appdata.Reservations[i].Instances[0];
var id = ins.InstanceId;
var state = ins.State.Name;
apparray[id]=state;
}
console.log(apparray);
context.succeed(apparray);
}
});
rds.describeDBInstances(rdsparams, function(err, data) {
if (err) {
console.log(err, err.stack);
return;
}
else {
var rdsarray={};
var rdsarray=(data);
console.log(rdsarray);
var ins=rdsarray[0];
var name = ins.ReadReplicaDBInstanceIdentifiers[0];
rdsarray[replicant]=name;
}
context.succeed(rdsarray);
});
//context.done();
};
I want to return my filtered (apparray) and (rdsarray) back from my functions and perform a calculation on this within the main body of the script. Any ideas on how to do this.
something like
var replicas = rdsarray.length for example
Thanks in advance
var aws = require('aws-sdk');
var ec2 = new aws.EC2();
var rds = new aws.RDS();
aws.config.region = 'us-east-1';
exports.handler = function(event, context) {
if (event) {
console.log(event.id);
}
//setup params for rds call
var rdsparams = {
DBInstanceIdentifier: 'master',
};
//setup params for ec2 call
var ec2params = {
Filters: [{
Name: 'tag:role',
Values: [
'app'
],
}]
};
//Get ec2 instances with app tag, may need to add a condition on running so pulled it into hash
ec2.describeInstances(ec2params, function(err, appdata) {
if (err)
return context.done(err, null);
var apparray = {};
for (var i = 0; i < appdata.Reservations.length; i++) {
var ins = appdata.Reservations[i].Instances[0];
var id = ins.InstanceId;
var state = ins.State.Name;
apparray[id] = state;
}
console.log(apparray);
var resultData = {};
resultData.apparray = apparray;
rds.describeDBInstances(rdsparams, function(err, data) {
if (err)
return context.done(err, null);
var rdsarray = {};
var rdsarray = (data);
console.log(rdsarray);
var ins = rdsarray[0];
var name = ins.ReadReplicaDBInstanceIdentifiers[0];
rdsarray[replicant] = name;
resultData.rdsarray = rdsarray;
context.done(null, resultData);
});
});
};
and back in the code from you are calling the lambda function
var lambda = new sdk.Lambda();
var params = {
FunctionName: 'arn:aws:lambda:us-west-2:1541546477777:function:MyFunction',
Payload: JSON.stringify(/*your params here*/)
};
lambda.invoke(params, function(err, data) {
if (err) {
console.log('error ===', err);
return ;
}
var lambdaData = JSON.parse(data.Payload);
// do your stuff here
});
Is this what you needed? It may be broken but I hope you get the idea of it

Using parse.com is it possible to convert a string so that it saves as a pointer in the object browser?

Using parse.com and JavaScript.
Currently I have a BadgeSentTo which is a string taken from a html option box. I want to save this to parse, but ideally I want to save it into a pointer column "SentTo" so that it links back to the _User class.
It wont let me save as is, because its expecting a pointer. Is there a why to convert this to a pointer in the code?
$(document).ready(function () {
$("#send").click(function () {
var myBadge = new MyBadge();
var badgeselected = $('#badgeselect img').attr("src");
var BadgeSentTo = $('#SentToUser').val();
var uploadercomment = $('#UploaderComment').val();
myBadge.set("BadgeName", badgeselected);
myBadge.set("Comment", uploadercomment);
myBadge.set("uploadedBy", Parse.User.current());
myBadge.set("SentTo", BadgeSentTo).id;
myBadge.save(null, {
success: function (results) {
console.log("Done");
//location.reload();
},
error: function (contact, error) {
// The save failed.
alert("Error: " + error.code + " " + error.message);
}
});
return false;
});
});
The query capturing the data is
var currentUser = Parse.User.current();
var FriendRequest = Parse.Object.extend("FriendRequest");
var query = new Parse.Query(FriendRequest);
query.include('toUser');
query.include('SentTo');
query.include("myBadge");
query.equalTo("fromUser", currentUser);
query.equalTo("status", "Request sent");
query.find({
success: function (results) {
var friends = [];
for (var i = 0; i < results.length; i++) {
friends.push({
username: results[i].get('toUser').get('username'),
userId: results[i].get('toUser').id
});
var select = document.getElementById("selectNumber");
$.each(friends[0], function (i, v) {
//alert(i+" "+v);
var opt = v;
var el = document.createElement("option");
el.textContent = opt;
el.value = opt;
select.appendChild(el);
})
}
If BadgeSentTo contains the objectId of the User, you'll need to wrap that in a Parse Object. The SDK will convert it to a pointer to _User when it saves.
myBadge.set("SentTo", new Parse.User({id: BadgeSentTo}));

How to display a JSON Object with ListView

I am trying to display a json object with listView using the code below and have no error message but it doesn't works.
return WinJS.xhr({
url: "http://rest-api.wasamundi.com/search/?q=" + userInput
}).then(function (response) {
try {
var result = response.responseText;
var obj = eval("(" + result + ")");
}
catch (e) {
}
//code pour objet recuperer du web
var dataArray = result;
//create object for data obtained from the web
var dataList = new WinJS.Binding.List(dataArray);
var publicMembers =
{
itemList: dataList
};
WinJS.Namespace.define("DataResult", publicMembers);

Categories