I made a prototype for a real-time voting system by using deepstream.io and rethinkdb as persistence store. So far, it works, and multiple browsers can stay in sync in getting the latest number of vote counts (see screenshot below), however, one thing I don't like it is the vote count is incremented in the browser, which is sent to the deepstream.io remote server.
the JS code embedded in the client's browser:
/**
* Login to deepstream as Frank
*/
var ds = deepstream( 'localhost:6020' ).login({ username: 'Frank'});
var name = 'upvote';
var upVotes;
var voteText = $('.streaming-prices .vote');
var record = ds.record.getRecord(name);
$('#upvote_btn').click(function() {
// on button click, increment the vote counts
// set the record stored in the rethinkdb storage
record.set({
count: ++upVotes
});
});
record.subscribe('count', function(newVal) {
console.info('count updated, newVal: ', newVal);
upVotes = newVal;
voteText.text(newVal);
});
the server.js code:
var PermissionHandler = require( './permission-handler' );
var DeepstreamServer = require( 'deepstream.io' ),
RdbC = require( 'deepstream.io-storage-rethinkdb' ),
server = new DeepstreamServer();
server.set('host', '0.0.0.0');
server.set('port', 6020);
server.set( 'tcpHost', '0.0.0.0' );
server.set( 'tcpPort', '6022' );
server.set( 'permissionHandler', new PermissionHandler() );
server.set( 'storage', new RdbC({
port: 28015,
host: '127.0.0.1',
splitChar: '/',
database: 'votings',
defaultTable: 'question'
}));
server.start();
So you can see that the js code in the client increments the vote counts directly and updates the record, which is to be sent to the deepstream.io server for updating the database. I don't like this part, because I don't want the user to possibly mess up the total vote counts. Instead, I would like the client just to send something like +1 to the server, and let the server update the total counts for persistence. I am not sure if this is possible, can someone shed some light? I appreciate it
Good point, allowing clients to manipulate votes might not work so well!
I would do it using an rpc, that way in the browser you can let a trusted provider increment the record on the users behalf.
The three things you'll need to do is:
request the rpc via the browser
respond to it from a rpc provider ( a trusted client that can respond to the rpc )
add permissions to reject any attempts to change the record from non-providers
Code would look something as follows:
The JS code in browser
/**
* Login to deepstream as Frank
*/
var ds = deepstream( 'localhost:6020' ).login( { username: 'Frank'} );
var voteText = $('.streaming-prices .vote');
var name = 'vote';
var record = ds.record.getRecord( name );
$('#upvote_btn').click(function() {
// on button click, increment the vote counts
// set the record stored in the rethinkdb storage
ds.rpc.make( 'upvote', {}, function( error, response ){
//notify user when upvote succesfull
});
});
record.subscribe('count', function( newVal ) {
console.info( 'count updated, newVal: ', newVal);
voteText.text(newVal);
});
The rpc provider that handles upvotes
/**
* Login to deepstream as Frank
*/
var ds = deepstream( 'localhost:6021' ).login( { username: 'upvote-provider' } );
var name = 'vote';
var record = ds.record.getRecord( name );
ds.rpc.provide( 'upvote', function( data, response ){
record.set( 'count', record.get( 'count' ) + 1 );
response.send();
});
The server should also have permissions to only allow the upvote-provider to change the votes.
canPerformAction: function( username, message, callback ) {
/**
* If the user is a provider, it has all permissions
*/
if( username === 'upvote-provider' ) {
callback( null, true );
}
/**
* Otherwise the client request is valid unless it's trying to change the score
*/
else {
var messageObj = Deepstream.readMessage( message );
var isAllowed = messageObj.name !== 'vote' || messageObj.isRead;
var errorMessage = isAllowed ? null : 'Can\'t change votes via client, use \'upvote\' rpc instead';
callback( errorMessage, isAllowed );
}
}
Related
I’m brand new to programming and I’m currently working on a MySQL database. I’m using Visual Studio Code for all of my JavaScript, HTML, and CSS files.
I have a JavaScript server file that is giving me issues. Our professor gave us his code for the server JavaScript file (which is posted below), his client JavaScript file (which is named contacts.js), and his HTML file.
He told us to open the server JavaScript file, open a terminal and type: node contacts.js. However, doing this gives me error messages that say that the document is not defined.
Occasionally, I'll even get "module not found" errors.
We just did a similar project last week and the terminal worked just fine with a similar node.js command, but I’m running into issues now and don’t know what to do. Hours on Google haven’t helped at all and my professor can’t be contacted for the entire week.
I’m not sure how to get beyond this “document not defined” error. Any help would be appreciated.
Below is the server JavaScript file:
// The following statements are for database connection and queries
var mysql = require('mysql'); // use the msql libraries. Must use 'npm install msyql --save' before using
var bodyParser = require('body-parser'); // use the body-parser library for JSON use. Must 'npm install body-parser --save'
// Set up the SQL connection to the MYSQL database. This will all need to match what you set up in your DB
var connection = mysql.createConnection({
host:'localhost',
user: 'mike',
password: '********',
database: 'contacts'
});
// do the actual connecting by calling the connect method and log the result
connection.connect();
console.log("After connection to DB established in server, setting up web server");
//The following are for web server setup - we are using the express library that makes this all pretty easy
const express = require('express'); // use express library. must use 'npm install express --save'
const cors = require('cors'); // use cors library. must use 'npm install cors --save'
const app = express(); // get the express application object
const path = require('path'); // use the path library for managing paths. must use 'npm install path --save'
const port = 3000; // constant for the port we're using.
// set up the use of JSON url-encoding. Allows us to put all the arguments in the url
app.use(bodyParser.urlencoded({extended: false}));
app.use(bodyParser.json());
// We want to also serve static pages. This command sets that up. In my case, I created a subdirectory called 'public'
// and put the main html page (contacts.html), the javascript client file (contacts.js) and the CSS file (contacts.css)
// in that directory, and therefore I can get everything I need by just goint to (localhost:3000) and it all just works
app.use(express.static('public'));
// This is our main save handler (express calls these 'middleware'). The request coming from the client is a post
// and all the parameters/values are in the query object in the request object (req).
// All the field names here must match the names in the form (name='blah') which we use when we craft the request
// in the javascript saveContact().
// NOTE: we have to use the cors() method to make this all work. Look up cors (Cross-Origin Resource Sharing) to learn about it
app.post('/save', cors(), function (req, res) {
console.log("trying to save contact (post)"); // Log what we're doing
console.log(req); // log the actual request
var curId = req.query.Id; // Get the Id from the query object
var firstName = req.query.fname; // get the fname from the query object
var lastName = req.query.lname; // get the lname from the query object
var age = req.query.age; // etc. etc. etc.
var phone = req.query.phone;
var email = req.query.email;
// We can use the same handler for both cases of saving information:
// 1)we INSERT the new contact in the DB - the Id is 0 in this case
// 2)we UPDATE an existing contact in the DB - the Id is the correct Id for the contact we're updating
// Here we're crafting the appropriate SQL statements using the values above - either INSERT or UPDATE
if (curId > 0) {
var sql = `UPDATE contacts SET fname = '${firstName}', lname = '${lastName}', age = ${age}, phone = '${phone}', email = '${email}' WHERE Id = ${curId}`;
} else {
var sql = `INSERT INTO contacts (fname, lname, age, phone, email) VALUES ('${firstName}', '${lastName}', '${age}', '${phone}', '${email}')`;
}
// Here we're creating the query and the callback function for when we get a response from the DB asynchronously
// This same method executes the SQL call to the database connection we established earlier (above)
connection.query(sql, function (err, result) {
console.log("Trying to save contact into DB"); // log what we're doing
if (err) throw err; // If we get an error, send the error along
console.log(result.affectedRows + " record(s) saved");
res.status(201).send(result); // set the status code (201 = successful add) and send it
console.log(`result of post is: ${result}`); // log the result
console.log(result);
});
});
// This handler is for deleting a user given a valid Id.
// NOTE: we have to use the cors() method to make this all work. Look up cors (Cross-Origin Resource Sharing) to learn about it
app.post('/delete', cors(), function (req, res) {
console.log("trying to delete contact (post)"); // log what we're doing
console.log(req); // log the actual request we received
var curId = req.query.Id; // get the Id from the query object
console.log(curId); // log the Id
// As long as we have a valid Id (in variable curId), we craft the sql statement and execute the query
// all the SQL commands are asynchronous so we provide a callback function
if (curId > 0) {
var sql = `DELETE FROM contacts WHERE Id = ${curId}`; // This is the right SQL statement
connection.query(sql, function (err, result) {
console.log("Trying to delete contact from DB"); // log what we're trying to do
if (err) throw err; // if we get an error, pass it along to the client
console.log(result.affectedRows + " record(s) deleted");
res.status(200).send(result); // otherwise set the status to success (200) and send the result to the client
console.log(`result of post is:`); // log the result
console.log(result);
});
}
});
// THis is our static GET Handler if you just open a browser and type in 'http://localhost:3000'. the '/' means root
// and so this our default page (often called 'index.html' but in this case it's our 'contacts.html')
// Simply send the contacts.html page by getting the default path (wherever we have this javascript file)
app.get('/', function (req, res) {
console.log(req.params);
res.sendFile(path.join(__dirname + '\\contacts.html'));
});
// This is our handler for getting the full list of contacts
// NOTE: we have to use the cors() method to make this all work. Look up cors (Cross-Origin Resource Sharing) to learn about it
app.get('/list', cors(), function (req, res) {
console.log(`inside list GET function, req object is ${req}`);
console.log(req);
// Craft the simple select statement that just gets everything in the contacts table
var sql = `SELECT * FROM contacts`;
//Create the query and execute it, sending the appropriate result back to the client
connection.query(sql, function (err, result) {
console.log(`Trying to get list from DB - result is ${result}`);
console.log(`Inside get list - result first row is ${result[0]}`);
if (err) throw err; // if we get an error, pass it along to the client
res.send(result); // simply send the result of the query to the client.
console.log(`result of GET to list is: ${result}`);
});
});
// This is what actually starts the express server, listening on the port constant we defined at the beginning
// of the file (in this case I'm using 3000) and logging what we're doing.
app.listen(port, () => console.log(`Example app listening on port ${port}!`));
Below is the client JavaScript file:
// This JavaScript file is in support of the contacts application.
// Users can see and manage all their contacts, where a contact is [Id, firstname, lastname, age, phone, email]
// There are functions to manage the http interactions with the server backend
// and to manage the screen/user experience
// This is a globally available array of contacts we get back from the server. Set it initially to an empty array
document.contactList = [];
// This is the function queries the server (using an HTTP GET) to get the list of contacts
// We save the contacts to a globable variable in the document (contactList) and we fill
// both the table at the bottom of the document and a drop-down list used for management
// both of those functionality are function calls ('fillContactTable()' and 'fillContactSelect()')
function getContacts() {
console.log(`Getting contact list from server`); // log what we're doing
var xhttp = new XMLHttpRequest(); // create a variable for HTTP protocol
xhttp.onreadystatechange = function() { // callback function for when a response occurs
console.log(this.responseText); // log the response
// readyState is the XMLHttpRequest state that means we're done. Status is what is returned from the server
// a status code anywhere in the 200's is success. SO if we're done and get a success return code, then we're good!
if (this.readyState == 4 && (this.status >= 200 && this.status < 300)) {
console.log(`Got the contact list successfully`); // Log that we're good
document.contactList = this.responseText; // The response is the actual list of contacts.Set to globabl var in document
fillContactTable(); // Fill the table
fillContactSelect(); // Fill the drop down list (select element)
} else {
console.log(`failed to get contact list`); // Log failure if that's what we got
}
}
// We've set the callback function that handles the result. This is the actual setting up the http request (the open method)
// and the actual sending of the http request (send method)
xhttp.open("GET", "http://localhost:3000/list", true);
xhttp.send();
}
// Given an Id of a contact, get the rest of the contact information and return it
// The pLocal parater is in case we want to get the contact information from the server instead of getting it from
// the global variable (document.contactList). Default is to be local.
function getContactById(pId, pLocal = true) {
console.log(`Getting contact by ID = ${pId}`); // log what we're doing
if (pLocal) { // If we're local, get the data from document.contactList
var contactsJSON = JSON.parse(document.contactList); // parse the contactList into JSON format - easier to deal with
// Loop through all the contacts in the JSON formated list of contacts to look for the one we want (by Id)
for (loopIndex = 0; loopIndex < contactsJSON.length; loopIndex++) {
if (contactsJSON[loopIndex].Id == pId) { // if Id's match, we're good but log what we found
console.log(`Found contact in getContactById. Index = ${loopIndex}`);
console.log(contactsJSON[loopIndex]);
return contactsJSON[loopIndex]; // Return the found contact
}
}
console.log(`Did not find the contact in getContactById`); // log the fact that we didn't find it and return null
return null;
// For now, if we're not local just return null. Will add the code to get the data from the server later
} else {
return null;
}
}
// Simple function that just clears the form that we use for showing, creating new, and updating contacts
function clearEditForm() {
console.log("clearing the contact form"); // Log what we're doing
// Set all the values to empty (or 0 for the Id - that has to be a number)
document.getElementById('contact_id').value = 0;
document.getElementById('contact_fname').value = "";
document.getElementById('contact_lname').value = "";
document.getElementById('contact_age').value = "";
document.getElementById('contact_phone').value = "";
document.getElementById('contact_email').value = "";
// Now control the user experience. Hide the ID fields and change the name of the button to "Insert"
document.getElementById('contact_id').hidden = true;
document.getElementById('contact_id_label').hidden = true;
document.getElementById('save_button').innerHTML = "Insert Contact";
document.getElementById('save_button').name = "Insert Contact";
}
// Main function that saves the contact form. We have two cases to deal with:
// 1) We're inserting a new contact. In that case, the Id (curId below) will be 0
// 2) We're updating an exesting contact. In that case, the Id will NOT be 0
// If the ID is not a number >= 0, we have a problem so we don't do anything
function saveContact() {
console.log("Attempting to save contact"); // Log what we're doing
// Get all the values from the elements in the form by name.
var curId = document.getElementById('contact_id').value;
var curFName = document.getElementById('contact_fname').value;
var curLName = document.getElementById('contact_lname').value;
var curAge = document.getElementById('contact_age').value;
var curPhone = document.getElementById('contact_phone').value;
var curEmail = document.getElementById('contact_email').value;
console.log(`Trying to save contact in saveContact. Id = ${curId}`);
// As long as we have a valid Id (number at least 0) we'll make the http request (a POST)
if (curId >= 0) {
var xhttp = new XMLHttpRequest(); // Create a new HTTP object and put it in xHTTP variable
// As in all of our interactions implementing http, we supply a callback function for when we actually get a response
// Remember, all http request/responses should be asynchronous, and so we have to use callbacks
xhttp.onreadystatechange = function() {
console.log(this.responseText); // log what's happening
// If readyState shows we're done (value == 4) and status code is in the 200's we got a success response
if (this.readyState == 4 && (this.status >= 200 && this.status < 300)) {
console.log(`saved the contact successfully`); // Log our success
getContacts(); // Re-get our contact list since it has changed
} else {
console.log(`failed to save contact `); // Log our failure response
console.log(this.status); // log the actual status code
console.log(this.responseText); // log the actual response text
}
}
// Here we're crafting the http POST request with all the parameters urlencoded. Look up url encoding to understand it
// As usual, the open method is used to set up the call, and the send method actually sends the request
xhttp.open("POST", `http://localhost:3000/save?Id=${curId}&fname=${curFName}&lname=${curLName}&age=${curAge}&phone=${curPhone}&email=${curEmail}`, true);
xhttp.send();
}
}
// Function to delete a contact by creating the right server http request (a POST)
// We'll pass the Id of the contact we want to delete in the url (url-encoded)
// We'll get the name of the contact to be deleted and prompt the user to verify that they want to really delete the contact
// look up the window method 'confirm' to understand how that works
function deleteContact() {
console.log("Attempting to delete contact"); // Log what we're doing
var contactList = document.getElementById('contacts_list'); // get the drop-down select element in the form
var curId = contactList.value; // get the value of the form, which will be an Id of the contact to be deleted
var curIndex = contactList.selectedIndex; // We need the index of the option chosen to get the name for prompting the user
var curName = contactList.options[curIndex].text; // get the name from the option list based on the index
console.log(`Trying to verify delete. curid = ${curId}, curIndex = ${curIndex}, and curName = ${curName}`);
// Prompt the user to confirm using the window.confirm method. If they say ok, confirm returns true
// if they say cancel, confirm returns false. We're checking for the false, thus the not (!) at the beginning of the condition
if (!confirm(`Are you sure you want to delete contact: ${curName}?`)) {
return; // If we're here they said cancel, so just return out of here
}
console.log(`Trying to delete contact in fillEditForm. Id = ${curId}`);
if (curId.length > 0) { // Make sure we have a good Id
var xhttp = new XMLHttpRequest(); // create the http object
// Here's our callback for the asynchronous return. As long as we get a good status code, we update the form appropriately
xhttp.onreadystatechange = function() {
console.log(this.responseText); // log the actual response
// readyState 4 means we're done, and status in the 200's means success, so re-get the contact list from the server
if (this.readyState == 4 && (this.status >= 200 && this.status < 300)) {
console.log(`deleted the contact successfully`);
clearEditForm(); // clear the form since we deleted the contact
getContacts(); // get the contacts from the server
} else {
console.log(`failed to delete contact list`);
}
}
// Create the actual request and send it.
xhttp.open("POST", `http://localhost:3000/delete?Id=${curId}`, true);
xhttp.send();
}
}
// Simple function to clear the table element. We delete all the rows backwards. Make the function generic by allowing
// a parameter (pTable) which is the name of the table to be reset if there is more than one on the form
function tableDeleteRows(pTable = "") {
var curTable;
if (pTable.length == 0) {
curTable = document.getElementById('contacts_table');
} else {
curTable = document.getElementById(pTable);
}
// We start at the end of the rows (rows[length-1]), deleting backwards until we delete all of them
for (i = curTable.rows.length - 1; i >= 0; i--) {
curTable.deleteRow(i);
}
}
// Simple function to clear a drop-down select element. We delete all the rows backwards. Make the function generic by allowing
// a parameter (pSelect) which is the name of the select element to be reset if there is more than one on the form
function selectDeleteOptions(pSelect = "") {
var curSelect;
if (pSelect.length == 0) {
curSelect = document.getElementById('contacts_list');
} else {
curSelect = document.getElementById(pSelect);
}
// Go backward from the end of the list of options in the select, removing them until we remove all of them
for (i = curSelect.length - 1; i >= 0; i--) {
curSelect.remove(i);
}
}
// Assuming we have a contact chosen in the drop-down select element, fill the edit form with all the values for that contact
function fillEditForm() {
console.log("filling the contact form"); // Log what we're doing
var contactList = document.getElementById('contacts_list'); // get the drop-down list
var curId = contactList.value; // the selected element Id is the value of the list
console.log(`Trying to find contact in fillEditForm. Id = ${curId}`);
var curContact = getContactById(curId); // Get the whole contact by calling the function
console.log(curContact); // log the contact we're using to fill the form
// As long as we have a good contact, we fill the form
if (curContact != null) {
document.getElementById('contact_id').value = curContact['Id'];
document.getElementById('contact_fname').value = curContact['fname'];
document.getElementById('contact_lname').value = curContact['lname'];
document.getElementById('contact_age').value = curContact['age'];
document.getElementById('contact_phone').value = curContact['phone'];
document.getElementById('contact_email').value = curContact['email'];
}
// after we fill the form, we set elements appropriate to things like update and delete instead of add new
document.getElementById('contact_id').hidden = false;
document.getElementById('contact_id').disabled = true;
document.getElementById('contact_id_label').hidden = false;
document.getElementById('save_button').innerHTML = "Update Contact";
document.getElementById('save_button').name = "Update Contact";
}
// This function fills the table at the bottom of the document with all the contacts and all the information
function fillContactTable() {
console.log("Filling the contacts table in the form"); // Log what we're doing
tableDeleteRows("contacts_table"); // Reset the table
// if we don't have anything in the global contact list - forget it and return
if (document.contactList.length == 0) {
console.log("the contact list/array is empty!");
return;
}
// We have contacts in the global array, so first parse the array into JSON and process it
var contactsJSON = JSON.parse(document.contactList);
var properties = ['Id', 'fname', 'lname', 'age', 'phone', 'email']; // we need the property names
var tr, curRow; // variables for table properties
var contactTable = document.getElementById("contacts_table"); // get the table element
// cycle through the rows in the contacts array
for (var rowIndex = 0; rowIndex < contactsJSON.length; rowIndex++) {
console.log(`Creating table rows, rowindex is ${rowIndex}`);
tr = document.createElement('tr'); //create a new table row element
curRow = contactsJSON[rowIndex]; // get the current row from the array
console.log(curRow); // log the data in the current row
// Cycle through the columns - defined in the property array above and add column elements to the row in the table
for (var i = 0; i < properties.length; i++) {
console.log(`Creating table columns for row ${i}, property is ${properties[i]} value is ${curRow[properties[i]]}`);
var td = document.createElement('td'); // create a data element for the column
td.appendChild(document.createTextNode(curRow[properties[i]])); //Append the property data to the new data element
tr.appendChild(td); // append the new data element to the row element
}
contactTable.appendChild(tr); // append the row element to the table element
}
console.log("Finished procesing contacts list");
}
// Fill the drop-down select. First reset the select (removing all options), then recreate it
function fillContactSelect() {
console.log("Filling the contacts drop down select in the form"); // log what we're doing
selectDeleteOptions("contacts_list"); // Reset the select element clearing all options
// if we don't have anything in the global contact list - forget it and return
if (document.contactList.length == 0) {
console.log("the contact list/array is empty!");
return;
}
// We have contacts in the global array, so first parse the array into JSON and process it
var contactsJSON = JSON.parse(document.contactList);
var properties = ['Id', 'fname', 'lname']; // only need Id, fname, lname for drop down
var option, curRow; // variables for table properties
var contact = document.getElementById("contacts_list"); // get the select drop down element
// cycle through the rows in the contacts array
for (var rowIndex = 0; rowIndex < contactsJSON.length; rowIndex++) {
console.log(`Creating select items, rowindex is ${rowIndex}`);
option = document.createElement('option'); //create a select option element
curRow = contactsJSON[rowIndex]; // get the current row from the array
console.log(curRow); // log the data in the current row
// the value of this option will be the id, since that's what we'll use to get a contact. The text is fname + lname
option.value = curRow["Id"];
option.appendChild(document.createTextNode(`${curRow['fname']} ${curRow['lname']}`));
contact.appendChild(option); // append the option to the select element
}
console.log("Finished procesing contacts list");
}
// When the windo first loads, get the list of contacts which will also fill the table and drop down list
window.onload = function() {
getContacts();
};
You are running the wrong JS file. You want to do:
node contactserver.js
At the moment you are running contacts.js, which is client-side code.
To expand on this, you're seeing that error because document is a global variable available in browsers, but not in Node.js. Frontend code designed to run in a browser often relies in browser APIs that simply don't exist on a server, so attempting to run a client-side only file in a server environment will throw errors when it can't find global objects that only exist in a browser.
(Props to #Jon Church for the explanation from the comments below)
Turns out that contacts.js was the wrong file. Typing into the terminal: node contactsserver.js was the solution.
I have almost completed pub/sub fake-server, that requests user password and email (from the client), compares this info with database and returns data back. It has 'api_in' and 'api_out' frames and then the JSON.
The publisher takes and processes all the info without a hitch, but it doesn't seem to send anything back to the client (subscriber) and I don't know why, cause it is connected to the subsequent port.
And I know that this implementation is not a classic PUB/SUB pattern, but that was prerequisite, to do it like that.
I tried different pub/sub options, but nothing has changed.
Server
let zmq = require('zeromq');
const sqlite3 = require('sqlite3').verbose();
const DBSOURCE = "./db.sqlite";
let db = new sqlite3.Database(DBSOURCE, (err) => {
if(err) {
console.error(err.message);
throw err;
} else {
console.log('Connected to SQLite database');
db.run(`CREATE TABLE users (
user_id INTEGER,
email TEXT,
passw TEXT)`,
(err) => {
if (err) {
// Table already created
} else {
// Creating rows
let insert = 'INSERT INTO users (user_id, email, passw) VALUES (?,?,?)';
db.run(insert, [123098, 'phillCollins#gmail.com','5502013']);
db.run(insert, [42424242,'dukenukem3d#mustdie.com','RodriguesShallLiveLong']);
db.run(insert, [5,'yourchick#yandex.ru','semolinaAndPain666']);
}
})
}
});
const args = require('minimist')(process.argv.slice(2));
const pubSocket = zmq.socket('pub', null);
pubSocket.bindSync(`tcp://127.0.0.1:${args['pub']}`);
const subSocket = zmq.socket('sub', null);
subSocket.subscribe('api_in');
subSocket.on('message', function(data) {
let message = data.toString().replace(/api_in/g, '');
let mes = JSON.parse(message);
let api_out = 'api_out';
let errorWrongPWD = 'WRONG_PWD';
let errorWrongFormat = 'WRONG_FORMAT';
if(mes.type = 'login') {
db.get(`SELECT user_id from users WHERE email = ? and passw = ?`, [mes.email, mes.pwd], function(err, row) {
if(err) {
console.log(err);
} else {
if(row) {
let msg = {
msg_id: mes.msg_id,
user_id: row.user_id,
status: 'ok'
}
let outMessage = api_out + JSON.stringify(msg);
console.log(outMessage);
subSocket.send(outMessage);
} else {
let msg = {
msg_id: mes.msg_id,
status: 'error',
error: mes.email == '' || mes.pwd == '' ? errorWrongFormat : errorWrongPWD
}
console.log(msg);
let outMessage = api_out + JSON.stringify(msg);
subSocket.send(outMessage);
}
}
});
}
});
subSocket.bindSync(`tcp://127.0.0.1:${args['sub']}`);
client
let zmq = require('zeromq');
let uniqid = require('uniqid');
let readline = require('readline').createInterface({
input: process.stdin,
output: process.stdout
});
const args = require('minimist')(process.argv.slice(2));
const pubSocket = zmq.socket('pub', null);
let pubSocketTCP = `tcp://127.0.0.1:${args['sub']}`;
pubSocket.connect(pubSocketTCP);
const subSocket = zmq.socket('sub', null);
let subSocketTCP = `tcp://127.0.0.1:${args['pub']}`;
subSocket.connect(subSocketTCP);
let api_in = 'api_in';
let secondFrame = {
type: 'login',
email: '',
pwd: '',
msg_id: uniqid()
}
readline.question('What is your email? \n', (email) => {
secondFrame.email = email;
readline.question('What is your password \n', (pwd) => {
secondFrame.pwd = pwd;
let msg = api_in + JSON.stringify(secondFrame);
console.log(msg);
pubSocket.send(msg);
});
});
subSocket.subscribe('api_out');
subSocket.on('message', (response) => {
/* let res = response.toString().replace('api_out');
let responseParsed = JSON.parse(res);
console.log(responseParsed.status);
if(response.status == 'error') console.log(response.error); */
console.log(response);
});
I want the server side to send info back.
Well, first of all, welcome to the Zen-of-Zero domain. ZeroMQ is a powerful tool for smart signaling / messaging, so if you pay attention to all its internal beauties, there will be no such thing you will not be able to do with it ( nightmares still not avoided on this way forward ). If feeling to be new to this domain, one may enjoy a short read into "ZeroMQ Principles in less than Five Seconds" before diving into further details on subject, or re-use some of tricks posted here
Q : it doesn't seem to send anything back to the client (subscriber) and I don't know why
There are two pieces of code, that seem to use both PUB and SUB Scalable Formal Communication Pattern Archetypes, yet have some glitches on how these get configured.
The server-code :
seems to try to instantiate PUB-archetype and equips that instance with a single AccessPoint, using .bindSync()-method and cli-parameter args['pub'] for accepting connections over a plain and commontcp://-transport-class.
After defining the event-handler .on( 'message', ... ) for the second instance, being the SUB-archetype, this one becomes .bindSync()-equipped with a single AccessPoint, using tcp://-transport-class, for receiving connections using tcp://-transport-class.
If you indeed have to make a .send() over a SUB-alike archetype, you have to use XSUB alternative, where you can send data and perform some tricks with the actual payload on the PUB-side or XPUB-side ( ref. API documentation for details about ZMQ_XPUB_MANUAL mode capabilities and limits for some wilder data-mangling on the XPUB-side )
ZMQ_XSUB
Same as ZMQ_SUB except that you subscribe by sending subscription messages to the socket. Subscription message is a byte 1 (for subscriptions) or byte 0 (for unsubscriptions) followed by the subscription body. Messages without a sub/unsub prefix may also be sent, but have no effect on subscription status.
The client-code :
Seems to instantiate and .connect() both the client-local PUB and SUB Archetypes over tcp://-transport-class to the server-side AccessPoints ( which both ought to set ZMQ_LINGER to 0, so as to avoid infinitely hanging orphans ( version dependent defaults do not have other solution but an explicit setting on this ) ).
Possible improvements :
XPUB/XSUB with ZMQ_XPUB_MANUAL may solve the sending via SUB-archetype
XPUB/SUB with ZMQ_XPUB_MANUAL may solve the sending via SUB-archetype with less comfort of masquerading the messages to be sent via the .subscribe()-method
PUB/SUB with making all .send()-s strictly via a local PUB-archetype instance.
be explicit with ZMQ_SNDHWM and ZMQ_RCVHWM parameters if still loosing messages
be explicit on setting .subscribe() only after a successfully completed { .bind() + .connect() }-methods ( systematically using original zmq_errno() and zmq_strerror() functions for actively detecting and repairing the potential colliding states )
may request to work with only completed connections ( distributed systems have zero-warranty of an order of operations autonomous distributed (many) agents perform ) using .setsockopt( ZMQ_IMMEDIATE, 1 )
Your server is trying to send on the sub socket
subSocket.send(outMessage);
You can't send on the sub socket. It should be sending on a pub socket.
I am trying to send a Push Notification through Parse Cloud Code when a certain object has been modified - "dirty"
I think I am almost there, but received an error because I believe am creating a new user instead of querying for one.
Parse.Cloud.beforeSave("Fact", function(request, response) {
var dirtyKeys = request.object.dirtyKeys();
for (var i = 0; i < dirtyKeys.length; ++i) {
var dirtyKey = dirtyKeys[i];
if (dirtyKey === "isValid") {
//send push
// Creates a pointer to _User with object id of userId
var targetUser = new Parse.User();
// targetUser.id = userId;
targetUser.id = request.object.userID;
var query = new Parse.Query(Parse.Installation);
query.equalTo('user', targetUser);
Parse.Push.send({
where: query,
data: {
alert: "Your Fact was approved :)"
}
});
return;
}
}
response.success();
});
I found this post related to my problem. My question now is how to integrate the user query in my beforeSave block. Ideally I would create another function for the user query and place that in my beforeSave block.
**5/14 Update
I took #toddg's advice and fixed the before save. Here is a clearer picture of what I am trying to do and the new error.
A couple points (as #Subash noted in the comments) before I get into the code:
Parse.Push.send is an async operation, so you'll want to ensure you call response.success() after your push send completes. I'm going to deal with this using Promises, as I think they are more flexible than callbacks. If you're not familiar, read about them here
The return in your if statement will likely prevent the response.success() from being called.
Here's my recommended way of doing it:
Parse.Cloud.beforeSave("Fact", function(request, response) {
// Keep track of whether we need to send the push notification
var shouldPushBeSent = false;
var dirtyKeys = request.object.dirtyKeys();
for (var i = 0; i < dirtyKeys.length; ++i) {
var dirtyKey = dirtyKeys[i];
if (dirtyKey === "isValid") {
shouldPushBeSent = true;
}
}
if (shouldPushBeSent) {
//send push
// Creates a pointer to _User with object id of userId
var targetUser = new Parse.User();
// targetUser.id = userId;
targetUser.id = request.object.userId;
var query = new Parse.Query(Parse.Installation);
// We want to pass the User object to the query rather than the UserId
query.equalTo('user', targetUser);
Parse.Push.send({
where: query, // Set our Installation query
data: {
alert: "Your fact was approved"
}
}).then(function(){
// Now we know the push notification was successfully sent
response.success();
}, function(error){
// There was an error sending the push notification
response.error("We had an error sending push: " + error);
});
} else {
// We don't need to send the push notification.
response.success();
}
});
By the way, I'm assuming that you have a column on your Installation class that tracks which user is associated with each Installation.
I have an array of clients with their _id's from mongo, I wanted to know how can I route all of them (at once) to a page using router?
example: 3 users are landing on a page named "game", when there are 3 people I have an array which saves their userID, all the users with their ID's saved in the array should be routed to another page (for examle: "page2"). I understand that this should be done from server side perspective but im having a hard time to figure this one out.
//client
Template.GameLayout.onRendered(function () {
var ses = Session.get("loggedIn");
Meteor.call('userCounter', ses, function(error, fullArray){
if(error && error.error === "noArray"){
console.log(error);
console.log("I have error");
} else {
if(fullArray){
var usersArray = fullArray[1];
var randomGen = fullArray[0];
console.log(randomGen);
}
}
})
//server
userCounter: function(sessions){
usersArray.push(sessions);
var usersConnected = usersArray.length;
if(!usersConnected){
throw new Meteor.Error("noArray");
console.log("oops heres the problem");
} else {
if(usersConnected > 2){
var randomGen = Math.floor(Math.random() * 9999999) + 1;
var fullArray = [randomGen, usersArray];
console.log(fullArray);
return fullArray;
usersArray =[];
}
}
}
Personally I would just do this in a Tracker.autorun() on the client-side, ex:
Tracker.autorun(function(){
if ( ... condition that you want to re-route on ... ){
Router.go('page2');
}
});
Your array would have to be published in a collection of some kind, say active games so that the client could do its logic and route accordingly.
I have a model: api/models/Agency.js
attributes: {
// attributes for agency
// One agency can have many owners
owners: {
collection: 'user',
required: true,
via: 'agencies'
},
employees: {
collection: 'user',
via: 'employer'
}
}
The model has a many to many relationship with Users; as many Users can own many Agencies.
I want to protect the Blueprint controller for Agency (AgencyController.js) with a Policy called isOwner.js; which makes sure the User is the owner of the Agency before allowing them to make an edit. I have based the policy on the example found in the Sails.js docs, where I am trying to ensure the userId (found in the session) is the owner of the resource.
api/policies/isOwner.js:
module.exports = function(req, res, next) {
var userId = req.session.passport.user;
req.options.where = req.options.where || {};
req.options.where.owners = userId;
return next();
};
Then in my config/policies.js file I have added the following:
AgencyController: {
destroy: ['isOwner'],
update: ['isOwner']
},
This doesn't work. I think its because of the many to many relationship between the two models. My question is can I create a policy that can query a many to many relationship? Or is it only possible through a one to many relationship?
Thanks.
I couldn't find a way of nicely protecting the blueprint methods by a policy alone so I created a service that checked the user was the owner of the model, and then extended the update and destroy methods in my controller.
api/services/isOwner.js:
/**
* Only allow access to models if they are the owner.
* Assumes an attribute called owners on the model and assumes it has a relationship that can be queried through the
* 'populate' waterline method.
*/
var actionUtil = require( 'sails/lib/hooks/blueprints/actionUtil' );
var _ = require( 'underscore' );
/**
* #param req
* #param res
* #param is {function} called if the user is the owner
* #param isnt {function} called if the user is not the owner. If not present will redirect 403 not authorised.
*/
module.exports = function isOwner( req, res, is, isnt ){
var ownerEmail = req.options.where.owner;
var Model = actionUtil.parseModel( req );
isnt = isnt || res.forbidden;
is = is || function(){
sails.log.warn( 'No callback defined for isOwner' );
res.ok();
};
Model.findOne({ id: req.params.id }).populate( 'owners' ).exec( function( error, model ){
var canEdit = _.find( model.owners, function( owner ){
return owner.email === ownerEmail;
});
canEdit ? is() : isnt();
});
};
api/controllers/AgencyController.js:
var update = require( 'sails/lib/hooks/blueprints/actions/update' );
var isOwner = require( '../services/isOwner' );
module.exports = {
/**
* Override the default blueprint update behaviour so only the owner can update a record.
*
* #param req
* #param res
*/
update: function( req, res ){
isOwner( req, res, update );
}
};
Doesn't feel like the nicest way of doing it but it's the only way I could think of. Just thought I'd share it on here just incase someone comes across the same problem OR someone has a better solution.