Wednesday, June 05, 2024

TypeORM raw sql query

  import { Connection } from 'typeorm';
  export class SomeService {
    constructor(private readonly connection: Connection) {}
    async runRawQuery(sql, params) {
        return this.connection.query(sql, params)
    }
  }

as of TypeORM v0.3.0, the @InjectConnection() decorator is deprecated
and @InjectDataSource() should be used instead

import { DataSource } from 'typeorm';
export class SomeService { // using Dependency Injection (DI)
  constructor(@InjectDataSource() private dataSource: DataSource) {}
  async runRawQuery(sql, params) {
    return this.dataSource.query(sql, params);
  }
}
// simplest solution

import { getManager } from 'typeorm';
async function runRawQuery(sql, params) {
  return getManager().query(sql, params);
}