mssql connection using strapi - node.js

A strapi API app connects and works perfectly on SQLlite. however we need it to connect to SQL Express db. the msssql module is installed through npm i mssql and the connection strings have been amended in order to connect to mssql heres the config file
/*
const fs = require( "fs" );
module.exports = ( { env } ) => ( {
defaultConnection: 'default',
connections: {
default: {
connector: 'bookshelf',
settings: {
client: 'sqlite',
filename: env( 'DATABASE_FILENAME', '.tmp/data.db' ),
},
options: {
useNullAsDefault: true,
},
},
},
} );
*/
const sql = require('mssql')
module.exports = ( { env } ) => ( {
defaultConnection: 'default',
connections: {
default: {
connector: 'mssql',
settings: {
user: "***",//process.env.DB_USER,
password: "***",//process.env.DB_PWD,
database: "***",//process.env.DB_NAME,
server: "**.**.**.**",
port: 1433,
connectionTimeOut: 150000,
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000
},
options: {
enableArithAbort: true,
encrypt: false,
trustedConnection: true
},
useNullAsDefault: true
}
}
}
})
the command lines commended out (for the code above) is the previous connection to sql lite that works.
now the error message is the following:
PS C:*Team\Q*_Team\AngularAPI\ui\molla-angular\strapi> npm start
mollastrapi#0.1.0 start
strapi start
[2022-07-29T08:05:53.028Z] debug ⛔️ Server wasn't able to start properly.
[2022-07-29T08:05:53.029Z] error TypeError: requireConnector(...) is not a function
at Object.load (C:\****Team\Q****_Team\AngularAPI\ui\molla-
angular\strapi\node_modules\strapi-database\lib\connector-registry.js:20:65)
at DatabaseManager.initialize (C:\****Team\Q****_Team\AngularAPI\ui\molla-
angular\strapi\node_modules\strapi-database\lib\database-manager.js:32:21)
at Strapi.load (C:\****Team\Q****_Team\AngularAPI\ui\molla-
angular\strapi\node_modules\strapi\lib\Strapi.js:297:19)
at async Strapi.start (C:\****Team\Q***_Team\AngularAPI\ui\molla-
angular\strapi\node_modules\strapi\lib\Strapi.js:156:9)
PS C:\****Team\Q****_Team\AngularAPI\ui\molla-angular\strapi>

Related

Node-mssql not able to connect to the server but with tedious it connects

currently i'am using tedious package to connect to the database and do operations but i would like to switch to node-mssql (seems less messy).
The problem i'm getting is connection timeout:
originalError: ConnectionError: Failed to connect to yyy:1433 in 15000ms
code: 'ETIMEOUT',
isTransient: undefined
}
My config with tedious :
const config = {
server: process.env.HOST, // update me
authentication: {
type: 'default',
options: {
userName: process.env.USER, // update me
password: process.env.PASS, // update me
},
},
options: {
// If you are on Microsoft Azure, you need encryption:
database: process.env.DB,
rowCollectionOnDone: true, // update me
},
};
My config with mssql :
const configMssql = {
user: process.env.USER,
password: process.env.PASS,
server: process.env.HOST, // update me
database: process.env.DB,
pool: {
max: 10,
min: 0,
idleTimeoutMillis: 30000,
},
options: {
encrypt: false, // for azure
trustServerCertificate: false, // change to true for local dev / self-signed certs
},
};
or
const configMssqlString = `Server=${process.env.HOST},1433;Database=${process.env.DB};User Id=${process.env.USER};Password=${process.env.PASS};Encrypt=false`;
Can't figure out whats wrong

Migration with Sequelize CLI to DigitalOcean Postgres Database Throwing SSL Error

Connecting to my my DigitalOcean database with Sequelize works fine when I'm not migrating. For example, attempting to create a new table works just fine; the code below successfully connects and creates a new table.
sequelize = new Sequelize(config.use_env_variable, config);
sequelize.authenticate().then(console.log('success')).catch((error) => console.log(error));
sequelize.define('test-table', {
test_id: {
type: Sequelize.INTEGER,
},
});
sequelize.sync();
I have a CA certificate .crt file I downloaded from DigitalOcean that I'm passing in with the Sequelize options. My config.js looks like
development: {
use_env_variable: 'postgresql://[digitalocean_host_url]?sslmode=require',
ssl: true,
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false,
ca: fs.readFileSync(`${__dirname}/../.postgresql/root.crt`),
},
},
},
However when I try to create tables using migrations with
npx sequelize-cli db:migrate
I receive the following output and error:
Parsed url postgresql://[digitalocean_host_url]?sslmode=require
ERROR: no pg_hba.conf entry for host [host], user [user], database [database], SSL off
Which is very strange, because SSL is working when I create a table using just Sequelize sync. I have a .sequelizerc file for the sequelize-cli configurations, which looks like this:
const path = require('path');
const env = process.env.NODE_ENV || 'development'
const config = require('./config/config')[env];
module.exports = {
'config': path.resolve('config', 'config.js'),
'url': config.use_env_variable,
'options-path': path.resolve('config', 'sql-options.json')
}
inside my sql-options.json I have the following
{
"use_env_variable": "postgresql://[digitalocean_host_url]?sslmode=require",
"dialect":"postgres",
"ssl": true,
"dialectOptions": {
"ssl": {
"required": true,
"rejectUnauthorized": true,
"ca": "/../.postgresql/root.crt"
}
}
}
I've tried a lot of the advice from various resources, including the sequelize/cli repo. But none of it seems to work. Any advice would be helpful.
I had the same issue and the fix was to add the code below in the migrations config file even though you already have it in the database connection file.
The following code is in the config/config.js file for migrations.
production: {
username: ****,
password: ****,
database: ****,
host: ****,
dialect: ****,
port: ****,
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false,
},
},
},
This is how my DB connection looks like that was working normally.
const sequelize = new Sequelize({
host: ****,
database: ****,
username: ****,
password: ****,
dialect: ****,
port: ****,
dialectOptions: {
ssl: {
require: true,
rejectUnauthorized: false,
},
},
});

cannot migrate my knex migration table to postgres on heroku

I'm following a tutorial on youtube that uses node express knex and sqlite locally and postgres on heroku. I managed to get everything working locally with sqlite and have managed to load the app on heroku. I get the initial home message. I manged to create a blank postgres database on heroku and can look at the database credentials on heroku. I need to migrate my knex tables to the heroku postgres database. According to the video below I need to use this instruction
heroku run knex migrate:latest -a node-knex1
Which gives me the following error
Running knex migrate:latest on ⬢ node-knex1... up, run.3492 (Free)
Using environment: production
error: no pg_hba.conf entry for host "54.76.162.141", user "vnujkqszmxsboi", database "def52ulvb1tjg9", SSL off
at Parser.parseErrorMessage (/app/node_modules/pg-protocol/dist/parser.js:278:15)
at Parser.handlePacket (/app/node_modules/pg-protocol/dist/parser.js:126:29)
at Parser.parse (/app/node_modules/pg-protocol/dist/parser.js:39:38)
at Socket.<anonymous> (/app/node_modules/pg-protocol/dist/index.js:10:42)
at Socket.emit (events.js:315:20)
at addChunk (internal/streams/readable.js:309:12)
at readableAddChunk (internal/streams/readable.js:284:9)
at Socket.Readable.push (internal/streams/readable.js:223:10)
at TCP.onStreamRead (internal/stream_base_commons.js:188:23)
my knexfile.js looks like the following.
module.exports = {
development: {
client: 'sqlite3',
connection: {
filename: './data/lessons.db3',
},
useNullAsDefault: true,
pool: {
afterCreate: (conn, done) => {
conn.run('PRAGMA foreign_keys = ON', done);
},
},
},
production: {
client: 'pg',
connection: process.env.DATABASE_URL,
pool: {
min: 2,
max: 10,
},
migrations: {
tablename: 'knex-migrations',
directory: './migrations',
},
},
};
[Node Express Tutorial 18 - Setting up a Postgres database in
Heroku][1]
[1]: https://www.youtube.com/watch?v=OZQWfW3VvhE&list=PLKii3VqdFnoZY6EBxb2K37D0wrEmS-5RD&index=17
I found I could overcome my problem by changing the knexfile.js to something close to what is in the heroku documentation.
module.exports = {
development: {
client: 'sqlite3',
connection: {
filename: './data/lessons.db3',
},
useNullAsDefault: true,
pool: {
afterCreate: (conn, done) => {
conn.run('PRAGMA foreign_keys = ON', done);
},
},
},
production: {
client: 'pg',
connection: {
connectionString: process.env.DATABASE_URL,
ssl: { rejectUnauthorized: false },
},
migrations: {
directory: __dirname + '/migrations',
},
seeds: {
directory: __dirname + '/seeds',
},
},
};

Why I can't send an api request to database on heroku?

I have an app built with react, redux, node, and postgresql(knex), and I could deploy this app to heroku. However, all the api requests to database made in an app does not work. It is not fetching any data or I can not sign up.
In the app, I get a console error like this:
Failed to load resource: the server responded with a status of 503 (Service Unavailable)
Uncaught (in promise) Error: Request failed with status code 503(…)
...
Is there a way to fix this?
My knex configuration:
module.exports = {
development: {
client: 'postgresql',
connection: {
database: 'database5',
user: 'user',
password: ''
},
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'knex_migrations'
}
},
staging: {
client: 'postgresql',
connection: {
database: 'my_db',
user: 'username',
password: 'password'
},
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'knex_migrations'
}
},
production: {
client: 'postgresql',
connection: process.env.DATABASE_URL,
pool: {
min: 2,
max: 10
},
migrations: {
tableName: 'knex_migrations'
}
}
};
Error in heroku logs:
2016-10-25T13:06:04.647342+00:00 app[web.1]: Unhandled rejection Error: connect ECONNREFUSED 127.0.0.1:5432
2016-10-25T13:06:04.647361+00:00 app[web.1]: at Object.exports._errnoException (util.js:893:11)
2016-10-25T13:06:04.647362+00:00 app[web.1]: at exports._exceptionWithHostPort (util.js:916:20)

How do I configure grunt-connect-proxy with grunt serve?

I managed to configure grunt to serve my application, but since it serves on localhost:9000, my api calls also go to port 9000 while my api is at port 3000, resulting in a 404 error.
After some research, I've decided I need to use grunt-connect-proxy to proxy my api calls to the right port. I've been beating my head against a wall going through every article, stack overflow question and the documentation, but I can't seem to get the configuration right. See my gruntfile below. Any help will have my undying gratitude.
// Invoke 'strict' JavaScript mode
'use strict';
module.exports = function(grunt) {
require('matchdep').filterDev('grunt-*').forEach(grunt.loadNpmTasks);
grunt.initConfig({
less: {
development: {
options: {
compress: true,
yuicompress: true,
optimization: 2,
paths: ['public/styles/less']
},
files: {
"public/styles/css/main.css": "public/styles/less/main.less" // destination file and source file
}
}
},
watch: {
styles: {
files: ['public/styles/less/*.less'],
tasks: ['less'],
options: {
nospawn: true
}
}
},
connect: {
server: {
options: {
port: 8000,
base: 'public',
logger: 'dev',
hostname: 'localhost',
middleware: function (connect, options, defaultMiddleware) {
var proxy = require('grunt-connect-proxy/lib/utils').proxyRequest;
return [
// Include the proxy first
proxy
].concat(defaultMiddleware);
}
},
proxies: [
{
context: '/',
host: '127.0.0.1',
port: 3000,
https: false,
xforward: false,
headers: {
"x-custom-added-header": 'value'
},
hideHeaders: ['x-removed-header']
}
]
},
serve: {
options:{
port: 9000,
hostname: "127.0.0.1",
middleware: function(connect, options) {
return [
require('grunt-contrib-livereload/lib/utils').livereloadSnippet,
connect.static(options.base[0])
];
}
}
}
},
open: {
serve: {
path: 'http://localhost:<%= connect.serve.options.port%>/public'
}
},
regarde: {
serve: {
files:['public/index.html','public/script/*.js','public/script/**/*.js','public/styles/**/*.css','public/styles/less/*.less','public/views/*.html'],
tasks: ['livereload']
}
}
});
grunt.loadNpmTasks('grunt-contrib-watch');
grunt.loadNpmTasks('grunt-contrib-less');
//grunt.loadNpmTasks('grunt-contrib-clean');
//grunt.loadNpmTasks('grunt-contrib-compass');
grunt.loadNpmTasks('grunt-connect-proxy');
grunt.registerTask('serve',['less','livereload-start','connect:serve','open:serve','regarde:serve']);
grunt.registerTask('server', function (target) {
grunt.task.run([
//'clean:server',
//'compass:server',
'configureProxies:server',
'connect:server',
'watch'
]);
});
};

Resources