Testing Postgre Database on Heroku - javascript

I am currently building an API with Swagger on Heroku and i would like to try if the endpoints are creating the correct entries in the Postgre Database. However, once i try to connect to Heroku's Postgre in my testing envoirment the connection is rejected. I think this is because in the continous integration envoirnment heroku creates a sandbox and does not accept connections to the real dbs.
I tried to create a backup database as suggested here: https://devcenter.heroku.com/articles/heroku-postgres-backups
but i couldn't find the information to access!
Any help is appreciated!
Thank you.
Here is my code test:
'use strict';
var should = require('should');
var request = require('supertest');
var assert = require('assert');
var server = require('../../../app');
var pg = require('pg');
var knex = require('knex')({
client: 'postgresql',
connection: process.env.DATABASE_URL
});
describe('controllers', function () {
describe('testing cenas', function () {
it('test1', function (done) {
request(server)
.get('/hello')
.set('Accept', 'application/json')
.expect('Content-Type', /json/)
.expect(200)
.end(function (err, res) {
assert.equal(res.body, 'Hello,Hugo Pereira!');
done();
});
});
});
});
it gives an error:
Unhandled rejection Error: Unable to acquire a connection
at Client_PG.acquireConnection (/app/node_modules/knex/lib/client.js:332:40)
at Runner.ensureConnection (/app/node_modules/knex/lib/runner.js:233:24)
at Runner.run (/app/node_modules/knex/lib/runner.js:47:42)
at Builder.Target.then (/app/node_modules/knex/lib/interface.js:39:43)
at testPg (/app/api/controllers/hello_world.js:27:44)
at swaggerRouter (/app/node_modules/swagger-tools/middleware/swagger-router.js:407:20)
at swagger_router (/app/node_modules/swagger-node-runner/fittings/swagger_router.js:31:5)
at Runner.<anonymous> (/app/node_modules/bagpipes/lib/bagpipes.js:171:7)
at bound (domain.js:301:14)
at Runner.runBound (domain.js:314:12)
at Runner.pipeline (/app/node_modules/pipeworks/pipeworks.js:72:17)
at Runner.flow (/app/node_modules/pipeworks/pipeworks.js:223:19)
at Pipeworks.flow (/app/node_modules/pipeworks/pipeworks.js:135:17)
at Pipeworks.siphon (/app/node_modules/pipeworks/pipeworks.js:186:19)
at Runner.<anonymous> (/app/node_modules/bagpipes/lib/bagpipes.js:98:22)
at bound (domain.js:301:14)
0 passing (2s)

The heroku pg:psql command should connect to your database. You can also pass it parameters to connect to alternative/backup databases.

If you are using a heroku postgres url then one thing you need for external access is the query string ?ssl=true appended to the url
e.g.
"DATABASE_URL" : "postgres://user:pass#ec2-54-235-206-118.compute-1.amazonaws.com:5432/dbid?ssl=true"

I manage to solve this problem using the heroku in-dyno database (https://devcenter.heroku.com/articles/heroku-ci-in-dyno-databases). Once i got the database I go to a endpoint in my dev env that i made myself that gives me a dump file of the schemas of my real db. In the test env i import this file and voila i have all the schemas and tables i need for my test envoirment.

Related

How to deploy Next JS App with Mongoose(MongoDB) connection on Vercel?

I am facing issue while deploying my next js app on vercel with mongodb connection. I have added env variable also on vercel site where we deploy next js app. Is there something going wrong in the below file ?
next.config.js
module.exports = {
env: {
MONGODB_URI: "mongodb://localhost/tasksdb",
},
};
I have add env variable as well into my next js project
.env.local
MONGODB_URI = "mongodb://localhost/tasksdb"
I establish this mongodb connection from this doc https://mongoosejs.com/. It's provide us to connect with mongodb straightaway .
And this my mongodb connection establish code
import { connect, connection } from "mongoose";
const conn = {
isConnected: false,
};
export async function dbConnect() {
if (conn.isConected) return;
const db = await connect(process.env.MONGODB_URI);
conn.isConnected = db.connections[0].readyState;
// console.log(conn.isConnected);
// console.log(db.connection.db.databaseName)
}
connection.on("connected", () => {
console.log("Mongodb connected to db");
});
connection.on("error", (err) => {
console.error("Mongodb connected to", err.message);
});
Is there something wrong by creating the database this way because in local everything working fine ?
I don't think vercel's servers can comunicate with your localhost. You can try hosting your database in the mongodb cloud
The code seems to be fine, but you can not connect to Vercel using localhost. You can use Serverless Atlas version of MongoDB which is free you can host your database there and then connect using the link they will provide.
See : https://www.mongodb.com/pricing

SCRAM-SERVER-FIRST-MESSAGE: client password must be a string

Ive read documentation from several pages on SO of this issue, but i havent been able to fix my issue with this particular error.
throw new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string')
^
Error: SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string
at Object.continueSession (C:\Users\CNFis\Desktop\WulfDevelopments\ThePantry\node_modules\pg\lib\sasl.js:24:11)
at Client._handleAuthSASLContinue (C:\Users\CNFis\Desktop\WulfDevelopments\ThePantry\node_modules\pg\lib\client.js:257:10)
at Connection.emit (events.js:400:28)
at C:\Users\CNFis\Desktop\WulfDevelopments\ThePantry\node_modules\pg\lib\connection.js:114:12
at Parser.parse (C:\Users\CNFis\Desktop\WulfDevelopments\ThePantry\node_modules\pg-protocol\dist\parser.js:40:17)
at Socket.<anonymous> (C:\Users\CNFis\Desktop\WulfDevelopments\ThePantry\node_modules\pg-protocol\dist\index.js:11:42)
at Socket.emit (events.js:400:28)
at addChunk (internal/streams/readable.js:290:12)
at readableAddChunk (internal/streams/readable.js:265:9)
at Socket.Readable.push (internal/streams/readable.js:204:10)
its as if in my connectDB() function its not recognizing the password to the database. I am trying to run a seeder.js script to seed the database with useful information for testing purposes, and if i run npm run server which is a script that just starts a nodemon server, itll connect to the DB just fine. but when i try to run my script to seed data, i am returning this error.
import { Sequelize } from "sequelize";
import colors from "colors";
import dotenv from "dotenv";
dotenv.config();
const user = "postgres";
const host = "localhost";
const database = "thePantry";
const port = "5432";
const connectDB = async () => {
const sequelize = new Sequelize(database, user, process.env.DBPASS, {
host,
port,
dialect: "postgres",
logging: false,
});
try {
await sequelize.authenticate();
console.log("Connection has been established successfully.".bgGreen.black);
} catch (error) {
console.error("Unable to connect to the database:".bgRed.black, error);
}
};
export default connectDB;
above is my connectDB() file, and again, it works when i run the server normally. but i receive this error only when trying to seed the database. Ill post my seeder script below:
import dotenv from "dotenv";
import colors from "colors";
import users from "./data/users.js";
import User from "./models/userModel.js";
import connectDB from "./config/db.js";
dotenv.config();
console.log(process.env.DBPASS);
connectDB();
const importData = async () => {
try {
await User.drop();
await User.sync();
await User.bulkCreate(users);
console.log("Data Imported".green.inverse);
process.exit();
} catch (e) {
console.error(`${e}`.red.inverse);
process.exit(1);
}
};
const destroyData = async () => {
try {
await User.bulkDestroy();
console.log("Data Destroyed".red.inverse);
process.exit();
} catch (e) {
console.error(`${e}`.red.inverse);
process.exit(1);
}
};
if (process.argv[2] === "-d") {
destroyData();
} else {
importData();
}
Add your .env file in your project, I think your .env file is missing in your project folder.
add like this:
So, i may have figured this out by playing around in another project with sequelize, as it turns out, the initial connection to the database in my server.js file, honestly means nothing. Unlike Mongoose where the connection is available across the whole app. its not the same for Sequelize this connection that it creates is only apparent in certain places, for example i was trying the same process in my other project as i am here, except i was trying to read data from my DB using the model that i built with sequelize and i was receiving the same type error, i went into where i defined the model and made a sequelize connection there, and i was then able to read from the database using that object model.
Long story short, to fix the error in this app i have to place a connection to the database in the seeder.js file or i have to place a connection in the User model (this is ideal since ill be using the model in various places) to be able to seed information or read information from the database.
today i have same problem like this, so if you use database with type relational. you must define password from database.
const user = "postgres";
const host = "localhost";
const database = "thePantry";
const password = "yourdatabasepassword"; if null > const password = "";
const port = "5432";
but, if you use database with type non-relational, as long as the attributes are the same, you can immediately run the program as you defined it
I also faced this issue and another solution different from the accepted solution here solved my issue, so I wanted to explain that to this lovely community, too.
Firstly, when I faced the issue, ran my project in debug mode and reached the code below.
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
The problem here is actually obvious when I saw first, there is a problem in .env file as mentioned in the solutions above. In my process.env is defined as like as following line: DATABASE_URL=postgres://username:password#IP_adress:port/db_name and my config.js file is in the following format:
module.exports = {
"development": {
"url":"postgres://username:password#IP_adress:port/db_name",
"dialect": "postgres",
}, ...
}
So as a solution, I come with the following fix for the parameters that are inside Sequelize(...). My solution below is totally worked for me and I hope it also works for you too.
let sequelize;
if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.url, config);
}
Finally, the point you need to be careful about what you have written to the config file. That's the most important in this case.
Farewell y'all.
Here is my case. I have postgresql connection url in my enviroment like:
POSTGRES=postgres://postgres:test#localhost:5432/default
But my config getting like:
POSTGRES_DB_HOST=localhost
POSTGRES_DB_PORT=5432
...rest of configs
Now it has resolved.
I faced this issue because I was trying to execute nodemon from a parent folder. Once I changed my pwd, the error was resolved.
For your seeder script, i'm doing something similar but not using Sequilize, just the node-postgres package in an ExpressJS app.
To give context (so you know if this applies to your situation)
I run a separate script for testing, which uses database credentials to test batched emailing. So, I need to access my database (eventually will migrate it to an AWS lambda function).
I need to access my database and run sequential actions, since I'm not spinning up my server, all that 'under the hood' processes that would normally start your connection pool is probably not running. My guess ( I know it's an old post but this may help others).
Try passing your hardcoded password credentials. first on your seeder.js file. (i'm sure you've tried this already).
Try creating a new Pool within your seeder script and pass it your credentials (try hard coding it first to see if it works).
Pool in postgres takes a client config with the following properties (i use this to get mine to work).
const pool = new Pool({
user: '****',
database: '****',
password: '****',
port: 5432,
host: '****',
max: 5,
idleTimeoutMillis: 30000,
connectionTimeoutMillis: 5000,
})
I imagine sequilize will have a similar configuration, so try playing around with that.
Then I just connect to the pool and do everything I'd normally do.
Hope this helps with a bit of the troubleshooting. I had the EXACT same error message earlier. Ultimately I had to restructure my code to 'boot up' the Client/Connection Pool for the database. It sounds like you're not properly 'booting up' your connection so try doing it manually within your seeder script (don't pass process.env.DB_PASSWORD at first).
I saw this error when running a npx sequelize-cli db:... command
and my postgres server wasn't running or able to accept connections.
To fix it, I had to be running: postgres -D /usr/local/var/postgres in the background.

Cannot connect to AWS EC2 using AWS-sdk

I am using aws-sdk with node.js and I am not able to establish a connection to aws ec2 to obtain instance details using the sdk.
This is the error:
Error Error: connect ENETUNREACH
at Object.exports._errnoException (util.js:1020:11)
at exports._exceptionWithHostPort (util.js:1043:20)
at TCPConnectWrap.afterConnect [as oncomplete] (net.js:1086:14)
And this is the piece of code I have written:
I have removed the access keys for security purpose.
var express = require("express");
var mysql = require('mysql');
var connection = mysql.createConnection({
host: 'localhost',
user: '',
password: '',
database: ''
});
var app = express();
// Load the SDK for JavaScript
var AWS = require('aws-sdk');
// Set the region
AWS.config.update({
region: 'us-east-1'
});
var AWS_ACCESS_KEY_ID = '';
var AWS_SECRET_ACCESS_KEY = '';
var params = {
DryRun: false
};
ec2 = new AWS.EC2({
apiVersion: '2016-11-15'
});
ec2.describeInstances(params, function(err, data) {
if (err) {
console.log("Error", err.stack);
} else {
console.log("Success", JSON.stringify(data));
res.send({
message: data
});
}
});
app.listen(443);
console.log("The node server is running at port 443");
Is there a way to fix this? I am using aws-sdk for the first time. Thanks in advance.
Probably you're not passing the API keys.
var AWS_ACCESS_KEY_ID = '';
var AWS_SECRET_ACCESS_KEY = '';
var params = {
DryRun: false
};
ec2 = new AWS.EC2({
accessKeyId: AWS_ACCESS_KEY_ID,
secretAccessKey: AWS_SECRET_ACCESS_KEY,
apiVersion: '2016-11-15'
});
Recommendation:
Put your API keys in separated locations.
If this code will be hosted within an EC2, use Service role permissions for EC2.
Use profiles.
The credentials seems to be the issue here. Please double check the credentials you are providing for connecting to EC2. The best option would be to generate a new key_id and secret_access_key and use that.
I would personally recommend to download the credentials file and pass that in your code rather than putting key_id and secret_access_key here.
Is Your Computer or Node.js connect to internet? You control this.
first open cmd an use ping, if the ping return packet proper. Control internet of node.js. For control use requestify module for this. use this code:
const requi=require('requestify');
requi.get("https://google.com")
.then(function(data){
console.log(data);
})
.catch(function (err) {
console.log(err);
});
The easiest way to ensure you're doing this properly is to follow the suggested credential management described in AWS SDK For NodeJs.
npm install aws-sdk
Create a credentials file at ~/.aws/credentials on Mac/Linux or C:\Users\USERNAME.aws\credentials on Windows
[default]
aws_access_key_id = your_access_key
aws_secret_access_key = your_secret_key
And then have the AWS object manage the credentials for you:
var AWS = require('aws-sdk');
It looks like you might be almost there; instead of storing your keys in your code, store them in the specified credentials file above, and try again.

Express.js cannot connect to mongodb

Im on OS x. Im running an express.js app. This is what I have in app.js:
var express = require('express');
var mongoose = require('mongoose');
var cn = 'mongodb://localhost/test';
mongoose.connect(cn, function(error) {
console.log("inside?");
console.log(res);
});
console.log("outside");
If I open a terminal a write:
mongo
then I see this:
MongoDB shell version v3.4.3
connecting to: mongodb://127.0.0.1:27017
MongoDB server version: 3.4.3
Server has startup warnings:
2017-04-13T16:25:17.440+0200 I CONTROL [initandlisten]
2017-04-13T16:25:17.440+0200 I CONTROL [initandlisten] ** WARNING: Access control is not enabled for the database.
2017-04-13T16:25:17.440+0200 I CONTROL [initandlisten] ** Read and write access to data and configuration is unrestricted.
2017-04-13T16:25:17.440+0200 I CONTROL [initandlisten]
> show dbs
admin 0.000GB
local 0.000GB
test 0.000GB
When I run
node app.js
The only thing I see in the terminal is:
outside
So it never goes inside "connect"? I have a callback because I realized that when I tried to communicate with database the code hangs up. I dont get any error message but it seems I never can query mongodb from express. What is wrong? I have tried several different connection string, for example 127.0.0.1 or even 127.0.0.1:27017 but no luck.
nothing wrong your code, you will get reponse after outside because node.js is not blocking the next code execution, once callback return the value you will get the output. its working for me.
var express = require('express');
var mongoose = require('mongoose');
var cn = 'mongodb://localhost/test';
mongoose.connect(cn, function(error) {
console.log("inside?");
console.log(error);
});
console.log("outside");
output console:
outside
inside?
undefined
Using 'async' or putting the connection initialization part inside a promise will make sure that the execution gets blocked till the connection has been made.
await mongoose.connect(cn, function(error) {
console.log("inside?");
console.log(res);
});
If you're using await make sure the function has the async keyword.
Using a promise:
return new Promise((resolve, reject) => {
mongoose.connection.on('open', () => {
debug('Connection successfully made');
resolve();
});
mongoose.connection.on('error', () => {
debug('Error occurred');
reject();
});
});

node.js application - how to connect to mongodb and "share" connection via an include?

Background Information
I'm attempting my first node.js API/application. As a learning exercise, I'm trying to create some test cases initially delete all records in a table, insert 3 specific records, and then query for those 3 records.
Code
Here's the code I have cobbled together:
http://pastebin.com/duQQu3fm
Problem
As you can see from the code, I'm trying to put the database connection logic in a dbSession.js file and pass it around.
I am able to start up the http server by doing the following:
dev#devbox:~/nimble_node$ sudo nodejs src/backend/index.js
Server started and listening on port: 8080
Database connection successful
However, when I try to run my jasmine tests, it fails with the following error:
F
Failures:
1) The API should respond to a GET request at /api/widgets/
Message:
TypeError: Object #<MongoClient> has no method 'collection'
Stacktrace:
TypeError: Object #<MongoClient> has no method 'collection'
at resetDatabase (/home/dev/nimble_node/spec/resetDatabase.js:6:29)
at /home/dev/nimble_node/spec/e2e/apiSpec.js:23:25
at /home/dev/nimble_node/node_modules/async/lib/async.js:683:13
at iterate (/home/dev/nimble_node/node_modules/async/lib/async.js:260:13)
at async.forEachOfSeries.async.eachOfSeries (/home/dev/nimble_node/node_modules/async/lib/async.js:279:9)
at _parallel (/home/dev/nimble_node/node_modules/async/lib/async.js:682:9)
at Object.async.series (/home/dev/nimble_node/node_modules/async/lib/async.js:704:9)
at null.<anonymous> (/home/dev/nimble_node/spec/e2e/apiSpec.js:19:9)
at null.<anonymous> (/home/dev/nimble_node/node_modules/jasmine-node/lib/jasmine-node/async-callback.js:45:37)
Finished in 0.01 seconds
1 test, 1 assertion, 1 failure, 0 skipped
Database connection successful
Line 6 of resetDatabase is:
var collection = dbSession.collection('widgets');
Given that after the error appears, I get the "Database connection successful" message, I think what's happening is that when the tests request the dbSession library, the database hasn't finished running the code to connect. And therefore, I can't get the collection object.
I'm currently reading through the mongodb online manual to see if I can find some hints as to how to do something like this.
Any suggestions or pointers would be appreciated.
EDIT 1
To prove that there is a collection method on the MongoClient object, I changed the dbSession.js code to look like this:
'use strict';
var DBWrapper = require('mongodb').MongoClient;
var dbWrapper = new DBWrapper;
dbWrapper.connect("mongodb://localhost:27017/test", function(err, db) {
if (!err) {
console.log("Database connection successful");
dbWrapper = db;
var collection = dbWrapper.collection('widgets');
console.log('just created a collection...');
}
});
module.exports = dbWrapper;
And now, when I start up the http server (index.js), notice the messages:
dev#devbox:~/nimble_node$ sudo nodejs src/backend/index.js
Server started and listening on port: 8080
Database connection successful
just created a collection...
It could be an async issue.
Your code in dbSessionjs
dbWrapper.connect("mongodb://localhost:27017/test", function(err, db) {
if (!err) {
console.log("Database connection successful");
dbWrapper = db;
}
});
module.exports = dbWrapper;
Starts the connection at dbWrapper asynchronously, but exports dbWrapper right away, which is then imported in resetDatabase. Thus yes, the connect function may have not yet returned from the async function when you call it in resetDatabase (and is what the log suggests,as the error appears before the success log).
You could add a callback after dbWrapper.connect() returns, in order to actually only be able to use dbWrapper when the connection finished.
(With sqlite, this may not happen as it accesses the DB faster on the commandline).
This may not be your problem but looks like a candidate.
EDIT: Here's a possible example for a callback, but please take note it depends on what you need to do so there are a lot of different solutions. The key is to call a callback function when you are done initializing.
Another solution could be to simply wait, and/or poll (e.g. chcke a variable 'initialized').
'use strict';
var DBWrapper = require('mongodb').MongoClient;
var dbWrapper = new DBWrapper;
function doConnect(callback) {
console.log("Initializing DB connection...");
dbWrapper.connect("mongodb://localhost:27017/test", function(err, db) {
if (!err) {
console.log("Database connection successful");
dbWrapper = db;
var collection = dbWrapper.collection('widgets');
console.log('just created a collection...');
console.log('calling callback...');
callback(dbWrapper);
} else {
console.log("Error connectingi: " + err);
}
});
};
doConnect(function(correctDbWrapper) {
//Now you can use the wrapper
console.log("Inside callback, now consuming the dbWrapper");
dbWrapper = correctDbWrapper;
var collection = dbWrapper.collection('widgets');
});
It's interesting though I never ran into this issue, although I have generally used similar code like yours. I guess because normally I have this DB initialization right at the top, and then have to do lots of initializations on the node app, which gives the app time enough to return from the connect call....

Categories

Resources