Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

typeorm migration:generate cannot work with entities that import from libraries in the same repo #9122

Open
p-v-d-Veeken opened this issue Jun 18, 2022 · 8 comments

Comments

@p-v-d-Veeken
Copy link

Issue Description

I have an Nx monorepo with several nestjs libs which each have their own typeorm configuration (i.e. their own database). The entities in these libs all import from a shared utilities library.

Since Typeorm 0.3.x generating migrations for each of these libs is broken due to the typeorm cli not understanding how it needs to handle imports.

Neither of these commands work:

npm run typeorm migration:generate -- exampleMigration -d libs/backend/user/orm.config.ts

nor:

ts-node --project tsconfig.base.json -r tsconfig-paths/register node_modules/typeorm/cli-ts-node-commonjs.js migration:generate test -d libs/backend/user/orm.config.ts

Expected Behavior

A correctly generated migration.

Actual Behavior

The first command errors with:

$ npm run typeorm migration:generate -- test -d libs/backend/user/orm.config.ts

> typeorm-example@0.0.0 typeorm
> typeorm-ts-node-esm "migration:generate" "test" "-d" "libs/backend/user/orm.config.ts"

Error during migration generation:
libs/backend/user/src/lib/domain/user.entity.ts:2:31 - error TS2307: Cannot find module '@typeorm-example/shared/ddd-seedwork' or its corresponding type declarations.

2 import { AggregateRoot } from '@typeorm-example/shared/ddd-seedwork';
                                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
libs/backend/user/src/lib/domain/user.entity.ts:5:14 - error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning.

5 export class User extends AggregateRoot {
               ~~~~
libs/backend/user/src/lib/domain/user.entity.ts:7:10 - error TS1219: Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option in your 'tsconfig' or 'jsconfig' to remove this warning.

7   public name: string;
           ~~~~

The second command errors with:

$ ts-node --project tsconfig.base.json -r tsconfig-paths/register node_modules/typeorm/cli-ts-node-commonjs.js migration:generate test -d libs/backend/user/orm.config.ts

Error during migration generation:
libs/backend/user/src/lib/domain/user.entity.ts:3:31 - error TS2307: Cannot find module '@typeorm-example/shared/ddd-seedwork' or its corresponding type declarations.

3 import { AggregateRoot } from '@typeorm-example/shared/ddd-seedwork';
                                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
libs/backend/user/src/lib/domain/user.entity.ts:5:17 - error TS7006: Parameter 'name' implicitly has an 'any' type.

5     constructor(name) {
                  ~~~~
libs/backend/user/src/lib/domain/user.entity.ts:7:14 - error TS2339: Property 'name' does not exist on type 'User'.

7         this.name = name;

Steps to Reproduce

  1. checkout: https://github.com/p-v-d-Veeken/typeorm-example
  2. Run either of the two commands described above.

My Environment

Dependency Version
Operating System
Node.js version v14.17.4
Typescript version 4.7.4
TypeORM version 0.3.6

Additional Context

My project is in an Nx Monorepo (version 14.3.6) and is using @nestjs/typeorm ^8.1.4

Relevant Database Driver(s)

DB Type Reproducible
aurora-mysql yes
aurora-postgres yes
better-sqlite3 yes
cockroachdb yes
cordova yes
expo yes
mongodb yes
mysql yes
nativescript yes
oracle yes
postgres yes
react-native yes
sap yes
spanner yes
sqlite yes
sqlite-abstract yes
sqljs yes
sqlserver yes

Are you willing to resolve this issue by submitting a Pull Request?

  • ✖️ Yes, I have the time, and I know how to start.
  • ✅ Yes, I have the time, but I don't know how to start. I would need guidance.
  • ✖️ No, I don’t have the time, but I can support (using donations) development.
  • ✖️ No, I don’t have the time and I’m okay to wait for the community / maintainers to resolve this issue.
@p-v-d-Veeken
Copy link
Author

I think this could be fixed by specifying what options are passed to ts-node in both https://github.com/typeorm/typeorm/blob/master/src/cli-ts-node-commonjs.ts and https://github.com/typeorm/typeorm/blob/master/src/cli-ts-node-esm.ts

@HankTwTw
Copy link

same problem here

@p-v-d-Veeken
Copy link
Author

I've managed to work around this issue in the following manner:
create tools/typeorm.custom-cli.ts:

#!/usr/bin/env node
import { register } from 'ts-node';

register({ transpileOnly: true, });

import 'typeorm/cli';

and then putting the following in my package.json:

{
...
   "scripts": {
    ...
      "typeorm": "ts-node --project ./tsconfig.base.json -r tsconfig-paths/register ./tools/typeorm.custom-cli.ts"
   }
}

Then the generate migrations command can be run as follows:

npm run typeorm migration:generate -- YourMigrationName -d libs/some-project/backend/user/orm.config.ts

Where orm.config.ts:

import { DataSource } from 'typeorm';
import { SqlServerConnectionOptions } from 'typeorm/driver/sqlserver/SqlServerConnectionOptions';

const config = {
    type: 'mssql',
    host: 'hostt', // adjust
    port: 1433,
    username: 'username', // adjust
    password: '***snip***', // adjust
    database: 'user', // adjust
    entities: ['libs/some-project/backend/user/src/lib/domain/**/*.entity.ts'], // adjust
    migrations: ['libs/some-project/backend/user/src/lib/infrastructure/migrations/*.ts'], // adjust
    synchronize: false,
    logging: false,
    options: {
        encrypt: true,
        enableArithAbort: true,
    },
    migrationsRun: true,
    pool: {
        max: 100,
        min: 0,
        idleTimeoutMillis: 30000,
    }
} as SqlServerConnectionOptions;

export default new DataSource(config);

@paroquet
Copy link

@p-v-d-Veeken The code you provided works! Would you mind explain it for a while ?

@edulima01
Copy link

I couldn't make this solution work, @p-v-d-Veeken. I've receiving the error:

node ➜ /workspaces/my-system (feature/add-migrations ✗) $ npm run typeorm migration:generate -- initialVersion -d libs/my-lib-base-dir/my-lib/migrations.datasource.ts

> my-system@0.0.0 typeorm
> ts-node --project ./tsconfig.base.json -r tsconfig-paths/register ./tools/typeorm.custom-cli.ts migration:generate initialVersion -d libs/content/component/migrations.datasource.ts

(node:22110) Warning: To load an ES module, set "type": "module" in the package.json or use the .mjs extension.
(Use `node --trace-warnings ...` to show where the warning was created)
/workspaces/my-system/tools/typeorm.custom-cli.ts:2
import { register } from 'ts-node';
^^^^^^

SyntaxError: Cannot use import statement outside a module
    at Object.compileFunction (node:vm:360:18)
    at wrapSafe (node:internal/modules/cjs/loader:1088:15)
    at Module._compile (node:internal/modules/cjs/loader:1123:27)
    at Module.m._compile (/workspaces/my-system/node_modules/ts-node/src/index.ts:1618:23)
    at Module._extensions..js (node:internal/modules/cjs/loader:1213:10)
    at Object.require.extensions.<computed> [as .ts] (/workspaces/my-system/node_modules/ts-node/src/index.ts:1621:12)
    at Module.load (node:internal/modules/cjs/loader:1037:32)
    at Function.Module._load (node:internal/modules/cjs/loader:878:12)
    at Function.executeUserEntryPoint [as runMain] (node:internal/modules/run_main:81:12)
    at phase4 (/workspaces/my-system/node_modules/ts-node/src/bin.ts:649:14)

Is there anything environment-specific to make this work? Is your sample github that you mentioned when opening the issue updated with the correct solution? Or is it the initial not-working version?

My tsconfig.base.json is exactly the same as the one in your github repository.

I have node v18.12.1, ts-node v10.9.1 and I'm using nestjs/typeorm v9.0.1 with typeorm v0.3.10. What is your environment?

@rbmdotdev
Copy link

same issue here

1 similar comment
@lukas-h
Copy link

lukas-h commented May 24, 2023

same issue here

@SeyedMostafaHosseinian
Copy link

SeyedMostafaHosseinian commented Dec 29, 2023

I had the same problem
I use NX for the project environment. The problem was that there were different configuration files, for example, with the names tsconfig.base.json and... in the root of the project. But tsconfig.json was not exist!! I created this file in the root of the project and gave it the desired configurations, such as the following codes:

{
    "compilerOptions": {
      "module": "commonjs",
      "declaration": true,
      "removeComments": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "allowSyntheticDefaultImports": true,
      "target": "ES2021",
      "sourceMap": true,
      "outDir": "./dist",
      "baseUrl": "./",
      "incremental": true,
      "skipLibCheck": true,
      "strictNullChecks": false,
      "noImplicitAny": false,
      "strictBindCallApply": false,
      "forceConsistentCasingInFileNames": false,
      "noFallthroughCasesInSwitch": false
    }
  }
  

The problem was solved! So we conclude that typeorm must be able to find the typescript configuration file and most likely tsconfig.json must be in the root of the project and the following options must be active in it:

{
     "emitDecoratorMetadata": true,
     "experimentalDecorators": true,
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

7 participants