How do I use persist with node.js? - javascript

I am attempting to get familiar with this persist package for node. Can someone tell me if the connection is being made here with persist.connect or are these properties?
var persist = require("persist");
var type = persist.type;
// define some model objects
Phone = persist.define("Phone", {
"number": type.STRING
});
Person = persist.define("Person", {
"name": type.STRING
}).hasMany(this.Phone);
persist.connect({
driver: 'sqlite3',
filename: 'test.db',
trace: true
}, function(err, connection) {
Person.using(connection).all(function(err, people) {
// people contains all the people
});
});

The code above runs without error on my system if I just change this.Phone to Phone.
persist.connect "connects" to a test.db file which contains the database.

Related

Node.Js using tmi.js and cleverbot.io trouble

I am currently having trouble with a twitch bot that I am trying to make. I decided to try out Node.js, but I am having a couple of errors. I am using the tmi.js and cleverbot.io libraries, installed via npm. My code so far is as shown below:
var tmi = require('tmi.js');
var cleverbot = require('cleverbot.io');
var options = {
options: {
debug: true
},
connections: {
cluster: "aws",
reconnect: true
},
identity: {
username: "TwitchCleverBot",
password: "APIKEY"
},
channels: ["klausmana"]
};
var client = new tmi.client(options);
var smartbot = new
cleverbot('APIUSERNAME','APIKEY');
client.connect();
client.on("chat", function(channel, userstate, message, self){
if(self){
return;
}
if(message.toLowerCase().includes("cleverbot")){
var lowmessage = message.toLowerCase();
var newmessage = lowmessage.replace("cleverbot", " ");
smartbot.create(function(err, session){
smartbot.ask(newmessage, function(err, response){
client.action(channel, response);
});
});
}
});
This is all the code I have in my app.js so far. The error occurs when I try to make a request to the cleverbot.io, so the tmi.js part works (with as much as I know). It gives me the following error:
Apparently, I am trying to make a JSON parse to a html file, but I really do not understand where and how that happens if anyone is able to help, I would really appreciate it.
P.S : The project is indeed a twitch bot, but my problem was in Node.js and Javascript, so that is why I decided to turn to StackOverflow

How to use servicebus topic sessions in azure functionapp using javascript

I have an Azure Functionapp that processes some data and pushes that data into an Azure servicebus topic.
I require sessions to be enabled on my servicebus topic subscription. I cannot seem to find a way to set the session id when using the javascript functionapp API.
Here is a modified extract from my function app:
module.exports = function (context, streamInput) {
context.bindings.outputSbMsg = [];
context.bindings.logMessage = [];
function push(response) {
let message = {
body: CrowdSourceDatum.encode(response).finish()
, customProperties: {
protoType: manifest.Type
, version: manifest.Version
, id: functionId
, rootType: manifest.RootType
}
, brokerProperties: {
SessionId: "1"
}
context.bindings.outputSbMsg.push(message);
}
.......... some magic happens here.
push(crowdSourceDatum);
context.done();
}
But the sessionId does not seem to get set at all. Any idea on how its possible to enable this?
I tested sessionid on my function, I can set the session id property of a message and view it in Service Bus explorer. Here is my sample code.
var connectionString = 'servicebus_connectionstring';
var serviceBusService = azure.createServiceBusService(connectionString);
var message = {
body: '',
customProperties:
{
messagenumber: 0
},
brokerProperties:
{
SessionId: "1"
}
};
message.body= 'This is Message #101';
serviceBusService.sendTopicMessage('testtopic', message, function(error)
{
if (error)
{
console.log(error);
}
});
Here is the test result.
Please make sure you have enabled the portioning and sessions when you created the topic and the subscription.

Meteor session is undefined after page redirect

I am making a game that requires a lobby of players, but no accounts. Kind of like the game, Spyfall. I am using Meteor Sessions to know which player joined the lobby so that I can return the proper data for that specific player. I have a join.js component where the user enters in the lobby access code and the user's name. This component also redirects the user to the lobby. Join.js is at the route, /join, and the lobbies are at the route, /:lobby. Here is the join.js handleSubmit method which takes the user input and puts it in the players collection:
handleSubmit(event) {
event.preventDefault();
var party = Players.findOne({code: this.refs.code.value});
if(typeof party !== 'undefined') {
Meteor.call('players.insert', this.refs.code.value, this.refs.name.value);
var playerId = Players.findOne({"name": this.refs.name.value})._id;
Meteor.call('players.current', playerId);
location.href = "/" + this.refs.code.value;
} else {
document.getElementById("error").innerHTML = 'Please enter a valid party code';
}
I am using Sessions in the Meteor.methods in the players.js collection to get the current user.
import { Mongo } from 'meteor/mongo';
import { Session } from 'meteor/session';
Meteor.methods({
'players.insert': function(code, name) {
console.log('adding player: ', name , code);
Players.insert({code: code, name: name});
},
'players.updateAll': function(ids, characters, banners, countries, ancestors) {
for (var i = 0; i < characters.length; i++){
Players.update({_id: ids[i]}, {$set: {character: characters[i], banner: banners[i], country: countries[i], ancestor: ancestors[i]},});
}
},
'players.current': function(playerId) {
Session.set("currentPlayer", playerId);
console.log(Session.get("currentPlayer"));
},
'players.getCurrent': function() {
return Session.get("currentPlayer");
}
});
export const Players = new Mongo.Collection('players');
The console.log in the 'players.current' method returns the proper player id, but once the page redirects to /:lobby, the players.getCurrent returns undefined. I want players.getCurrent to return the same value that the console.log returns. How do I fix this issue? This is the function to get the current player id in the lobby.js:
getCurrentPlayerId() {
return Meteor.call('players.getCurrent');
}
Per the Meteor API, Meteor methods are meant to be the way you define server side behavior that you call from the client. They are really intended to be defined on the server.
Methods are remote functions that Meteor clients can invoke with Meteor.call.
A Meteor method defined on the client simply acts as a stub.
Calling methods on the client defines stub functions associated with server methods of the same name
Based on your code it looks like you are doing everything client side. In fact, session is part of the Meteor client API (can't use on the server).
Session provides a global object on the client that you can use to store an arbitrary set of key-value pairs.
Therefore, If I were you, I would just implement all this logic in some sort of util file that you can then import into the Templates where you need it. You are effectively doing the same thing, you just need to use regular functions instead of Meteor methods.
Here is an example util file (be sure to update the Players import based upon your project's file structure).
import { Players } from './players.js';
import { Session } from 'meteor/session';
export const players = {
insert: function(code, name) {
console.log('adding player: ', name , code);
return Players.insert({code: code, name: name});
},
updateAll: function(ids, characters, banners, countries, ancestors) {
for (var i = 0; i < characters.length; i++) {
Players.update({_id: ids[i]}, {$set: {character: characters[i], banner: banners[i], country: countries[i], ancestor: ancestors[i]},});
}
},
setCurrent: function(playerId) {
Session.set("currentPlayer", playerId);
console.log(Session.get("currentPlayer"));
},
getCurrent: function(unixTimestamp) {
return Session.get("currentPlayer");
},
};
Then, you can import this into whatever template you have that has defined the event handler you included in your question.
import { Template } from 'meteor/templating';
import { players } from './utils.js';
Template.template_name.events({
'click .class': handleSubmit (event, instance) {
event.preventDefault();
var party = Players.findOne({code: this.refs.code.value});
if (typeof party !== 'undefined') {
var playerId = players.insert(this.refs.code.value, this.refs.name.value);
players.setCurrent(playerId);
location.href = "/" + this.refs.code.value;
} else {
document.getElementById("error").innerHTML = 'Please enter a valid party code';
}
},
});
Of course you will need to modify the above code to use your correct template name and location of the utils file.
I think the issue is that you are using
location.href = "/" + this.refs.code.value;
instead of using
Router.go("/"+this.refs.code.value);
if using Iron Router. Doing this is as if you are refreshing the page. And here's a package to maintain Session variables across page refreshes.

TypeError: Property 'locals' of object #<ServerResponse> is not a function

I am using a github project to build a chat, but it is a bit outdated using express 3x.
The code tries to pass some data into the req.locals object, the commented out code is what I did but it does not save so it does not work in my io.sockets.on('connection') function.
I am trying to use that object to get some information about a room and the users inside.
/*
* Enter to a room
*/
exports.enterRoom = function(req, res, room, users, rooms, status){
res.locals.room = room;
res.locals.rooms = rooms;
res.locals.user.nickname = req.user.username;
res.locals.user.provider = req.user.provider;
res.locals.user.status = status;
res.locals.users_list = users;
// res.locals({
// room: room,
// rooms: rooms,
// user: {
// nickname: req.user.username,
// provider: req.user.provider,
// status: status
// },
// users_list: users
// });
console.log(res.locals);
res.render('room');
};
You're getting the error because you're trying to invoke res.locals as a function:
res.locals() // this executes a function
when it appears that it's not. I don't know what you're trying to do but this is probably not the way to go about it.

Accessing MySQL database in node.js - internal assertion fails

I'm trying to connect to MySQL database from node.js using db-mysql library. Everything works great with example code, but now I'm trying to write a simple ORM.
This is my code:
require.paths.unshift('/usr/lib/node_modules'); // default require.paths doesn't include this
function Model() {
this.database = null;
}
Model.prototype.getDB = function(callback) {
if (this.database != null)
callback(this.database);
else {
console.log("Connecting to database...");
this.database = require("db-mysql").Database({
"hostname" : "localhost",
"user" : "root",
"password" : "pass",
"database" : "miku",
}).on("ready", function() {
console.log("Database ready, saving for further use.");
this.database = this;
callback(this);
});
}
}
exports.Model = Model;
And simple code I use for testing:
orm = require('./orm');
model = new orm.Model();
model.getDB(function (db) { console.log("callback'd"); });
It looks fine (at least for me), however node.js fails with internal assertion:
Connecting to database...
node: /usr/include/node/node_object_wrap.h:61: void node::ObjectWrap::Wrap(v8::Handle<v8::Object>): Assertion `handle->InternalFieldCount() > 0' failed.
Przerwane (core dumped)
After further investigation, if fails before/during creating Database object. I have no idea why this happens. I first though that it's because I was using git node.js version, but it fails with current release (v0.4.7) as well.
I'm trying to track down this issue in node.js code, with no success at the moment.
Oh, it was me to fail hard. It seems that having Python background is undesired in JavaScript world ;).
Database initialization should look like:
db = require("db-mysql");
new db.Database({
"hostname" : "localhost",
"user" : "root",
"password" : "pass",
"database" : "miku",
}).on("ready", function() {
console.log("Database ready, saving for further use.");
this.database = this;
callback(this);
}).connect();
So, I basically forgot to call new and connect().

Categories

Resources