How to use postgres or SQL Server with nestjs - nestjs

I am from .net background and few days back started using nestjs for one of my project.
I love the way nestjs built but few question here.
When using .net I can easily connect .net application with database by using some ORM like Ado.net, EF etc.
How do I connect nestjs with Postgres or SQL Server database?
Whatever will be the answer I would also like to know will that be suitable for enterprise applications?
Is there any reference site?
Thanks in advance

The docs show examples of how to conenct to a database using TypeORM and Sequilize, or you can roll your own dynamic module with custom providers if you want to use something else. There are a few packages around for knex, pg-promise, and massiveORM. These should all be more than suitable for enterprise applications, but if anything shows up as an issue, make sure to notify the owners of the repository.

Here is the basic structure I created to set up my current project with NestJS and PostgreSQL just in case this helps.
I added the following packages:
$ npm install --save knex objection objection-graphql pg
Created the nest database module and added this module to the "imports" and "exports" within the app.module.ts:
./src/database/database.module.ts
Then added the following files and folders:
./src/database/migrations
./src/database/models
./src/database/base.model.ts
./src/database/user.model.ts
./src/database/seeds
./src/database/migration.stub
./src/database/seed.stub
At the root level, I placed the knexfile.ts
import 'dotenv/config';
import Knex from 'knex';
import { knexSnakeCaseMappers } from 'objection';
module.exports = {
development: {
client: 'pg',
connection: process.env.DATABASE_URL,
migrations: {
directory: './src/database/migrations',
stub: './src/database/migration.stub',
},
seeds: {
directory: './src/database/seeds',
stub: './src/database/seed.stub'
},
...knexSnakeCaseMappers()
},
production: {
client: 'pg',
connectio: process.env.DATABASE_URL,
migrations: {
directory: __dirname + '/database/migrations',
},
seeds: {
directory: __dirname + '/database/seeds/production',
},
},
} as Knex.Config;
Then for each new Module, I called the model from the database folder
import { UserModel } from '../database/models/user.model'
That's it. Here you have connected PostgreSQL with NestJS.
As others have mentioned the NestJS manual is a well written resource for a detailed reference.
RON

Related

Configuring knex database connection uisng an access key

Well I recently started using knex for my database connectivity for my nodejs project. Here's the following code:
var knex = require('knex')({
client: 'mysql',
connection: {
'host':'localhost',
'port':'3306',
'user':'root',
'password':'',
'database':'db_sample'
}
});
So what I need is, I want to add an access key as well in my Database configuration. I just wanted to know if its possible to do it. If yes, please do tell me how. Thank you

Use mongoose in an angular project

I try to integrate MongoDB in my project angular 6. I want to use the ODM Mongoose.
npm install mongoose --save
I created this service which must manage the connection with the database
import { Injectable } from '#angular/core';
import { mongoose } from 'mongoose';
#Injectable()
export class BD {
private bd;
public test: string;
constructor(mongoose: mongoose){}
Test(){
mongoose('the url of the database')
this.bd = mongoose.connection;
this.bd.on('error', console.error.bind(console, 'error: impossible connection to the database'));
this.bd.once('open', ()=>{console.log('connected to the DB :}')})
}
}
When I launch the application in my browser I have this erreur:
SCRIPT5009: 'global' is not defined
What does this error mean?
Is this how I have to import mongoose?
Thank you in advance for your help
Mongoose is a library designed specially for node.js and won't work in the browser environment. In order to be able to connect the db - you need to establish node.js back-end server, for example express.js. Then you will be able access your resources through the REST api.
Also, you cannot establish connection to the database directly, because you need somehow secure the data inside those database. When you connecting to the database directly - everyone who can take a look at your code will gain acess to the data and this is serious security problem.

change database to mongo db on sails.js

I am a newbie in sails.js framework(and for node.js) and I have created myself an API from the address bar using sails.js features. my question is how do I transfer this data to mongodb so I can see it visually.
I have tried to follow this guide: https://www.npmjs.org/package/sails-mongo
but its for 0.9 sails version(current version is 0.10) so that a lot of files that I needed to change has been modified and gone/renamed. I couldn't find an updated tutorial as well so if anyone can please write down how can I implement mongoDB to my sails project that would be wonderful.
In config/connections.js you need to configure your mongoDB connection. Then go to config/models.js, uncomment the connection property and set the name of your mongoDB connection.
In config/connection.js, You can configure your MongoDb connection like this.
module.exports.connections = {
MongoConnection: {
adapter: 'sails-mongo',
host: 'localhost',
port: 27017,
// user: 'username',
// password: 'password',
database: 'DB_Name'
}
};
You need to install sails-mongo package using npm in your working folder.
Then in config/models.js, Add the name of your mongoDb connection like this:
module.exports.models = {
connection: 'MongoConnection',
migrate: 'alter'
};
Thats it, you are ready to go.

How to deal with calling sequelize.sync() first?

I'm a bit new to developing in nodejs, so this is probably a simple problem. I'm building a typical webapp based on express + sequelize. I'm using sqlite in-memory since I'm just prototyping at the moment. I understand if I were to use a persistent sqlite file, this may not be a problem, but that's not my goal at the moment. Consider the following:
var User = sequelize.define("User", {
"username": DataTypes.STRING,
// etc, etc, etc
});
sequelize.sync();
User.build({
"username": "mykospark"
});
At first, I got an error on User.build() about the Users table not existing yet. I realized that sequelize.sync() was being called async, and the insert was happening before the table was created. I then re-arranged my code so that the User.build() call was inside of sequelize.sync().complete() which fixes the problem, but I'm not sure how to apply this to the rest of my project.
My project uses models in a bunch of different places. It is my understanding that I just want to call sequelize.sync() once after my models are defined, then they can be used freely. I could probably find some way to block the entire nodejs app until sequelize.sync() finishes, but that doesn't seem like good form. I suppose I could wrap every single model operation into a sequelize.sync().complete() call, but that doesn't seem right either.
So how do people usually deal with this?
Your .sync() call should be called once within your app.js file. However, you might have additional calls if you manage multiple databases in one server. Typically your .sync() call will be in your server file and the var User = sequelize.define("ModelName"... will be in your models/modelName.js file. Sequelize suggests this type of guidance to "create a maintainable application where the database logic is collected in the models folder". This will help you as your development grows. Later in the answer, I'll provide an easy step to follow for initializing the file structure.
So for your case, you would have app.js, models/index.js and models/users.js. Where app.js would be your server running the .sync() method. In the models folder you will have the required index.js folder where you configure a connection to the database and collect all the model definitions. Finally you have your user.js files where you add your model with class and instance methods. Below is an example of the models/user.js file you might find helpful.
user.js
module.exports = function(sequelize, DataTypes) {
return sequelize.define('User', {
username: DataTypes.STRING,
},{
classMethods: {
doSomething: function(successcb, errcb, request) {}
},
instanceMethods: {
someThingElse: function(successcb, errcb, request) {}
}
});
};
models/index.js --> See here
EDIT 03/14/17
Now the best option to setup your node app with sequelize is to use sequelize-cli. This is sequelize migrations and has very useful functionality in development and production environments. For the scope of this question and revision to the answer, the best approach is the following:
npm install sequelize-cli
Use npm install sequelize-cli -g if you want it installed globally.
Then initialize sequelize migrations:
sequelize init
It should install the following folders and files structure in the folder you initiated the command:
config:
-config.json
models:
-index.js
seeders:
migrations:
If you want to create a model you can run the following command and it will auto generate the file structure for you. Here is an example
sequelize model:create --name User --attributes "user:string email:string"
Next you should be able to see the new model page in models/page.js.
config:
-config.json
models:
-index.js
-user.js
-page.js
seeders:
migrations:
You'll need to then go into you models/index.js and define your new model for your database to access the correct path for that model. Here is an example:
models/index.js
var sq = new Sequelize(dbname, user, password, config);
db = {
Sequelize: Sequelize,
sequelize: sq,
page: sq.import(__dirname + '/page.js'),
user: sq.import(__dirname + '/user.js')
}
module.exports = db;
If you need to make changes to the model you can go into the migrations folder and add methods. Follow the sequelize migration docs here. Now, about the app.js server. Before you run your server you need to initialize your databases. I use the following script to initialize the database before running the server to setup a postgres db:
postgresInit.sh
[...]
`sudo -u postgres createdb -U postgres -O $PG_USER $PG_DB. `
If you prefer a javascript solution, there is an SO solution here
app.js
[...]
console.log('this will sync your table to your database')
console.log('and the console should read out Executing (default): CREATE TABLE IF NOT EXISTS "TABLE NAME"....')
db.sequelize.sync(function(err){});

Using sails.js with an existing postgres database

I was looking at using Sails for an app that we are developing.
I'm using the sails-postgresql adapter which uses the waterline orm.
I have an existing database that I want to connect to.
If I create a model using generate something
and then in my model I have
attributes:{
title:{type:'String'}
}
If I browse to localhost/something the orm deletes all the columns in the something table except title.
Is there a way to stop it from doing this? This app should not delete columns on this database.
Thanks!
I am the author of Sails-Postgresql. Sails has an ORM called Waterline that it uses for managing data. The default setting assumes that you would want to auto-migrate your database to match your model attributes. Because Postgresql is a SQL database the Sails-Postgresql adapter has a setting called syncable that defaults to true. This would be false in a NoSQL database like redis.
This is easy to turn off if you want to manage your database columns yourself. You can add migrate: safe to your model and it won't try and update your database schema when you start Sails.
module.exports = {
adapter: 'postgresql',
migrate: 'safe',
attributes: {
title: { type: 'string' }
}
};
Sails doesn't have anything like migrations in Rails. It uses auto-migrations to attempt to remove this from your development process and then leaves updating your production schema to you.

Resources