NestJS TypeORM syntax error in migration file - postgresql

I was going through the NestJS official docs. I set up PostgreSQL on Heroku, connected with TypeORM, run a migration and after that my app started crushing. I tried different approaches and searched blogs/issues on github/questions here, but nothing helped.
Here is an error:
[Nest] 46723 - 05/10/2020, 6:33:42 PM [InstanceLoader] TypeOrmModule dependencies initialized +84ms
[Nest] 46723 - 05/10/2020, 6:33:43 PM [TypeOrmModule] Unable to connect to the database. Retrying (1)... +493ms
/Users/Shared/diploma/be/migration/1589119433066-AddUser.ts:1
import {MigrationInterface, QueryRunner} from "typeorm";
^
SyntaxError: Unexpected token {
at Module._compile (internal/modules/cjs/loader.js:721:23)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:787:10)
at Module.load (internal/modules/cjs/loader.js:653:32)
at tryModuleLoad (internal/modules/cjs/loader.js:593:12)
at Function.Module._load (internal/modules/cjs/loader.js:585:3)
at Module.require (internal/modules/cjs/loader.js:690:17)
at require (internal/modules/cjs/helpers.js:25:18)
at Function.PlatformTools.load (/***/PROJECT_ROOT/node_modules/typeorm/platform/PlatformTools.js:114:28)
at /***/PROJECT_ROOT/node_modules/typeorm/util/DirectoryExportedClassesLoader.js:39:69
at Array.map (<anonymous>)
Here is my ormconfig.json:
"type": "postgres",
"url": "postgres://***",
"ssl": true,
"extra": {
"ssl": {
"rejectUnauthorized": false
}
},
"entities": ["dist/**/*.entity{.ts,.js}"],
"migrationsTableName": "custom_migration_table",
"migrations": ["migration/*{.ts,.js}"],
"cli": {
"migrationsDir": "migration"
}
}
migration was generated using ts-node ./node_modules/.bin/typeorm migration:generate -n AddUser
I'm using nest start --watch command to start the app.
Migration file {TIMESTAMP}-AddUser.ts:
import {MigrationInterface, QueryRunner} from "typeorm";
export class AddUser1589119433066 implements MigrationInterface {
name = 'AddUser1589119433066'
public async up(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`CREATE TABLE "users" (...)`, undefined);
}
public async down(queryRunner: QueryRunner): Promise<void> {
await queryRunner.query(`DROP TABLE "users"`, undefined);
}
}

Thanks to #Isolated!
I've changed the ormconfig.json so entities and migrations files looks like this now and it works fine for me:
"entities": ["dist/**/*.entity{.ts,.js}"],
"migrations": ["dist/migration/*{.ts,.js}"],

Related

How do I connect TypeORM to MongoDB? I receive errors while trying to connect

I have a NestJS and TypeORM project going. I am trying to connect it to my MongoDB database.
Here is the list of my MongoDB projects from the https://cloud.mongodb.com/ website:
The only name I can see for these is "cluster0" like here:
And then in my .env file I have:
MONGODB_CONNECTION_STRING=mongodb+srv://roland:<myActualPassword>#cluster0.7llne.mongodb.net/?retryWrites=true&w=majority
MONGODB_DATABASE=cluster0
and then the entrypoint to the application:
import { Module } from "#nestjs/common";
import { SchedulingController } from "./scheduling.controller";
import { SchedulingService } from "./scheduling.service";
import { ConfigModule } from "#nestjs/config";
import { TypeOrmModule } from "#nestjs/typeorm";
import { Meeting } from "./db/Meeting.entity";
#Module({
imports: [
ConfigModule.forRoot(),
TypeOrmModule.forRoot({
type: "mongodb",
url: process.env.MONGODB_CONNECTION_STRING,
database: process.env.MONGODB_DATABASE,
entities: [__dirname + "/**/*.entity{.ts,.js}"],
ssl: true,
useUnifiedTopology: true,
useNewUrlParser: true,
}),
TypeOrmModule.forFeature([Meeting]),
],
controllers: [SchedulingController],
providers: [SchedulingService],
})
export class SchedulingModule {}
But I see these errors:
[Nest] 16760 - 2022-05-16, 10:05:09 p.m. ERROR [TypeOrmModule] Unable to connect to the database. Retrying (5)...
MongoServerSelectionError: read ECONNRESET
at Timeout._onTimeout (C:\Users\jenfr\Documents\Code2022\TakeHomeTests\bluescape\bluescape\node_modules\mongodb\src\sdam\topology.ts:594:30)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
[Nest] 16760 - 2022-05-16, 10:05:42 p.m. ERROR [TypeOrmModule] Unable to connect to the database. Retrying (6)...
MongoServerSelectionError: read ECONNRESET
at Timeout._onTimeout (C:\Users\jenfr\Documents\Code2022\TakeHomeTests\bluescape\bluescape\node_modules\mongodb\src\sdam\topology.ts:594:30)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
[Nest] 16760 - 2022-05-16, 10:06:15 p.m. ERROR [TypeOrmModule] Unable to connect to the database. Retrying (7)...
MongoServerSelectionError: read ECONNRESET
at Timeout._onTimeout (C:\Users\jenfr\Documents\Code2022\TakeHomeTests\bluescape\bluescape\node_modules\mongodb\src\sdam\topology.ts:594:30)
at listOnTimeout (node:internal/timers:557:17)
at processTimers (node:internal/timers:500:7)
edit: I'm fairly certain my MONGODB_CONNECTION_STRING and MONGODB_DATABASE are set properly, anyone know what else could be causing these errors?
Try to set useUnifiedTopology=false.

Error: listen EADDRINUSE when using nodemon with babel 7

nodemon -v: 1.18.6
node -v: v11.2.0
Command: nodemon --exec babel-node lib/server.js
My app starts ok with the above command. When I change the source code, I expect the nodemon restart automatically. But I got the error Error: listen EADDRINUSE: address already in use :::3000.
Error details
[nodemon] starting `babel-node lib/server.js`
events.js:167
throw er; // Unhandled 'error' event
^
Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle [as _listen2] (net.js:1294:14)
at listenInCluster (net.js:1342:12)
at Server.listen (net.js:1429:7)
at Function.listen (/Users/longntran/Desktop/learning/pangara-web/node_modules/express/lib/application.js:618:24)
at Object.listen (/Users/longntran/Desktop/learning/pangara-web/lib/server.js:12:5)
at Module._compile (internal/modules/cjs/loader.js:722:30)
at Module._compile (/Users/longntran/Desktop/learning/pangara-web/node_modules/pirates/lib/index.js:83:24)
at Module._extensions..js (internal/modules/cjs/loader.js:733:10)
at Object.newLoader [as .js] (/Users/longntran/Desktop/learning/pangara-web/node_modules/pirates/lib/index.js:88:7)
at Module.load (internal/modules/cjs/loader.js:620:32)
Emitted 'error' event at:
at emitErrorNT (net.js:1321:8)
at internalTickCallback (internal/process/next_tick.js:72:19)
at process._tickCallback (internal/process/next_tick.js:47:5)
at Function.Module.runMain (internal/modules/cjs/loader.js:778:11)
at Object.<anonymous> (/Users/longntran/Desktop/learning/pangara-web/node_modules/#babel/node/lib/_babel-node.js:224:23)
at Module._compile (internal/modules/cjs/loader.js:722:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:733:10)
at Module.load (internal/modules/cjs/loader.js:620:32)
at tryModuleLoad (internal/modules/cjs/loader.js:560:12)
at Function.Module._load (internal/modules/cjs/loader.js:552:3)
Dependencies
"dependencies": {
"ejs": "^2.6.1",
"express": "^4.16.4",
"react": "^16.6.3",
"react-dom": "^16.6.3"
},
"devDependencies": {
"#babel/core": "^7.1.6",
"#babel/preset-env": "^7.1.6",
"#babel/preset-react": "^7.0.0",
"#babel/node": "^7.0.0",
"babel-jest": "^23.6.0",
"babel-loader": "^8.0.4",
"jest": "^23.6.0",
"nodemon": "^1.18.6",
"pm2": "^3.2.2",
"prettier": "1.15.2",
"regenerator-runtime": "^0.13.1",
"webpack": "^4.26.1",
"webpack-cli": "^3.1.2"
}
Note
I am using nodemon with babel 7. Please help me. Thank you guys
I found an interesting fix in this thread around adding a delay and kill process commands to your scripts.
"events": {
"restart": "fuser -k 5000/tcp ; fuser -k 3050/tcp" // change to whatever ports you're using.
}
And to add a delay to the nodemon command:
--delay 1500ms
https://github.com/remy/nodemon/issues/1316#issuecomment-387367160
I also noticed that if I hit save twice in my code editor in rapid succession, I get this error. However if I only hit save once, I see no problem.
I've found that completing a graceful server shutdown on any interruption allows nodemon to restart successfully (using Express):
// Run server
const PORT = process.env.PORT || 3000
const server = app.listen(PORT, () => {
console.log('[server] Started server');
});
// Graceful shutdown of server
process.on('SIGINT', () => {
console.log('\n[server] Shutting down...');
server.close();
process.exit();
});
process.on('SIGTERM', () => {
console.log('\n[server] Shutting down...');
server.close();
process.exit();
});
process.on('uncaughtException', () => {
console.log('\n[server] Shutting down...');
server.close();
process.exit();
});

Heroku Deployment Issues with Postgres and Sequelize

I am trying to deploy my app to Heroku. It works perfectly fine when run locally. From the moment I deployed it (deploying through github integration) I received the generic Application Error screen. Below are my heroku logs. These actually run three times but there was no point in me posting the same thing three times. They always end with:
2017-05-02T14:59:26.033702+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=calm-crag-40902.herokuapp.com request_id=6b64883e-9697-4d58-84d9-2f173d5b4cb1 fwd="70.
54.76.222" dyno= connect= service= status=503 bytes= protocol=https
2017-05-02T14:59:27.425435+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=calm-crag-40902.herokuapp.com request_id=d3719d8f-4670-4621-a044-a511ee6884
10 fwd="70.54.76.222" dyno= connect= service= status=503 bytes= protocol=https
This will print 2 to 4 times after each consecutive error screen. The first error is regarding the .env files not running and the second is trying to connect to sequelize. My primary focus is sorting out the .env because if that is sorted out, at least the app will show my app will be visible.
.env error:
{ Error: ENOENT: no such file or directory, open '.env'
2017-05-02T16:09:39.622865+00:00 app[web.1]: at Error (native)
2017-05-02T16:09:39.622866+00:00 app[web.1]: at Object.fs.openSync (fs.js:641:18)
2017-05-02T16:09:39.622867+00:00 app[web.1]: at Object.fs.readFileSync (fs.js:509:33)
2017-05-02T16:09:39.622867+00:00 app[web.1]: at Object.config (/app/node_modules/dotenv/lib/main.js:30:37)
2017-05-02T16:09:39.622868+00:00 app[web.1]: at Object.<anonymous> (/app/server.js:3:19)
2017-05-02T16:09:39.622869+00:00 app[web.1]: at Module._compile (module.js:570:32)
2017-05-02T16:09:39.622869+00:00 app[web.1]: at Object.Module._extensions..js (module.js:579:10)
2017-05-02T16:09:39.622870+00:00 app[web.1]: at Module.load (module.js:487:32)
2017-05-02T16:09:39.622871+00:00 app[web.1]: at tryModuleLoad (module.js:446:12)
2017-05-02T16:09:39.622871+00:00 app[web.1]: at Function.Module._load (module.js:438:3) errno: -2, code: 'ENOENT', syscall: 'open', path: '.env' }
2017-05-02T16:09:40.242885+00:00 app[web.1]: Unhandled rejection
Sequelize error:
SequelizeConnectionRefusedError: connect ECONNREFUSED 127.0.0.1:5432
2017-05-02T16:09:40.242902+00:00 app[web.1]: at /app/node_modules/sequelize/lib/dialects/postgres/connection-manager.js:98:20
2017-05-02T16:09:40.242903+00:00 app[web.1]: at Connection.<anonymous> (/app/node_modules/pg/lib/client.js:186:5)
2017-05-02T16:09:40.242904+00:00 app[web.1]: at emitOne (events.js:96:13)
2017-05-02T16:09:40.242905+00:00 app[web.1]: at Connection.emit (events.js:188:7)
2017-05-02T16:09:40.242905+00:00 app[web.1]: at Socket.<anonymous> (/app/node_modules/pg/lib/connection.js:86:10)
2017-05-02T16:09:40.242906+00:00 app[web.1]: at emitOne (events.js:96:13)
2017-05-02T16:09:40.242907+00:00 app[web.1]: at emitErrorNT (net.js:1281:8)
2017-05-02T16:09:40.242907+00:00 app[web.1]: at Socket.emit (events.js:188:7)
2017-05-02T16:09:40.242909+00:00 app[web.1]: at process._tickCallback (internal/process/next_tick.js:104:9)
2017-05-02T16:09:40.242908+00:00 app[web.1]: at _combinedTickCallback (internal/process/next_tick.js:80:11)
2017-05-02T16:09:40.360035+00:00 heroku[web.1]: Process exited with status 0
2017-05-02T16:09:40.373996+00:00 heroku[web.1]: State changed from starting to crashed
This is my index.js:
'use strict';
const fs = require('fs');
const path = require('path');
const Sequelize = require('sequelize');
const basename = path.basename(module.filename);
const env = process.env.NODE_ENV || 'development';
const config = require(__dirname + '/../config/config.json')[env];
const db = {};
if (config.use_env_variable) {
const sequelize = new Sequelize(process.env[config.use_env_variable]);
} else {
const sequelize = new Sequelize(config.database, config.username, config.password, config);
}
fs
.readdirSync(__dirname)
.filter((file) => {
return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js');
})
.forEach((file) => {
const model = sequelize['import'](path.join(__dirname, file));
db[model.name] = model;
});
Object.keys(db).forEach((modelName) => {
if (db[modelName].associate) {
db[modelName].associate(db);
}
});
db.sequelize = sequelize;
db.Sequelize = Sequelize;
module.exports = db;
config.json:
{
"development": {
"username": "",
"password": "",
"database": "late_file",
"host": "127.0.0.1",
"dialect": "postgres"
},
"test": {
"username": "",
"password": "",
"database": "database_test",
"host": "127.0.0.1",
"dialect": "postgres"
},
"production": {
"use_env_variable": "DATABASE_URL",
"dialect": "postgres"
}
}
.env, modified to exclude specific names of things
DB_HOST=localhost
DB_USER=
DB_PASS=
DB_NAME=
DB_SSL=true if heroku
DB_PORT=5432
DATABASE_URL=postgres://appropriate/url
applicable part of server.js
const pg = require('pg');
pg.defaults.ssl = true;
pg.connect(process.env.DATABASE_URL, function(err, client) {
if (err) throw err;
console.log('Connected to postgres! Getting schemas...');
client
.query('SELECT table_schema,table_name FROM information_schema.tables;')
.on('row', function(row) {
console.log(JSON.stringify(row));
});
});
Any help would be greatly appreciated!
Thanks in advance for anyone who offers any support!
Brandon,
I am running an app on Heroku using JAWS_DB and MySQL, but otherwise identical config.json and index.js. In my case on Heroku, the "if (config.use_env_variable) {const sequelize = new Sequelize(process.env[config.use_env_variable])" statement connects to the database without error. The logs appear to point to the "pg.connect" failing in server.js. It's not clear to me (without seeing the rest of your code) why you need to connect to the database in index.js, and then connect again in server.js. If you can remove the connection from pg.connect and try to run with just the connection from index.js it may stop this error.

could not find cucumber plugin for protractor test

i am brand new to protractor and did setup as per the instructions from the protractor website. When i try to run the protractor test with the a cucumber framework i always get "Error: Error: Cannot find module 'cucumber'". Any help on this? below are by configurations.
cucumber-conf.js
exports.config = {
seleniumAddress: 'http://localhost:4444/wd/hub',
capabilities: {
browserName:'chrome'
},
framework: 'custom',
frameworkPath: require.resolve('protractor-cucumber-framework'),
specs: [
'./cucumber/*.feature'
],
cucumberOpts: {
require: ['./cucumber/*.js'],
tags: [],
strict: true,
format: ["pretty"],
dryRun: false,
compiler: []
},
onPrepare: function () {
browser.manage().window().maximize();
}
};
when i run protractor cucumber-conf.js i get below error.
/opt/protractor_tests
➔ protractor cucumber-conf.js
(node:5681) DeprecationWarning: os.tmpDir() is deprecated. Use os.tmpdir() instead.
[12:06:55] I/launcher - Running 1 instances of WebDriver
[12:06:55] I/hosted - Using the selenium server at http://localhost:4444/wd/hub
[12:06:57] E/launcher - Error: Error: Cannot find module 'cucumber'
at Function.Module._resolveFilename (module.js:472:15)
at Function.Module._load (module.js:420:25)
at Module.require (module.js:500:17)
at require (internal/module.js:20:19)
at Object.module.exports.load (/opt/protractor_tests/node_modules/protractor-cucumber-framework/lib/cucumberLoader.js:5:12)
at Object.<anonymous> (/opt/protractor_tests/node_modules/protractor-cucumber-framework/index.js:5:48)
at Module._compile (module.js:573:32)
at Object.Module._extensions..js (module.js:582:10)
at Module.load (module.js:490:32)
at tryModuleLoad (module.js:449:12)
[12:06:57] E/launcher - Process exited with error code 100

protractor sets error without opening browser

i download a new ionic project and i am trying to test the header contains these elements ""
my config file is
exports.config = {
framework: 'jasmine2',
seleniumAddress: 'http://localhost:4444/wd/hub',
specs: ['../www/head.spec.js'],
multiCapabilities: [
{
browserName: 'chrome'
}]
}
named this as e2e.js
my test case file is
describe('header Module', function(){
var header;
beforeEach(function() {
header = element(by.css('title'));
});
it('should check title text',function(){
expect(header.getText()).toContain('Ionic Blank Starter');
});
});
and i named this as head.spec.js
my issue is that i could see the browser opened and my protractor sends an error msg
empresss-Mac-mini:myApp admin$ protractor test/e2e.js
Using the selenium server at http://localhost:4444/wd/hub
[launcher] Running 1 instances of WebDriver
/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/http/index.js:172
callback(new Error(message));
^
Error: ECONNREFUSED connect ECONNREFUSED 127.0.0.1:4444
at ClientRequest. (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/http/index.js:172:16)
at emitOne (events.js:77:13)
at ClientRequest.emit (events.js:169:7)
at Socket.socketErrorListener (_http_client.js:259:9)
at emitOne (events.js:77:13)
at Socket.emit (events.js:169:7)
at emitErrorNT (net.js:1253:8)
at doNTCallback2 (node.js:439:9)
at process.tickCallback (node.js:353:17)
From: Task: WebDriver.createSession()
at Function.webdriver.WebDriver.acquireSession (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:157:22)
at Function.webdriver.WebDriver.createSession (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/lib/webdriver/webdriver.js:131:30)
at [object Object].Builder.build (/usr/local/lib/node_modules/protractor/node_modules/selenium-webdriver/builder.js:445:22)
at [object Object].DriverProvider.getNewDriver (/usr/local/lib/node_modules/protractor/lib/driverProviders/driverProvider.js:38:7)
at [object Object].Runner.createBrowser (/usr/local/lib/node_modules/protractor/lib/runner.js:182:37)
at /usr/local/lib/node_modules/protractor/lib/runner.js:263:21
at _fulfilled (/usr/local/lib/node_modules/protractor/node_modules/q/q.js:797:54)
at self.promiseDispatch.done (/usr/local/lib/node_modules/protractor/node_modules/q/q.js:826:30)
at Promise.promise.promiseDispatch (/usr/local/lib/node_modules/protractor/node_modules/q/q.js:759:13)
at /usr/local/lib/node_modules/protractor/node_modules/q/q.js:525:49
[launcher] Process exited with error code 1
could someone help to fix this issue
when i try to webdriver-manager update err msg is displayed
empresss-Mac-mini:~ admin$ webdriver-manager update
fs.js:799
return binding.mkdir(pathModule._makeLong(path),
^
Error: EACCES: permission denied, mkdir '/usr/local/lib/node_modules/protractor/selenium'
at Error (native)
at Object.fs.mkdirSync (fs.js:799:18)
at Object.<anonymous> (/usr/local/lib/node_modules/protractor/bin/webdriver-manager:126:6)
at Module._compile (module.js:435:26)
at Object.Module._extensions..js (module.js:442:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:311:12)
at Function.Module.runMain (module.js:467:10)
at startup (node.js:134:18)
at node.js:961:3
empresss-Mac-mini:~ admin$