I am trying to deploy my backend to Heroku. I've pushed the app to heroku and it is supposedly working. I'm trying to run typeorm:migration:run however I get error during migration run:
error: no pg_hba.conf entry for host "3.90.xx.xxx", user "blahblahblah", database "blahblah", SSL off
my app.module.ts code includes the following:
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: (configService: ConfigService) => ({
type: 'postgres',
url: configService.get('DATABASE_URL'),
ssl: {
required: true,
rejectUnauthorized: false,
},
entities: ['dist/**/*.entity.js'],
synchronize: false,
}),
}),
I don't understand why the connection error says "SSL off." I'm quite inexperienced with all of this, so I may be missing something completely obvious.
Thank you for any help.
You have to create env variables like this: PGSSLMODE=no-verify
Related
I am Registering my SQL-server in app.module.ts as follows:
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'mssql',
host: configService.get('HOST'),
port: 1434,
username: configService.get('USERNAME'),
database: 'testdatabase',
password: configService.get('PASSWORD'),
name: 'myDatabase',
entities: [],
}),
inject: [ConfigService],
}),
In some other service I am Injecting the Database connection as follows:
constructor(
#InjectConnection("myDatabase") private readonly connection: Connection,
) { }
ThisService is inside a Module which is Imported in app.module.ts
If I register the TypeOrm Module without the async (just TypeOrmModule.forRoot()), and don't use config.service I can access the connection, but since I wanna use ConficService it registers the SQL-Server asynchronously. The connection doesn't exist yet when I inject it throwing the error:
Nest can't resolve dependencies
of the UsersService (?). Please make sure that the argument myDatabaseConnection at index [0] is available in the UsersModule context.
I use the injected connection to run SQL-Queries on it.
How can I make this work?
If you use name in the #InjectConnection(), then name also needs to be at the same level as imports and useFactory as well as inside the options. There's two things keeping track of the name here, Nest, which needs it for the injection tokens, and TypeORM, which needs it for the metadata storage.
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'mssql',
host: configService.get('HOST'),
port: 1434,
username: configService.get('USERNAME'),
database: 'testdatabase',
password: configService.get('PASSWORD'),
name: 'myDatabase',
entities: [],
}),
inject: [ConfigService],
name: 'myDatabase',
}),
After trying to create migrations, migration file adding in root folder, how can I add file in src/migration folder?
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
inject: [ConfigService],
useFactory: async (config: ConfigService) => ({
type: config.get<'aurora-postgres'>('TYPEORM_CONNECTION'),
username: config.get<string>('TYPEORM_USERNAME'),
password: config.get<string>('TYPEORM_PASSWORD'),
database: config.get<string>('TYPEORM_DATABASE'),
port: config.get<number>('TYPEORM_PORT'),
entities: ['../src/entities/**/*.ts'],
migrations: ['../src/migrations/**/*.ts'],
cli: {
entitiesDir: '/src/entities',
migrationsDir: '/src/migrations',
},
synchronize: false,
autoLoadEntities: true,
logging: true,
}),
})
package.json:
{
"migration:create": "ts-node --transpile-only ./node_modules/typeorm/cli.js migration:create"
}
The configuration passed to TypeOrmModule.forRoot() is not read by the typeormCLI. I would suggest creating a orm config file that's specific for the CLI, something liketypeorm-cli.config.js` and reference it when using the TypeORM CLI
i have a problem with connecting to database in nest.js with typeorm and postgres.
I created a .env file in the root project directory with the following content
POSTGRES_HOST=127.0.0.1
POSTGRES_PORT=5432
POSTGRES_USER=postgres
POSTGRES_PASSWORD=password
POSTGRES_DATABASE=db-name
In the app.module.ts I writed the code below:
import { Module } from '#nestjs/common';
import { ConfigModule } from '#nestjs/config';
import { TypeOrmModule } from '#nestjs/typeorm';
import { FeedModule } from './feed/feed.module';
#Module({
imports: [
ConfigModule.forRoot({ isGlobal: true }),
TypeOrmModule.forRoot({
type: 'postgres',
host: process.env.POSTGRES_HOST,
port: parseInt(<string>process.env.POSTGRES_PORT),
username: process.env.POSTGRES_USER,
password: process.env.POSTGRES_PASSWORD,
database: process.env.POSTGRES_DATABASE,
autoLoadEntities: true,
synchronize: true,
}),
FeedModule,
],
})
export class AppModule {}
But when im running the app by npm start it throws this error: new Error('SASL: SCRAM-SERVER-FIRST-MESSAGE: client password must be a string')
What am I missing or doing wrong?
In NestJs you should use ConfigService to get environment variables inside your typeorm module, read the docs for more information.
You can use it like that:
import { ConfigModule, ConfigService } from '#nestjs/config';
import { Module } from '#nestjs/common';
import { TypeOrmModule } from '#nestjs/typeorm';
#Module({
imports: [
ConfigModule.forRoot(
envFilePath: `.${process.env.NODE_ENV}.env`
),
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
injects: [ConfigService],
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get("POSTGRES_HOST"),
port: configService.get("POSTGRES_PORT"),
username: configService.get("POSTGRES_USER"),
password: configService.get("POSTGRES_PASSWORD"),
database: configService.get("POSTGRES_DB"),
entities: [],
synchronize: true,
}),
}),
],
controllers: [],
providers: [],
})
export class AppModule {}
As explained in the docs, you can define a factory function where you inject the config-service allowing you to resolve the corresponding values:
TypeOrmModule.forRootAsync({
imports: [ConfigModule],
useFactory: (configService: ConfigService) => ({
type: 'postgres',
host: configService.get('POSTGRES_HOST'),
port: +configService.get<number>('POSTGRES_PORT'),
username: configService.get('POSTGRES_USER'),
password: configService.get('POSTGRES_PASSWORD'),
database: configService.get('POSTGRES_DATABASE'),
synchronize: true,
autoLoadEntities: true,
}),
inject: [ConfigService],
});
I was able to fix the problem by using the config module.
Just do npm i #nestjs/config. Then in the imports array just above the TypeOrmModule put ConfigModule.forRoot({ isGlobal: true }),. This allows your module to get the environment variables from the .env file
I got this error because I put the .env file inside the src by mistake. If you put it outside of the src it will fix it
I was facing the same issue and it was weird because I modified several times that configuration just to check if "something new happens" but have no success.
Long story short, I deleted the "dist" folder of the project and build the app again (npm run build) and it worked! It appeared that I had a "bad build" running over and over again so this workaround kind of "refreshed" the build and let things running well again.
Hope this help!
Cannot able to connect database with correct connection info, followed documentation to connect database from https://docs.nestjs.com/techniques/database
Database connected on SQLYog
Following same database information in app.module.ts
#Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
port: 3306,
username: 'root',
password: null,
database: 'the_local_db',
entities: [
Table_one,
],
// entities: ['../typeorm/entities/*.ts'],
synchronize: true,
}),
StaffModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
Error Details
`[Nest] 5528 - 06/30/2020, 1:39:51 AM [ExceptionHandler] ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''"'' at line 1 +18m
QueryFailedError: ER_PARSE_ERROR: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near ''"'' at line 1
at new QueryFailedError (C:\Users\UserName\ProjectName\nrwl\src\error\QueryFailedError.ts:9:9)
at Query. (C:\Users\UserName\ProjectName\nrwl\src\driver\mysql\MysqlQueryRunner.ts:167:37)
at Query. (C:\Users\UserName\ProjectName\nrwl\node_modules\mysql\lib\Connection.js:526:10)
at Query._callback (C:\Users\UserName\ProjectName\nrwl\node_modules\mysql\lib\Connection.js:488:16)
at Query.Sequence.end (C:\Users\UserName\ProjectName\nrwl\node_modules\mysql\lib\protocol\sequences\Sequence.js:83:24)
at Query.ErrorPacket (C:\Users\UserName\ProjectName\nrwl\node_modules\mysql\lib\protocol\sequences\Query.js:92:8)
at Protocol._parsePacket (C:\Users\UserName\ProjectName\nrwl\node_modules\mysql\lib\protocol\Protocol.js:291:23)
at Parser._parsePacket (C:\Users\UserName\ProjectName\nrwl\node_modules\mysql\lib\protocol\Parser.js:433:10)
at Parser.write (C:\Users\UserName\ProjectName\nrwl\node_modules\mysql\lib\protocol\Parser.js:43:10)
at Protocol.write (C:\Users\UserName\ProjectName\nrwl\node_modules\mysql\lib\protocol\Protocol.js:38:16)`
Check if you have synchronize connection option set to true in database configuration. Make it to false.
It worked for me.
I was faced with a similar issue and the verified response did not help me. I was able to solve my issue using the mysql2 module instead of mysql.
$ npm install mysql2 --save
I also had to uninstall mysql module to connect to my database
$ npm uninstall mysql --save
Hope this response helped others with stuck in the same issue.
I have just removed the port:3306, now it's working.
#Module({
imports: [
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
username: 'root',
password: null,
database: 'the_local_db',
entities: [
Table_one,
],
// entities: ['../typeorm/entities/*.ts'],
synchronize: true,
}),
StaffModule,
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
In my case the solution was some different because my localhost had a different name,it happened in OSX sometimes,so I changed the "localhost" by the ip adress 127.0.0.1
TypeOrmModule.forRoot({
type: 'mysql',
host: '127.0.0.1',
port: 3306,
username: 'test',
password: '123456',
database: 'nest',
entities: ["dist/**/*.entity{.ts,.js}"],
synchronize: true,
dropSchema:true })
First, i solved my problem by using as following:
1/ synchronize :false in the app.module
2/nmp uninstall mysql
3/npm install mysql2
--> when i run >>npm run start:dev everything is ok
I solved this issue by using a connection URL instead of splitting the MongoDB URI.
dbConfig: {
type: 'mongodb',
url: process.env.MONGO_CONNECTION_STRING,
ssl: true,
useUnifiedTopology: true,
autoLoadEntities: true,
synchronize: false,
logging: true,
}
Where MONGO_CONNECTION_STRING: mongodb://ussername:password#host_name:port/?authSource=admin
. This way one can avoid getting this error in TypeORM. Also, there is a flag useNewUrlParser: true which could be used to configure DB in a way using the host username and password separately.
did you start your XAMP mysql server on locally? because i was not (:
just reminder
I am using Nest.js to develop a web backend.
When I use npm run build, the cmd shows success.
But when I use node dist/main.js, the cmd shows error. But I'm sure this file exist and in develop mode (npm run start), everything's ok.
This is github address.
https://github.com/Eve-1995/Oreo/tree/master/oreo-back-end
What should I do next?
entities: [__dirname + '/../**/**/!(*.d).entity.{ts,js}'], is doing the trick for me both in production and dev envs.
I think the reason is in TypeOrm config.
#Module({
imports: [
AuthModule,
ClassificationModule,
ArticleModule,
UserModule,
CommentModule,
FragmentModule,
TypeOrmModule.forRoot({
type: 'mysql',
host: 'localhost',
// logging: ["query"],
port: 3306,
username: 'root',
password: '123456',
database: 'myblog',
entities: ['src/**/**.entity{.ts,.js}'], // <-- replace it to 'dist/**/**.entity.js' in prod mode or use relative path
synchronize: true,
}),
],
})
export class AppModule { }
You probably just need to add this in your tsconfig.json:
"paths": {
"src/*": ["./src/*"]
}
TS can now correctly transform the src/ alias import when building the project.