How to retrieve class constants in TypeORM using getManager.query() in Typescript

I'm diving into the world of typeORM and Typescript. I've created a service class to handle a specific resource:

import { Injectable} from '@nestjs/common';
import { getManager } from 'typeorm';

class MyServiceClass {

static readonly sqlStr = `SELECT MAINTABLE.* WITH LEFT OUTER JOIN WITH TWO MORE TABLES`;

async findAll(limit?: number) {
    const mgr = getManager();
    const retRows = await mgr.query(
      `
      ${MyServiceClass.sqlStr}

          ${limit ? `FETCH NEXT ${limit} ROWS ONLY` : ''}
      `,
    );
    return retRows;
  }

async findOne(id: number) {
    const mgr = getManager();
    const retRow = await mgr.query(
      `
      ${MyServiceClass.sqlStr}

        ${id ? ` WHERE MAINTABLE.MAIN_ID = ${id}` : ''}
      `,
    );
    return retRow;
  }

}

I'm looking to streamline my code by removing the SQL statement from each function and utilizing the MyServiceClass.sqlStr property instead. Can anyone provide guidance on how to achieve this?

Answer №1

To maximize efficiency, consider utilizing the repository tools provided by the typeorm module:

async findAll(limit?: number) {
    const entities = await this.entityRepository.findAll(
      { where: { id: 1 } }, relations: ['someRelation'], sort: {id: 'DESC'},
      /* you have the flexibility to create highly advanced queries */
    );

    return entities;
  }

Alternatively, you can use query builder for more control:

async findAll(limit?: number) {
    const rows = await this.entityRepository
       .createQueryBuilder('Entity')
       .leftJoinAndSelect('Entity.relation', 'relation')
       .where('relation.id = :id', {id: 1})
       /* add any necessary query conditions here */
       .getMany() // or .getSql() or any other preferred method

    return rows;
  }

For a detailed guide on setting up typeorm repository, click here

Learn more about find options here

Explore query builder documentation here

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

Implement the conversion of a response to the JSON response standard within a NestJS application

I encountered an issue with converting the output of my object post saving it in the database. I attempted to adhere to the guidelines laid out by and convert my responses to the Json standard. The approach I took is not optimal. Here it is: async find ...

Using TypeORM QueryBuilder to retrieve data with nested INNER JOIN

I have a TripEntity that links to a Vehicle through the column vehicle_id. The VehicleEntity also has a reference to the VehicleDetailsEntity in the column vehicle_details_id. Example of TripEntity: id vehicle_id 1 99 Example of VehicleEntity: ...

Pause before sending each request

How can we optimize the Async Validator so that it only sends a request to JSON once, instead of every time a letter is typed in the Email form? isEmailExist(): AsyncValidatorFn { return (control: AbstractControl): Observable<any> => { ...

There seems to be an issue with functionality, as undefined is not behaving as expected in the combination of Graph

I am encountering an issue in my react native project where I am utilizing graphql codegen for generating types and hooks. The current version of react native that I am using is 0.74.5. However, I am facing an error which is preventing me from launching my ...

Switching FormControl based on condition in Angular

I'm currently working on creating a formGroup Validation that is dependent on a toggle value public toggle:boolean=false; ngOnInit(): void { this.formGroup = this.formBuilder.group({ formArray: this.formBuilder.array([ ...

What is the reason behind the Partial input basic type returning itself?

Snippet of code excerpt: type PartialType<T> = { [P in keyof T]?: T[P]; } I am curious about why the PartialType input basic type (such as string returning string) returns itself instead of throwing an error or an object. // undef => undefined t ...

The index.d.ts file for Bootstrap4 is unable to locate the 'popper.js' module when using TypeScript 3.9 and Libman in Visual Studio 2019

I currently utilize VisualStudio 2019 combined with TypeScript3.9 and Libman. My requirement is for Bootstrap4 and jQuery libraries to be incorporated. To achieve this, I attempt to obtain these libraries and typings(index.d.ts) via Libman. However, upo ...

Using createStyles in TypeScript to align content with justifyContent

Within my toolbar, I have two icons positioned on the left end. At the moment, I am applying this specific styling approach: const useStyles = makeStyles((theme: Theme) => createStyles({ root: { display: 'flex', }, appBar: ...

Angular 2- Unable to bind to 'ngSwitchCase' as it is not recognized as a native property

I am facing an issue with my code where I have two lists that are displayed in my .html file. In order to avoid repetition, I decided to utilize ngSwitch. However, when I try to implement this approach, I encounter an error. Here is the snippet of code cau ...

The dynamic fusion of Typescript and Angular 2 creates a powerful

private nodes = []; constructor(private nodeService: NodeService) {} this.nodeService.fetchNodes('APIEndpoint') .subscribe((data) => { this.nodes.push(data); }); console.log(this.nodes) This ...

When selecting the "Open Link in New Tab" option in Chrome, the Angular app's routing will automatically redirect to the login page

I am facing a peculiar issue in my Angular 2 application that I need help troubleshooting. Currently, the routing within my app functions as intended when I click on links to navigate between different components. Here is an example of how the routing path ...

The .ts document is not recognized as a TypeScript module

Check out this SystemJS + TypeScript plunk, which was created using the official Angular plunk template. An error is being thrown: (SystemJS) SyntaxError: Missing initializer in const declaration at eval () ... This error occurs when the .ts file is t ...

What is the best approach to creating a Typescript library that offers maximal compatibility for a wide range

My Vision I am aiming to develop a versatile library that can cater to both JavaScript and TypeScript developers for frontend applications, excluding Node.js. This means allowing JavaScript developers to utilize the library as inline script using <scri ...

Determining the argument type in Typescript based on the value of a previous argument

I am struggling to implement type checking on the payload argument of the notify method in the following class. Here is the code I have tried: type UserNotificationTypes = { ASSIGNED_TO_USER: { assignedUserId: string } MAIL_MESSAGE_SENT: { re ...

Tips for dismissing loader in Ionic 4

I'm struggling to programmatically dismiss the loader. I've developed two separate methods - one for displaying the loader and another for dismissing it. These methods are called accordingly when needed. async showLoader() { this.loader = a ...

Guide to successfully passing a function as a prop to a child component and invoking it within Vue

Is it really not recommended to pass a function as a prop to a child component in Vue? If I were to attempt this, how could I achieve it? Here is my current approach: Within my child component - <template> <b-card :style="{'overflow-y&apo ...

Error message: Trying to use the data type 'String' as an index in the React dynamic component name map won't work

I have successfully implemented the code below and now I am attempting to convert it to Typescript. However, even though I can grasp the error to some extent, I am unsure of how to correct it. At present, I am allowing a component to have a prop called "i ...

Having trouble building my Angular 2 app with Angular-cli beta 14, despite it working perfectly fine with systemjs beforeEach

I have been using VSCode on Windows 10 to work on an app developed in Angular 2 final version, which runs smoothly with systemjs. Recently, I upgraded to angular-cli beta 14 webpack version and followed the steps outlined in the upgrade document here. How ...

What is the relationship between an odd number and the value 1 in JavaScript that results in a 'true' outcome?

I encountered a straightforward problem, but the solution has left me perplexed. function transformArray(numbers) { // If 'i' is an odd number, i & 1 will evaluate to 1 or true return numbers.map(i => (i & 1) ? i * 3 : i * 2); } co ...

What is the best way to remove a reactive FormControl when a Component is destroyed?

I am facing an issue with a component that has a FormControl and a subscription to its value change: @Component(...) export class FooComponent implements OnInit, OnDestroy { fooFormControl: FormControl; ... ngOnInit() { this.fooFormControl.val ...