Creating a New Table and Automating Migration in Production Using TypeORM

I am looking to automate the creation of a new table in MySQL and execute TypeORM migration when the application is running in production mode.

Important: The new table should not exist before starting the application in production mode.

The Migration Documentation specifies that the typeorm migration:run command needs to be used to run the migration.

My new table will only be created when the application calls CreateNewTableTimeStamp(inputTableName).up, which will trigger the creation of the table in the database.

However, I am struggling to find a way to automate this migration process since it's not feasible for me to manually run typeorm migration:run every time the application executes this method to create the new table.

Once the new table is created, I will proceed with adding data to this table.

Any assistance on this matter would be greatly appreciated.

Code for My New Table:

class CreateNewTableTimeStamp implements MigrationInterface  {

  tableName: string;

  constructor (inputTableName: string) {
    this.tableName = inputTableName
  }

  async up(queryRunner: QueryRunner): Promise<any> {
    await queryRunner.createTable(new Table({
          name: this.tableName,
          columns: [
              {
                  name: "id",
                  type: "int",
                  isPrimary: true
              },
              {
                  name: "email",
                  type: "varchar",
              }
          ]
      }), true)
  }

  async down(queryRunner: QueryRunner): Promise<any> {
    const table = await queryRunner.getTable(this.tableName);
    await queryRunner.dropTable(this.tableName);
  }
}

Answer №1

For individuals who wish to execute migrations solely for testing purposes and NOT in a live production setting.

import {
  createConnection,
  ConnectionOptions,
  Connection,
} from 'typeorm';

import { YourEntity } from 'path/to/your/entity.ts';

const testSetup: ConnectionOptions = {
  type: 'mongodb',
  url: 'mongodb://localhost:27017',
  database: 'test',
  useUnifiedTopology: true,
  entities: [YourEntity],
  synchronize: true,
  migrations: ['migrations/*YourMigrations.ts'],
};

let connection: Connection;

connection = await createConnection({ ...testSetup });
await connection.synchronize(true);

await connection.runMigrations({
 transaction: 'all',
});

To execute, use the following commands:

node -r ts-node/register ./path/to/migrations.ts

or

node ./path/to/compiled/migrations.js

Answer №2

As pointed out by @zenbeni in the comments, it is advised against running migrations from within your server code. Migrations should be kept immutable and replayed when necessary.

Based on this advice, I would reconsider my approach and avoid executing migrations from my server code.

Answer №3

Execute

yarn typeorm migration:create -n users
(table_name)

Example of Table Code:

   import { MigrationInterface, QueryRunner, Table } from 'typeorm';

export class createUsers1585025619325 implements MigrationInterface {
  private table = new Table({
    name: 'users',
    columns: [
      {
        name: 'id',
        type: 'integer',
        isPrimary: true,
        isGenerated: true, // Auto-increment
        generationStrategy: 'increment',
      },
      {
        name: 'email',
        type: 'varchar',
        length: '255',
        isUnique: true,
        isNullable: false,
      },
      {
        name: 'created_at',
        type: 'timestamptz',
        isNullable: false,
        default: 'now()',
      },
      {
        name: 'updated_at',
        type: 'timestamptz',
        isNullable: false,
        default: 'now()',
      },
    ],
  });

  public async up(queryRunner: QueryRunner): Promise<any> {
    await queryRunner.createTable(this.table);
  }
  public async down(queryRunner: QueryRunner): Promise<any> {
    await queryRunner.dropTable(this.table);
  }
}

Execute created migrations with:

yarn typeorm migration:run

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

What is the method to determine the size of a file in Node.js?

Have you ever wondered how to accurately determine the size of a file uploaded by a user? Well, I have an app that can do just that. The code for this innovative tool is provided below: Here is the snippet from server.js: var express = require('expr ...

Filtering relations in TypeORM can be achieved by using various query criteria

Hello, I have a couple of questions regarding TypeORM in TypeScript. Using Find() Only: I have two tables in my database - Users and Sessions. I am interested in retrieving a specific User along with all their Sessions where the sessions_deleted_at column ...

Creating a secure Node.js server using `https.js` is a great way to ensure the safety of

Currently in the process of setting up a secure server for my node.js application by utilizing the https.js NPM module. app.js: var http = require('https'), fs = require('fs'); var cert = { key: fs.readFileSync('/opt ...

Node.js does not recognize the function Product.findByIdAndRemove

router.delete("/:productId", async (req, res) => { try { const productId = req.params.productId; const deletedProduct = await Product.findByIdAndRemove(productId); if (!deletedProduct) { return res.sta ...

Upgrading NPM necessitates the installation of a fresh NPM version, leading to a potential deadlock when a specific version is

When specifying a specific version of npm in the package.json along with an .npmrc file, it triggers an error when running npm ci as expected. However, it prevents the npm version from being updated. package.json "engines": { "npm" ...

The Yeoman tool is experiencing functionality issues on Windows operating systems

After installing Node version 0.10.4 and npm 1.2.18 on a Windows 64-bit system, I attempted to install Yeoman by using 'npm install -g yo'. However, the installation was unsuccessful as the 'yo' command is not recognized on my machine. ...

The putObject function in Node.js extends the size of an object on the server

Currently, I am working on pushing an image to an S3 instance using Nodejs with the aws-sdk. The approach involves reading from a file on the client and saving it on the server within a meteor framework. However, my goal is to directly upload it to the S3 ...

Setting custom parameters ($npm_config_) for npm scripts on Windows allows for more flexibility and customization in

I'm struggling with passing custom parameters from the command line to npm scripts in my package.json file. Despite researching on various platforms, including Stack Overflow, I haven't found a solution that works for me. Here's what I' ...

Utilizing Node Sharp (LibVips) for Image Enhancement

I am looking to utilize VIPS for merging a collection of small images into one large image. The node package "sharp" leverages libvips. Is there a way to merge two images together using sharp? While VIPS has an "LRJOIN" function, I cannot seem to find a sh ...

NodeJS Throws an Error: Unexpected Symbol

Looking to create a website based on Rullete. I have the necessary code and scripts, but when I try to run the script, I encounter an error. [SyntaxError: Unexpected token <] SyntaxError: Unexpected token < at Object.parse (native) at Reques ...

Working with variables passed from Node.js in Jade processing

Currently, I have a situation where my script is sending a matrix that looks like this: [[1,2,3,4], [7,6,5,4], [2,3,4,5]]. After sending it using res.send(JSON.stringify(dataArray)); and viewing it in jade with h1#results, I can see that the format appears ...

What is the reason for the Express middleware using parenthesis syntax, whereas custom-made middleware does not?

What is the reason behind Express inbuilt middleware using a parenthesis syntax like app.use(express.json()) while custom-made middleware does not use parentheses like app.use(logger)? It seems to throw an error with parentheses. I'm uncertain if th ...

What is the most effective method for securing a Node.js REST API?

My current project involves building a Stripe server using Node and Express, which is being accessed by a React frontend. The basic API functionality allows for customer creation, saving payment methods, and accessing accounts for editing and updating. Pa ...

When using Websocket, an error message stating "Invalid frame header" will be triggered if a close message of 130 or more characters is sent

I am utilizing the ws node.js module along with html5's WebSocket. The Websocket connection is established when a user triggers an import action, and it terminates once the import is completed successfully or encounters an error. At times, the error ...

Express 4.13.4 appears to be disregarding the cookie's expiration date when the moment.toDate() function is used

I've been encountering an issue where I am attempting to set a cookie with a specific expiry date of 3 months, but the expiration is not setting correctly. Using momentJS, I created a date object for the desired time. The console confirms that the co ...

Executing an Ajax call to trigger a NodeJS function that executes a bash script

I have created a bash script to generate a JSON file that needs to be parsed and sent to the client-side JavaScript for display. My goal is to achieve this without refreshing the page and without using jQuery. I attempted to use Axios but seem to be facing ...

What could be causing my middleware to run twice?

A custom middleware was created in express.js/node.js to handle session checking. If a user ID is found in the session, it displays the user's menu; otherwise, it shows the default menu. For every page request, an ID check is performed and the user d ...

Retrieve data from table1 based on the criteria specified in table2

I have a project in mind where users can like each other's photos, and if the feeling is mutual, they become a match. It's similar to the concept of the Tinder app. Currently, I am retrieving one photo using the following query: SELECT id, pict ...

What is the most effective method for storing large volumes of data on a daily basis that can be categorized for statistical analysis?

I am currently creating a unique tracking tool tailored for marketing campaigns. This specialized tool acts as a mediator between advertisements and landing pages, responsible for recording all user data including user-agent information, IP addresses, clic ...

Utilizing the handler.ResponseBuilder returned from a promise's then() method

During the handling of intents for my Alexa skill, I encounter a situation where I need to return a response once a promise is resolved. The code structure resembles the following: var rcvPromise = receiveMsgQ(); rcvPromise.then(function(speechText) ...