Nest: unable to launch start:prod with mariadb

Created on 3 Dec 2018  路  9Comments  路  Source: nestjs/nest

I'm submitting a...


[ ] Regression 
[x] Bug report
[ ] Feature request
[ ] Documentation issue or request
[ ] Support request => Please do not submit support request here, instead post your question on Stack Overflow.

Current behavior

yarn start:prod
yarn run v1.6.0
warning ..\package.json: No license field
$ rm -rf dist && tsc
$ node dist/main.js
[Nest] 9272   - 2018-12-3 19:21:53   [NestFactory] Starting Nest application...
[Nest] 9272   - 2018-12-3 19:21:54   [InstanceLoader] TypeOrmModule dependencies initialized +7

90ms
[Nest] 9272   - 2018-12-3 19:21:54   [InstanceLoader] AppModule dependencies initialized +1ms
[Nest] 9272   - 2018-12-3 19:21:54   [TypeOrmModule] Unable to connect to the database. Retryin

g (1)... +115ms
C:\dev\workspace\project\src\my-entity\my-entity.entity.ts:1
(function (exports, require, module, __filename, __dirname) { import { Column, Entity, ManyToOne, PrimaryGeneratedColumn } from 'typeorm';
                                                              ^^^^^^

SyntaxError: Unexpected token import
    at createScript (vm.js:80:10)
    at Object.runInThisContext (vm.js:139:10)
    at Module._compile (module.js:616:28)
    at Object.Module._extensions..js (module.js:663:10)
    at Module.load (module.js:565:32)
    at tryModuleLoad (module.js:505:12)
    at Function.Module._load (module.js:497:3)
    at Module.require (module.js:596:17)
    at require (internal/module.js:11:18)
    at Function.PlatformTools.load (C:\dev\workspace\project\node_modules\typeorm\platform\Plat

formTools.js:131:28)

Expected behavior

I just want to launch the server in production mode :(

Minimal reproduction of the problem with instructions

app.module.ts
______________________________________________________________________
import { Module } from '@nestjs/common';
import { TypeOrmModule } from '@nestjs/typeorm';
import { UserModule } from './user/user.module';
@Module({
    imports: [
        TypeOrmModule.forRoot({
                type: 'mysql',
                host: 'localhost',
                port: 3306,
                username: 'dbUser',
                password: 'dbUser',
                database: 'dbCustom',
                entities: [
                    'src/**/**.entity{.ts,.js}',
                ],
                synchronize: true,
            },
        ),
       UserModule,
    ],
})
export class AppModule {
}

user/user.entity.ts
______________________________________________________________________
import {Entity, Column, PrimaryGeneratedColumn, JoinTable, ManyToMany} from 'typeorm';

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({length: 50})
    username: string;
   ...
}

What is the motivation / use case for changing the behavior?

I just want to run my nestJs backend in production >.<

Environment


Nest version: 5.3.0


For Tooling issues:
- Node version: v8.11.1
- Platform:  Windows

Others:

question 馃檶

Most helpful comment

I have seen a similar issue before. Basically, the reason is probably this line:

'src/**/**.entity{.ts,.js}',

Even though you're running your js precompiled app, the glob path is still pointing at .ts files and is trying to load them which lead to an error. Simply do not hold your source files (.ts) in the same directory OR add a condition that would load different extensions depending on some conditions (for example, prod env)

All 9 comments

Seems like to me you're not transpiling all your files from TS to JS, otherwise you've just put in the wrong target or module option.
target should be es5 or es6 and module should be commonjs

You'd probably be better off trying to provide a repository where we can reproduce the error.

Next time, you should ask at https://stackoverflow.com as this isn't a Nest related issue.

I have seen a similar issue before. Basically, the reason is probably this line:

'src/**/**.entity{.ts,.js}',

Even though you're running your js precompiled app, the glob path is still pointing at .ts files and is trying to load them which lead to an error. Simply do not hold your source files (.ts) in the same directory OR add a condition that would load different extensions depending on some conditions (for example, prod env)

Seems like to me you're not transpiling all your files from TS to JS, otherwise you've just put in the wrong target or module option.
target should be es5 or es6 and module should be commonjs

You'd probably be better off trying to provide a repository where we can reproduce the error.

Next time, you should ask at https://stackoverflow.com as this isn't a Nest related issue.

I have already all the config you recommended. You may notice, that i've followed the documentation on nestjs, and it doesn't work :(

I have seen a similar issue before. Basically, the reason is probably this line:

'src/**/**.entity{.ts,.js}',

Even though you're running your js precompiled app, the glob path is still pointing at .ts files and is trying to load them which lead to an error. Simply do not hold your source files (.ts) in the same directory OR add a condition that would load different extensions depending on some conditions (for example, prod env)

When i tried to change the config, as you recommended, and as i've seen on typeorm. I've no import error. But i've another error 馃挜

No repository for "User" was found. Looks like this entity is not registered in current "default" connection? +1ms
RepositoryNotFoundError: No repository for "User" was found. Looks like this entity is not registered in current "default" connection?
    at new RepositoryNotFoundError (C:\dev\workspace\project\node_modules\typeorm\error\RepositoryNotFoundError.js:20:28)
    at EntityManager.getRepository (C:\dev\workspace\project\node_modules\typeorm\entity-manager\EntityManager.js:585:19)
    at Connection.getRepository (C:\dev\workspace\project\node_modules\typeorm\connection\Connection.js:359:29)
    at Object.useFactory [as metatype] (C:\dev\workspace\project\dist\user\user.providers.js:7:48)
    at Injector.instantiateClass (C:\dev\workspace\project\node_modules\@nestjs\core\injector\injector.js:215:50)
    at callback (C:\dev\workspace\project\node_modules\@nestjs\core\injector\injector.js:67:41)
    at <anonymous>
    at process._tickCallback (internal/process/next_tick.js:188:7)
 1: std::vector<v8::CpuProfileDeoptFrame,std::allocator<v8::CpuProfileDeoptFrame> >::vector<v8::CpuProfileDeoptFrame,std::allocator<v8::CpuProfileDeoptFrame> >
 2: v8::internal::wasm::SignatureMap::Find
 3: v8::internal::Builtins::CallableFor
 4: v8::internal::Builtins::CallableFor
 5: v8::internal::Builtins::CallableFor
 6: 000003D084A843C1
error Command failed with exit code 3.

for information

import { Entity, Column, PrimaryGeneratedColumn } from 'typeorm';

@Entity()
export class User {
    @PrimaryGeneratedColumn()
    id: number;

    @Column({length: 50})
    username: string;

    @Column({length: 255})
    password: string;

    @Column({length: 50})
    firstname: string;

    @Column({length: 50})
    lastname: string;

    @Column({length: 255})
    email: string;

    @Column('datetime')
    lastLogin: Date;

    @Column()
    enabled: boolean;

    @Column('datetime')
    lastPasswordResetDate: Date;
}
@Module({
    imports: [DatabaseModule],
    providers: [
        UserService,
        ...userProviders,
    ],
    controllers: [UserController],
    exports: [UserService],
})
export class UserModule {
}



md5-2c0302173a3388d8a3a47c6ec1fe6eec



import { Connection } from 'typeorm';
import { User } from './user.entity';

export const userProviders = [
    {
        provide: 'UserRepositoryToken',
        useFactory: (connection: Connection) => connection.getRepository(User),
        inject: ['DbConnectionToken'],
    },
];



md5-2c0302173a3388d8a3a47c6ec1fe6eec



@Injectable()
export class UserService {
    constructor(@Inject('UserRepositoryToken') private readonly userRepository: Repository<User>) {
    }
}

Could you share your current configuration?

Could you share your current configuration?

Thank's for the help!

tsconfig.json

{
  "compilerOptions": {
    "module": "commonjs",
    "declaration": false,
    "noImplicitAny": false,
    "removeComments": true,
    "noLib": false,
    "allowSyntheticDefaultImports": true,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "target": "es6",
    "sourceMap": true,
    "allowJs": true,
    "outDir": "./dist",
    "baseUrl": "./src",
    "lib": [
      "es2015",
      "dom"
    ]
  },
  "include": [
    "src/**/*"
  ],
  "exclude": [
    "dist",
    "node_modules",
    "**/*.spec.ts",
    "**/*-spec.ts",
    "**/*.js"
  ]
}

src/database.module.ts

import { Module } from '@nestjs/common';
import { databaseProviders } from './database.providers';

@Module({
    providers: [...databaseProviders],
    exports: [...databaseProviders],
})
export class DatabaseModule {}

src/database.providers.ts

import { createConnection } from 'typeorm';

export const databaseProviders = [
    {
        provide: 'DbConnectionToken',
        useFactory: async () => await createConnection({
            type: 'mysql',
            host: 'localhost',
            port: 3306,
            username: 'project',
            password: 'project',
            database: 'project',
            entities: [
                __dirname + '/../**/**.entity{.js}', // <- WIP: to test different configs :(
            ],
            synchronize: true,
        }),
    },
];

:) Found a solution, by providing entities like this:

import { createConnection } from 'typeorm';
import { User } from './user/user.entity';

export const databaseProviders = [
    {
        provide: 'DbConnectionToken',
        useFactory: async () => await createConnection({
            type: 'mysql',
            host: 'localhost',
            port: 3306,
            username: 'project',
            password: 'project',
            database: 'project',
            entities: [
                  User, // <- solution
            ],
            synchronize: true,
        }),
    },
];

It works, but it will be better if it works with the generic path

@meyacine instead of:

__dirname + '/../**/**.entity{.js}', // <- WIP: to test different configs :(

use:

__dirname + '/../**/**.entity.js',

This thread has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.

Was this page helpful?
0 / 5 - 0 ratings

Related issues

marshall007 picture marshall007  路  3Comments

tronginc picture tronginc  路  3Comments

mishelashala picture mishelashala  路  3Comments

rlesniak picture rlesniak  路  3Comments

cdiaz picture cdiaz  路  3Comments