Issue with nx-Monorepo when using TypeORM migrations

After numerous attempts on my own, I've come to the realization that I may need some assistance. My project is a nx-monorepo setup with an angular-frontend and nestjs backend. Recently, I integrated a Postgres-SQL database using TypeORM. The connectivity to the database, incoming API calls, and overall functionality seem to be in order.

However, I'm encountering issues when trying to generate a migration script. In an effort to resolve this, I added a run-command for my backend project:


        "generate-migration": {
          "builder": "@nrwl/workspace:run-commands",
          "outputs": [],
          "options": {
            "command": "ts-node ../../node_modules/.bin/typeorm migration:generate -n",
            "cwd": "apps/api"
          }
        }
    

Executing the command using "npm run api:generate-migration" results in the following error:

Error during migration generation: /apps/api/src/model/base.entity.ts:1 import { __decorate, __metadata } from "tslib"; ^^^^^^

SyntaxError: Cannot use import statement outside a module at wrapSafe (node:internal/modules/cjs/loader:1024:16) ... ERROR: Something went wrong in @nrwl/run-commands - Command failed: ts-node ../../node_modules/.bin/typeorm migration:generate -n

In my ormConfig.json file, the relevant details are as follows:


        {
          ...
          "type": "postgres",
          "migrationsTableName": "migration",  
          "migrations": ["src/migration/*.ts"],
          "cli": {
            "migrationsDir": "src/migration"
          },
          "ssl": false
        }
    

If anyone has insights or solutions regarding this issue, your help would be greatly appreciated! Please :)

Answer №1

Utilizing NX@13, NestJS@8, and

<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="c195b8b1a48e938c81">[email protected]</a>
, I have successfully developed a backend service.

In the configuration file project.json for game-api, I've included commands like the following:

"generate-migration": {
      "builder": "@nrwl/workspace:run-commands",
      "outputs": [],
      "options": {
        "command": "ts-node --project tsconfig.app.json ../../node_modules/.bin/typeorm migration:generate --pretty -f .env.local",
        "cwd": "apps/game-api"
      }
    },

Explore the code repository here: https://github.com/coinconket/conketkemon

Answer №2

If you're seeking assistance, the following information may be valuable. For the most recent nx@^14, @nestjs/*@^9, and typeorm@~0.3:

within your project.json. Remember,

"apps/<app-name>"
is also applicable to
"libs/<lib-name>"

"typeorm": {
      "builder": "@nrwl/workspace:run-commands",
      "outputs": [],
      "options": {
        "command": "ts-node --project tsconfig.json <path-to-node_modules>/typeorm/cli",
        "cwd": "apps/<app-name>"
      }
    },
"mig-gen": {
      "builder": "@nrwl/workspace:run-commands",
      "outputs": [],
      "options": {
        "command": "nx run <app-name>:typeorm migration:generate <path-to-migration>/{args.name} -d <path-to-typeorm-config>/typeorm.config.ts",
        "cwd": "apps/<app-name>"
      }
    },

In your typeorm.config.ts

import { DataSource, DataSourceOptions } from 'typeorm';
import { config } from 'dotenv';
import { join } from 'path';

config({ path: '<path-to-env>/.env' });

const { DB_TYPE, DB_HOST, DB_USER, DB_PASS, DB_PORT, DB_NAME } =
  process.env;

export default new DataSource({
  type: DB_TYPE,
  host: DB_HOST,
  port: Number(DB_PORT),
  username: DB_USER,
  password: DB_PASS,
  database: DB_NAME,
  entities: [join(__dirname, '<path-to-entities>/*.entity.{ts,js}')],
  migrations: [join(__dirname, '<path-to-migration>/*{.ts,.js}')],
  synchronize: false,
} as DataSourceOptions);

ensure that in your

<path-to-app>/tsconfig.json

you have set

"emitDecoratorMetadata": true
under compilerOptions{...}. Other properties like module, types, and target might require configuration as well. Refer to your
<root-workspace>/tsconfig.base.json
and documentation at https://www.typescriptlang.org/tsconfig for guidance

Lastly, execute the following command in your terminal to generate your migration file

nx run <app-name>:mig-gen --name=whatever-makes-you-happy

Answer №3

After including

"module": "CommonJS"
within the compilerOptions section of tsconfig.app.json file in the corresponding nx application, the problem was resolved successfully.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In the production build, the RegEx validation is lacking and fails to accept certain characters like 0, 2, 7, a, c, u, x, and occasionally z

Incorporating Angular 15.2.10 and Typescript 4.9.5, the RegEx utilized in one of my libraries and exposed via a service is outlined as follows: private readonly _DISALLOWED_CHARS_REGEX_GENERAL = new RegExp(/^[^\\/\?\!\&\: ...

The attribute 'fit' within the Button type cannot be reassigned to the identical attribute in the base type 'IButton'. The string type cannot be reassigned to the Fit type

In my coding project, I have a Button class that implements the IButton interface. class Button implements IButton { public fit = 'medium'; } declare type Fit = 'small' | 'medium' | 'large'; export interface IBu ...

Creating Empathetic User Experiences with Next 12 and SWC: A Guide to Harnessing import.meta.url

In my Next.js 12 App with the Rust Compiler, I am utilizing Jest and WebWorkers. In one of my files, I am using import.meta.url. to create the worker. The issue arises when Jest throws an error, stating that import.meta.url cannot be used outside of an ES ...

The Typescript generics are unable to be assigned to type T

Take a look at my code snippet: interface IDoc { doSomething(): void } class IDocFoo implements IDoc { doSomething(): void { console.log('Do doSomething'); } } class IDocFactory { getIDocInstance<T extends IDoc>(): T { re ...

Validator in Angular FormControl ensures that two fields have the same value or both are empty

When filling out a form with four fields, I have encountered a specific requirement. Two of the fields are mandatory, which is straightforward. However, the other two must either both be empty or both have a value - essentially resembling an XNOR logic sta ...

What is the method for transmitting a URL API from an ASP.NET Core server to my Angular 2 single application?

Is there a way to securely share the url of the web api, which is hosted on a different server with a different domain, from my asp net core server to my client angular2? Currently, I am storing my settings in a typescript config file within my angular2 ap ...

Issue with migrating the Django database

My Django project is connected to the Gmail API. When attempting to run a database migration, I encountered the following error: C:\Users\Peter\Desktop\FastProject>python manage.py migrate FastProject Traceback (most recent ...

Exploring Angular's ngFor feature in building a dynamic accordion menu that automatically closes one panel and opens another when clicked

The Angular Material accordion component is a key feature in my Angular project. Utilizing an ngFor loop to iterate through the information stored in menuItems, I dynamically create a new expansion panel for each item. With two components in play, I seaml ...

Guide on importing JavaScript into TypeScript without using noImplicityAny and while not allowing Js

In my development setup, I am utilizing Webpack along with @babel/typescript to compile a project that consists of a mix of TypeScript and JavaScript. To ensure better typing and take advantage of the benefits it offers, I have enabled the --noImplicitAny ...

Error: The 'name' property cannot be assigned to an undefined value

Currently facing an issue while trying to assign values from a JSON response to another variable. The error message "Cannot set property name of undefined" is appearing. export interface Data { description: any; name : any; } Within the main class, ...

Guide on creating several TypeScript interfaces that share identical type structures

export interface UserFailureResponse { statusCode: number statusMessage: string } export interface UserCreateResponse { statusCode: number statusMessage: string } export interface AuthCheckResponse { statusCode: number statusMessa ...

Angular 6 - The state of the expression was altered after it was verified, different types of constructions

During the build process in debug mode with ng build, I am encountering errors in some components. However, when I switch to production mode using ng build --prod, these errors disappear. I am curious as to why this discrepancy is occurring. Error: Expre ...

Angular allows you to set specific conditions for when a failed HTTP request should be retried, and you can also specify the number of attempts that should be

Within my angular application, I have a post request that needs to be retried based on the error message, but with a limit on the number of attempts. Initially, I attempted the following approach: public post(url, data) { this._http.post(url, data).pi ...

Caution: It is important for each child in a list to have a distinct "key" prop when adding a new element to the list

I have been working on a project that involves creating a list of items using React, Express (axios), and MongoDB. The items in the list are retrieved from MongoDB, displayed in a component, and users have the ability to add new items (which are then save ...

"Choosing how to define class properties: with a dot or an equal

As I delve into the angular documentation, I notice that all classes have properties defined in a specific way: class A { a = 2; }; However, in the TypeScript official documents, the class properties are declared differently: class A { a:2 } I'm c ...

Ways to access a nested property within an array

I'm having an issue when trying to access a sub property of an array. Here's the snippet in question: ngOnInit() { this.menus = this.navService.defaultMenu; console.log(this.getMenusItem()); this.registerChangeInProjects(); } T ...

Guide on removing a key from an object in TypeScript

My variable myMap: { [key: string]: string[] } = {} contains data that I need to modify. Specifically, I am trying to remove a specific value associated with a certain key from the myMap. In this case, my goal is to delete value1 from myMap[Key1]. Despit ...

Is it possible that Angular 6's ngOnChanges directive is not compatible with a lambda expression?

Currently, I am in the process of creating an attribute directive that is designed to alter the background color of the host element based on a provided "quality" @input. While experimenting with my directive, I discovered that using ngOnChanges as a lamb ...

Guide on importing TypeScript types into Vuetify 3

Exploring the use of the ValidationRule type from the Vuetify library (check out the docs and source code), I'm facing difficulties importing it into my Vue.js component. I have attempted to import the type in different ways, such as: import type { V ...

Directive's timeout function fails to execute

My goal was to experiment with a simple AutoScrollDirective. @Directive({ selector: '[appAutoScroll]', }) export class AutoScrollDirective implements AfterViewInit { constructor(private element: ElementRef<HTMLElement>) {} @Input() ...