Entities loading for a Nx.dev Monorepo with Nest.js and TypeOrm

1.1k views Asked by At

What I have been trying to do is to generate and run migrations with typeorm in the nest.js app within Nx.dev Monorepo.

But cannot find a way to do so.

My mono-repo looks like this

mono-repo structure

My database configurations look like this database configurations

And this is how I have initialized my connection in the app.module.ts file

 TypeOrmModule.forRootAsync({
  imports: [ConfigModule],
  useClass: DatabaseConfig
}),

I just wanted to know the way to generate and up the migrations.

Thanks and regards

1

There are 1 answers

0
Lucjan Wilczewski On

In order to run typeorm cli in my Nx monorepo, I have added following target in my project.json:

"typeorm": {
      "executor": "nx:run-commands",
      "outputs": [],
      "options": {
        "command": "TS_NODE_PROJECT=apps/web-api/tsconfig.app.json ts-node -r tsconfig-paths/register ./node_modules/typeorm/cli --config ./apps/web-api/src/database/cli.ts",
        "cwd": "."
      }
    },

where cli.ts returns DataSourceOptions in my command line configuration. Inside I have following configuration for migrations options:

  migrations: [path.join(__dirname, 'migrations', '*.[tj]s')],
  cli: { 
    migrationsDir: path.join(__dirname, 'migrations') 
  },

I execute it with following package.json script:

"migration:generate:web-api": "nx typeorm --project=web-api -- migration:generate -n",

In order to run migrations, I have added webpack configuration:

const glob = require('glob');

module.exports = (config, context) => {
  if (config.mode === 'production') {
    config.optimization = {
      minimize: false,
    };

    const sourcePaths = ['apps/web-api/src/database/migrations/**/*.[tj]s'];

    const additionalEntries = sourcePaths
      .flatMap((entryPath) => glob.sync(entryPath, { absolute: false }))
      .reduce((previous, current) => {
        const filename = current.split('src/')[1];
        previous[filename] = current;

        return previous;
      }, {});

    config.entry = {
      ...config.entry,
      ...additionalEntries,
    };
  }

  return config;
};

and configured my build target to use it with:

"build": {
  ...
  "options": {
    ...
    "webpackConfig": "apps/web-api/webpack.config.js",
  }
}