mardi 23 mars 2021

Calling API in loopback 4

I am new to loopback 4. I have written an API in a file hello.controller.ts as shown here: export class HelloController { constructor( @repository(StationMRepository) protected stationMRepository: StationMRepository) {}

 @post('/stationDetails')
  async stationDetails(@requestBody({
    content: {
      'application/json': {
        schema: {type: 'object'},
      },
    },
  }) data: {
    searchKeyValuePair:
    {
      miscellaneous: string,
      //relevantRollingStock: string,
    },

  }): Promise<any> {

    console.log("Req.body:", data)
    var miscellaneous: string = data.searchKeyValuePair.miscellaneous.trim()
    miscellaneous = miscellaneous.toLowerCase();
    var result: any = ''
    var resultLength: number = 0
    var stationData: string = ''
    var miscellaneousValid: boolean = !(miscellaneous == '' || miscellaneous == null || miscellaneous == undefined)
    if (miscellaneousValid) {
      stationData = `select public.stn_fullname_tsv_fn('${miscellaneous}')`
    }
    /*Calling tsVector Function*/
    result = await this.metadataLettersRepository.execute(stationData)
    //console.log(result)

    /*To make the format of the data same for ts_vector and non ts_vector case*/
    resultLength = result.length
    //var resultModified: Array<any> = []
    var resultModifiedNew: Array<any> = []


    if (resultLength > 0) {
      for (var i = 0; i < resultLength; i++) {
        // resultModified.push(result[i].letters_flex_search_tsvector)

        //Mapping from db format to Model format
        var objFormat: any = {}
        objFormat.stnCode = result[i].stn_fullname_tsv_fn.stn_code.trim()
        objFormat.stnFullname = result[i].stn_fullname_tsv_fn.stn_fullname.trim()
        objFormat.divCode = result[i].stn_fullname_tsv_fn.stn_divcode.trim()
        objFormat.divFullname = result[i].stn_fullname_tsv_fn.div_fullname.trim()
        objFormat.zoneCode = result[i].stn_fullname_tsv_fn.stn_zonecode.trim()
        objFormat.zoneFullname = result[i].stn_fullname_tsv_fn.zone_fullname.trim()

        console.log(objFormat)
        resultModifiedNew.push(objFormat)

      }
    }
    console.log('ResultModified: ', resultModifiedNew)
    console.log('ResultModified length:', resultModifiedNew.length)
    return (resultModifiedNew)

  }

}

And I need to call this API inside app.test.js for testing. The code is as here:

it("Provides Station Details", () => {

    
    var stn = { data: { searchKeyValuePair: { miscellaneous: "LKO" } } }

   
    const result = stationDetails(stn) //erroneous line
    console.log('Result: ', result)
    expect(result).to.have.status(200);
    console.log('Tested successfully..!!!')
   
  });

It gives me error as: ReferenceError: stationDetails is not defined

Please guide regarding what should i replace the erroneous code with so that API is called correctly. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire