Why do mysql-event not working in node.js? - javascript

var MySQLEvents = require('mysql-events');
var dsn = {
host: 'localhost',
user: 'root',
password: '' // no password set that's why keep blank
};
var mysqlEventWatcher = MySQLEvents(dsn);
console.log(mysqlEventWatcher);
var watcher =mysqlEventWatcher.add(
'myDB.myTable',
function (oldRow, newRow, event) {
//row inserted
if (oldRow === null) {
//insert code goes here
}
//row deleted
if (newRow === null) {
//delete code goes here
}
//row updated
if (oldRow !== null && newRow !== null) {
//update code goes here
}
//detailed event information
console.log(event); // don't matter, it updates, delete or insert
},
'Active'
);
Take code from https://www.npmjs.com/package/mysql-events
When I try to print console.log(mysqlEventWatcher); ,
it prints something like that
{ started: false,
zongji: {},
databases: [],
tables: {},
columns: {},
events: [ 'tablemap', 'writerows', 'updaterows', 'deleterows' ],
triggers: [],
dsn: { host: 'localhost', user: 'root', password: '' },
settings: {},
connect: [Function: connect],
add: [Function: add],
remove: [Function: remove],
stop: [Function: stop],
reload: [Function: reload],
includeSchema: [Function: includeSchema] }
After writing this code, I update specific table('myTable') in which I implement in mysqlEventWatcher, then It won't go to that method as inside that I am printing event.
I don't know which thing I am missing

I'm adding this answer because this appears first on Google. Hopefully this will help someone.
I'm using XAMPP as my server and in order to get it to work, I edited the my.cnf file, which can be found here: xampp\mysql\bin, with the following:
I enabled every instance of log-bin=mysql-bin (by removing the #) and I wrote-in binlog_format=row.
EDIT :
server-id = 1
log_bin = /var/log/mysql/mysql-bin.log
binlog_format = row

Make sure you enabled binlog on your mysql server and the binlog format is ROW
https://dev.mysql.com/doc/refman/5.7/en/replication-options-binary-log.html
Try to remove 'Active' and make sure you set the correct database and table name to run the first test
var watcher =mysqlEventWatcher.add(
'your_database_name.your_table_name',
function (oldRow, newRow, event) {}
);

As well as checking #nguyendn answer, please try and run ZongJi standalone to check it's functioning
var ZongJi = require('zongji');
var zongji = new ZongJi({
host : 'localhost',
user : 'user',
password : 'password',
debug: true
});
zongji.on('binlog', function(evt) {
evt.dump();
});
If ZongJi is not working, mysql-event will not work either. For me ZongJi was only working on localhost, not remote IP

Related

cant download attachments using mail-listener2

iam using mail-listener2 to download files from an gmail account
it works and I can see the files on the mailListener.on("mail",) event but it looks like
files r not save on the attachments folder
on the file event the file.path is undefined so I am guessing it dit not saved...
why I can't see the files?
why there is a .on("attachment") event id i can see the files on "mail" event?
i only want to process png files, is there any filter i can use?
this is my code...
thanks
import path from "path";
var MailListener = require("mail-listener2");
export class InvoiceFileLisetner {
private readonly hostName: string = 'imap.gmail.com'
private readonly userName: string = 'username';
private readonly password: string = 'password';
private readonly port: number;
public Listen() {
var mailListener = new MailListener({
username: this.userName,
password: this.password,
host: this.hostName,
port: 993, // imap port
tls: true,
connTimeout: 10000, // Default by node-imap
authTimeout: 5000, // Default by node-imap,
debug: console.log, // Or your custom function with only one incoming argument. Default: null
tlsOptions: { rejectUnauthorized: false },
mailbox: "INBOX", // mailbox to monitor
searchFilter: ["UNSEEN"], // the search filter being used after an IDLE notification has been retrieved
markSeen: true, // all fetched email willbe marked as seen and not fetched next time
fetchUnreadOnStart: true, // use it only if you want to get all unread email on lib start. Default is `false`,
mailParserOptions: { streamAttachments: true }, // options to be passed to mailParser lib.
attachments: true, // download attachments as they are encountered to the project directory
attachmentOptions: { directory: path.join(__dirname, '\\attachments/') }
});
mailListener.start(); // start listening
mailListener.on("server:connected", function () {
console.log("imapConnected");
});
mailListener.on("server:disconnected", function () {
console.log("imapDisconnected");
});
mailListener.on("error", function (err) {
console.log(err);
});
mailListener.on("mail", function (mail, seqno, attributes) {
if (mail.attachments != undefined) {
let accountName = mail.subject;
let invoiceFile = null;
for (let index = 0; index < mail.attachments.length; index++) {
if (mail.attachments[index].contentType == 'application/vnd.ms-excel') {
}
}
}
// mail processing code goes here
});
mailListener.on("attachment", function (attachment) {
console.log(attachment.path);
});
}
}

Mail listener on nodejs not disconnecting

I'm currently using mail-listener5 package to assert the number of emails in the Inbox of an email address.
My test framework is nightwatchjs.
Currently, my command script to get the number of emails from the email address inbox (titled getInboxEmails) is;
var {MailListener} = require('mail-listener5');
exports.command = function() {
this.perform(function(done) {
var mailListener = new MailListener({
username: '##########outlook.com',
password: '#########',
host: 'imap-mail.outlook.com',
port: 993,
tls: true,
connTimeout: 10000,
authTimeout: 5000,
tlsOptions: { rejectUnauthorized: false },
mailbox: 'Inbox',
searchFilter: ['ALL'],
markSeen: true,
fetchUnreadOnStart: false,
attachments: false,
});
mailListener.start();
mailListener.on('server:connected', function() {});
mailListener.on('mailbox', function(mailbox) {
var totalInboxMessages = (mailbox.messages.total);
console.log('Total number of Inbox emails: ', totalInboxMessages);
});
// mailListener.on('server:disconnected', function() {
// });
// mailListener.stop();
done();
});
};
And my nightwatchjs test script looks like this;
module.exports = {
'getting emails...': function (browser) {
browser.getInboxEmails();
},
'bfs': function (browser) {
browser.url('https://www.motorcyclenews.com/bikes-for-sale/****');
*...assertions, etc*
},
'closing the browser': function (browser) {
browser.browserEnd();
},
};
When I run this nightwatchjs script, the following is outputted;
however, the browser doesn't close.
I kind of expected this, as in my getInboxEmails command script included;
// mailListener.on('server:disconnected', function() {
// });
// mailListener.stop();
However, when I uncommented these two commands, I didn't get the number of emails displayed (but the test/browser correctly 'shut down'.
So the output was now;
So it appears that the number of emails is correctly displayed when the disconnect and stop are omitted, but the test doesn't cease.
And when the disconnect and stop are added, the number of emails is not displayed but the test finishes correctly.
And what I'd like to do is list the number of emails and for the test to end.
Any help would be greatly appreciated.
Yo need to init your mail listener in beforeAll part
and stop that in afterAll
the problem in your example is that your stop is reached in the init part so your mailbox listener will never be raised
mailListener.on('mailbox', function(mailbox) {
var totalInboxMessages = (mailbox.messages.total);
console.log('Total number of Inbox emails: ', totalInboxMessages);
});
Just do some staff as below
let mailListener ;
jest.beforeAll(() => {
mailListener = new MailListener({
username: '##########outlook.com',
password: '#########',
host: 'imap-mail.outlook.com',
port: 993,
tls: true,
connTimeout: 10000,
authTimeout: 5000,
tlsOptions: { rejectUnauthorized: false },
mailbox: 'Inbox',
searchFilter: ['ALL'],
markSeen: true,
fetchUnreadOnStart: false,
attachments: false,
});
mailListener.start();
mailListener.on('server:connected', function() {});
mailListener.on('mailbox', function(mailbox) {
var totalInboxMessages = (mailbox.messages.total);
console.log('Total number of Inbox emails: ', totalInboxMessages);
});
});
and finally in the end part of your tests
jest.afterAll(() => {
mailListener.stop();
});
wish this help

How to add form-data to Laravel Echo request?

I'm trying to send some data with Laravel Echo request
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'somekey',
wsHost: '127.0.0.1',
wsPort: 6001,
encrypted: false,
disableStats: true,
forceTLS: false,
authEndpoint: 'http://127.0.0.1:8000/broadcasting/auth',
'form-data': { // I tried data, dataForm, dataform
someData: '123', // this doesn't seem to work
},
});
I've seen how to add custom headers to the request
auth: {
headers: {
token: '123'
}
}
Is there any way to add form-data in a similar way?
Edit
When I inspect the network requests in the DevTools, I can see that there are two formData properties sent by the Echo to the server. So I thought there must be a way to attach additional properties into the existing formData object
Is there any way to add form-data in a similar way?
The simple answer is - NO
Laravel Echo doesn't have the functionality to achieve that within the parameter set.
The reason we can see the Form Data object in the Dev Tools requests, is because pusher-js is adding them before making the request to the server. To achieve that, we would have to manipulate the pusher API before the request is executed, but this goes off the original topic of this thread.
So if you want to send the data to the server, the easiest would be adding custom headers as pointed in the original question.
...
auth: {
headers: {
token: '123'
}
}
...
Edit 1
I'm really not sure if this would actually work but can you try this when you can
class LaravelEcho extends Echo {
constructor(options) {
super(options);
this.setformData();
}
setformData(formData = this.options.formData) {
if (formData) {
let path =
"?" +
Object.entries(formData)
.map((ch) => ch.join("="))
.join("&");
this.options.authEndpoint += path;
this.connector.options = this.options;
// since you are using pusher
if (this.connector.pusher) {
this.connector.pusher.options = this.options;
}
// maybe also for socket.io too?
else if (this.connector.socket) {
this.connector.socket.options = this.options;
}
}
}
}
let myEcho = new LaravelEcho({
broadcaster: "pusher",
key: "somekey",
wsHost: "127.0.0.1",
wsPort: 6001,
encrypted: false,
disableStats: true,
forceTLS: false,
authEndpoint: "http://127.0.0.1:8000/broadcasting/auth",
formData: {
foo: "bar",
username: "username",
password: "password",
},
});
console.log(myEcho);
I know this is really not the way you want. I've tried to make it as #Islam said on the comment and I'm really wondering if this is gonna work like this if we just override options after creation :)
Old
I was looking into this. here I saw that there is a headers option as following:
private _defaultOptions: any = {
auth: {
headers: {},
},
authEndpoint: '/broadcasting/auth',
broadcaster: 'pusher',
csrfToken: null,
host: null,
key: null,
namespace: 'App.Events',
};
This is Connecter's default options and inside it's constructor it's also setting an auth header for csrfToken here
So I'm guessing while you are creating your Laravel/Echo you might do,
window.Echo = new Echo({
broadcaster: 'pusher',
key: 'somekey',
wsHost: '127.0.0.1',
wsPort: 6001,
encrypted: false,
disableStats: true,
forceTLS: false,
authEndpoint: 'http://127.0.0.1:8000/broadcasting/auth',
auth: {
headers: {
'X-CSRF-TOKEN': 'your-csrf-token'
'your-header': 'with-value'
}
}
});
Hope this would work for you. Please do let me know! :)
By the way I don't have a test environment so i never tested it..

Unable to retrieve email information in protractor

Referencing the information from the question Fetching values from email in protractor test case, I am still unable to reference the emails. In my test case, the 'expect' is not getting executed for some unknown reason to me.
Also if I use the line,
browser.controlFlow().await(getLastEmail()).then(...)
There is a 'browser.controlFlow(...).await is not a function error'
conf.js
var MailListener = require("mail-listener2")
exports.config = {
framework: 'jasmine2',
specs: ['./test.js'],
jasmineNodeOpts: { defaultTimeoutInterval: 360000 },
allScriptsTimeout: 60000,
onPrepare: function () {
var mailListener = new MailListener({
username: "username",
password: "password",
host: "imapPort",
port: 993, // imap port
secure: true,
tls: true,
tlsOptions: { rejectUnauthorized: false },
mailbox: "INBOX", // mailbox to monitor
searchFilter: ["UNSEEN", "FLAGGED"], // the search filter being used after an IDLE notification has been retrieved
markSeen: true, // all fetched email willbe marked as seen and not fetched next time
fetchUnreadOnStart: true, // use it only if you want to get all unread email on lib start. Default is `false`,
mailParserOptions: {streamAttachments: true}, // options to be passed to mailParser lib.
attachments: true, // download attachments as they are encountered to the project directory
attachmentOptions: { directory: "attachments/" } // specify a download directory for attachments
})
mailListener.start()
mailListener.on("server:connected", function(){
console.log("Mail listener initialized")
})
mailListener.on("error", function(err){
console.log(err)
})
mailListener.on("server:disconnected", function(){
console.log("imapDisconnected")
})
global.mailListener = mailListener
},
onCleanUp: function () {
mailListener.stop()
}
}
The test case:
describe('Email Testing', function () {
it('should login with a registration code sent to an email', function () {
//this line causes a 'browser.controlFlow(...).await is not a function' error
// browser.controlFlow().await(getLastEmail()).then(function (email) {
getLastEmail().then(function (email) {
// The expect does not get executed as it should fail
expect(email.subject).toEqual('My Subject')
})
})
})
function getLastEmail () {
var deferred = protractor.promise.defer()
console.log('Waiting for an email...')
mailListener.on('mail', function (mail) {
console.log('No Console Log Here!')
deferred.fulfill(mail)
})
return deferred.promise
}
I am not certain what I am missing in my test case to be able to read the subject or body of the email?
Ran into the same issue today. Turns out the API for the webdriver and ControlFlow has been updated and await has been changed to wait. Yeah, subtle difference. See the new API reference here: https://seleniumhq.github.io/selenium/docs/api/javascript/module/selenium-webdriver/lib/promise_exports_ControlFlow.html
To schedule a task for the wait condition, change your code to look like this:
browser.controlFlow().wait(getLastEmail()).then(...)
you would basically have to wrap that asynchronous code inside of a promise and the pass that promise/function into the flow.execute()
var flow = protractor.promise.controlFlow();
flow.execute( getLastEmail() ).then(function(email){
text = email.text
});

How to execute Orientdb server side function from Orientjs?

I am using Orientjs to access a Orientdb database from a nodejs script, but the server side function does not effect the database.
Server side script:
This Javascript function addTxt() takes the argument author and text
var db = orient.getGraph();
db.command('sql','insert into Message (author, text) VALUES ("'+author+'", "'+text+'")');
return "1";
Query: This function has been tested in Orient Studio and the following query works:
SELECT addTxt("Testuser","foo")
Nodejs/Orientjs: When invoking this function from a nodejs script using Orientjs, it only returns
[ { '#type': 'd', addTxt: '1', '#rid': { cluster: -2, position: 1 } } ]
and the database remains untouched.
I have tried:
//some code
var OrientDB = require('orientjs');
var server = OrientDB({
host: 'localhost',
port: 2424,
});
var db = server.use({
name: 'database',
username: 'admin',
password: 'pass'
db.query('SELECT addTxt(:arg1, :arg2)', {
params: {arg1:"Testuser",arg2:"foo"}
}).then(function (response){
console.log(response);
});
Other queries from Orientjs works.
What am I doing wrong? Is there an other way to invoke a server side function?
You explicit returns "1"
it is right that returns
[ { '#type': 'd', addTxt: '1', '#rid': { cluster: -2, position: 1 } } ]
try to directly explicit the commit in your function
db.commit()

Categories

Resources