Connecting Sequelize to Postgres installed with Homebrew - javascript

I'm trying to use Sequelize to connect to my local install of Postgres. I installed it via Homebrew and have confirmed that I can connect and query the database just fine. When I run Sequelize it outputs valid queries (I ran them via console) but the database doesn't change and doesn't log any connection. My current code is:
var sequelize = new Sequelize('reliable_rabbit', 'mohammad', null, {
host: "127.0.0.1",
dialect: 'postgres',
define: { timestamps: true, paranoid: true, underscore: true }//,
});
I can connect to the database via: psql -d reliable_rabbit -U mohammad -h 127.0.0.1. I am using version 1.5.0-beta of Sequelize.
Edit:
In my entry point (app/app.js), logs nothing:
var models = require('./models');
models.Post.sync().success(function(){
console.log("Success!")
}).error(function(error){
console.log("Error: " + error);
});
app/models.js:
var Sequelize = require("sequelize")
var sequelize = new Sequelize('reliable_rabbit', 'mohammad', null, {
host: "127.0.0.1",
logging: console.log,
dialect: 'postgres',
define: { timestamps: true, paranoid: true, underscore: true }//,
});
exports.Post = require("../models/post")(sequelize);
and finally models/post.js:
var Sequelize = require("sequelize");
module.exports = function(sequelize) {
return sequelize.define('post', {
title: { type: Sequelize.STRING, validate: { notEmpty: true } },
permalink: { type: Sequelize.STRING, validate: { is: ["^[a-z]+[a-z\-][a-z]+$"] } },
content: { type: Sequelize.TEXT, validate: { notEmpty: true } },
published: { type: Sequelize.BOOLEAN, defaultValue: false },
published_at: { type: Sequelize.DATE }
},{
instanceMethods: {
generatePermalink: function() {
this.permalink = this.title.toLowerCase().replace(/[^a-z]/g, "-").replace(/^-+|-+$/g,'').replace(/\-{2,}/g, '-');
}
}
});
};

first of all i would recommend the use of sequelize.import. furthermore i'm wondering if you probably just forgot to sync the database? Please let me know if you need further details about those things :)

Related

cypress.origin throws error: (uncaught exception)Error: on only accepts instances of Function

I am using Cypress with Cucumber.
I am trying to test cross origin login but the origin method keeps on throwing error:
Code:
Given(/^the user login to the Test Page$/, function () {
cy.visit("https://example-originalURL");
cy.get("button").contains("Login").click();
const credentials = {
username: "hello",
password: "user",
};
cy.origin("https://example-newURL", { args: credentials }, ({ username, password }) => {
cy.get("#email", { timeout: 20000 }).type(username);
cy.get("#password").type(password, { log: false });
cy.get("button").contains("Login").click();
});
});
Cypress.config.js
module.exports = defineConfig({
projectId: "t7unhv",
e2e: {
setupNodeEvents(on, config) {
on("file:preprocessor", cucumber());
on('task', {
log(message) {
console.log(message +'\n\n');
return null;
},
});
},
specPattern: "./cypress/e2e/features/*.feature",
chromeWebSecurity: false,
experimentalSessionAndOrigin: true,
defaultCommandTimeout: 15000,
env: {
devCentralUrl: "https://***.dev.***.com.au/login",
testCentralUrl:
"https://***.test.***.com.au/login",
test***: "http://***.test.***.com.au",
dev***: "http://***.dev.***.com.au",
uat***: "https://***.uat.***.com.au",
dataSource: "",
environs: "test",
},
retries: {
runMode: 0,
},
pageLoadTimeout: 15000,
reporter: "mochawesome",
reporterOptions: {
reporterEnabled: "mochawesome",
mochawesomeReporterOptions: {
reportDir: "cypress/reports/mocha",
quite: true,
charts: true,
overwrite: false,
html: false,
json: true,
},
},
},
});
Error:
The following error originated from your test code, not from Cypress.
> on only accepts instances of Function
When Cypress detects uncaught errors originating from your test code it will automatically fail the current test.
I have tried multiple syntax changes like not passing the credentials as optional argument to cy.origin.
If someone can provide a quick help, that will be great.
If the problem is in the test code, it is likely to be that newURL is undefined. The error message suggests the problem is in the app, but that might be a red herring.
Try just adding a fixed string for the cy.origin() key,
cy.origin('login', { args: credentials }, ({ username, password }) => {
...
})

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

SQL Server connection using tedius and sequelize in NodeJs

Getting below error when trying to connect SQL Server Local database in NodeJs Sequelize.
name: 'SequelizeHostNotFoundError',
message: 'Failed to connect to abcdd\SQL2K12:1433 - getaddrinfo ENOTFOUND abcdd\SQL2K12',
code: 'ESOCKET
Below are my configuration settings and the credentials are correct
"use_env_variable": false,
"username": "username",
"password": "password#123",
"database": "db_test",
"host": "abcdd\\SQL2K12", //actual db hotsname is abcdd\SQL2K12
"dialect": "mssql",
"operatorsAliases": false,
"dialectOptions": {
"encrypt": true,
"trustedConnection": true
}
In SSMS its working fine. And is there issue with port number? As I am not using a port in SSMS.
For me works adding instanceName instead of putting server: 'SERVER\SQLSERVER2K06',
just put "SERVER".
var config = {
server: 'SERVER',
authentication: {
type: 'default',
options: {
userName: 'user',
password: '*****'
}
},
options: {
database: 'NAME',
instanceName: 'SQLSERVER2K06' /*It Works! */
}
}
for tedious:
options.instanceName
The instance name to connect to. The SQL Server Browser service must be running on the database server, and UDP port 1434 on the database server must be reachable.
(no default)
Mutually exclusive with options.port.
check the comments:
https://github.com/tediousjs/node-mssql/issues/130
var config = {
userName: 'test01',
password: 'test01',
server: 'localhost',
options: {
"database":"TestDB",
"instanceName": "SQL2012"
}
};
in your case
var config = { server: 'abcdd', options: {"instanceName": "SQL2K12" } };
Also, make sure TCP enabled on your SQL Server: Sql Server Configuration Manager > SQL Server Network Configuration > Protocols for SQLSERVER > TCP/IP

Sails js: How can I define two MySQL connections to two different databases in a single model in Sails js?

I have created a model Employee.js and EmployeeController.js. I have defined two connections in Employee.js file:
module.exports = {
connection: 'LocalhostMysqlServer',
attributes: {
name:{
type:"string",
required:true,
},
empnum:{
type:"integer",
required:true,
unique: true
},
email:{
type:"string",
required:true,
unique: true
}
},
connection: 'LocalhostMysqlServer1',
attributes: {
username:{
type:"string",
required:true,
},
usrnum:{
type:"integer",
required:true,
unique: true
},
email:{
type:"string",
required:true,
unique: true
}
},
};
Below is my EmployeeController.js file where I have included two views: CreateEmp & CreateUsr, associated with this Model and controller. Also, I have defined two functions to handle the post requests from these views. Here, I want to insert the data from CreateEmp to a different database and from CreateUsr to a different database.
module.exports = {
createEmp: function(req,res){
'use strict';
res.view('new.ejs');
},
createUsr: function(req,res){
'use strict';
res.view('newUser.ejs');
},
createEmployee: function(req, res){
if(req.method=="POST"){
var name= req.param("name");
var empnum= req.param("empnum");
var email= req.param("email");
var insert= "INSERT INTO employee(name, empnum, email) VALUES ('"+name+"', "+empnum+", '"+email+"')";
Employee.query(insert, function(err, record){
if(err)
console.log(err);
else{
console.log(record);
}
})
}
},
createUser: function(req, res){
if(req.method=="POST"){
var username= req.param("username");
var usrnum= req.param("usrnum");
var email= req.param("email");
var insert= "INSERT INTO user (username, usrnum, email) VALUES ('"+username+"', "+usrnum+", '"+email+"')";
Employee.query(insert, function(err, record){
if(err)
console.log(err);
else{
console.log(record);
}
})
}
},
};
I have included my config/connections.js here:
module.exports.connections = {
localDiskDb: {
adapter: 'sails-disk'
},
LocalhostMysqlServer: {
adapter: 'sails-mysql',
//module: 'sails-mysql',
host: 'localhost',
user: 'root',
password: 'disisanshu',
database: 'sailsTest1',
tableName: 'employee'
},
LocalhostMysqlServer1: {
adapter: 'sails-mysql',
host: 'localhost',
user: 'root',
password: 'disisanshu',
database: 'sailsTest2',
tableName: 'user'
}
};
Here I have included my model.js below:
module.exports.models = {
// migrate: 'alter'
connection: 'LocalhostMysqlServer',
migrate: 'alter',
connection1: 'LocalhostMysqlServer1',
migrate: 'alter'
};
There is no reason why you should do such a thing.
You are probably looking to reduce your load on your database. A master-slave database kind of structure should be implemented instead.
Also, the database should be totally de-coupled from the rest of your app.That is why you should have only one connection.
If the load on your database increases, scale it horizontally (add more servers to distribute the load)- mySQL is good for these things. This can and should be done without any change in your app code.
You can't use two different connections in the same model--hopefully there's no documentation that says this is possible! You'll just have to define two different models.
Also, it's not really valid Javascript to declare the same key twice in an object (as you do with connection in your first code block, and with migrate in your last). The second definition will just override the first if they're different.

Categories

Resources