Search code examples
loopback4

Executing query on database in loopback 4


I am trying to execute a query on a database using the below mentioned code in loopback 4 but it throws error:
Property 'execute' does not exist on type 'typeof MetadataLettersRepository'. Please help.

Relevant codes are attached here.

Repository definition:

import {DefaultCrudRepository} from '@loopback/repository';
import {MetadataLetters, MetadataLettersRelations} from '../models';
import {RossmasDataSource} from '../datasources';
import {inject} from '@loopback/core';

export class MetadataLettersRepository extends DefaultCrudRepository<
  MetadataLetters,
  typeof MetadataLetters.prototype.id,
  MetadataLettersRelations
> {
  constructor(
    @inject('datasources.rossmas') dataSource: RossmasDataSource,
  ) {
    super(MetadataLetters, dataSource);
  }
}

Controller code:

import {get} from '@loopback/rest';
import {MetadataLettersRepository} from '../repositories';


export class HelloController {
  
  @get('/searchByMetadata')
  async searchByMetadata(): Promise<any> {
    const result = await MetadataLettersRepository.execute(
      'SELECT * FROM metadata_letters'
    );
    console.log('Query run successfully...!!!')
    return (result)
  }
}



Solution

  • You're trying to use a class directly, which is not possible in JavaScript or TypeScript. You will need an instance of the class (an object) that has already been initialized by LoopBack 4.

    In the controller, there should be a constructor for dependency injection:

    // This may be different depending on how the controller was created.
    // But the structure is more-or-less the same.
    
    constructor(
      @repository(MetadataLettersRepository)
      protected repository: MetadataLettersRepository,
    ) {}
    

    This tells LoopBack 4 to provide an instance of MetadataLettersRepository into the repository variable.

    From there, repository.execute() can be used:

    // Notice the use of the `repository` variable.
    
    const result = await repository.execute(
      'SELECT * FROM metadata_letters'
    );
    

    Further reading