I am building a NestJS API which will call Bing's Custom Search Engine endpoint and return the search results in JSON format. https://learn.microsoft.com/en-us/azure/cognitive-services/bing-custom-search/call-endpoint-nodejs
I am successfully able to call the endpoint using my API key and print the resulting JSON to my console. The issue I have is that the function returns the empty data before the request has a chance to populate the array with any data.
I apologize if the code format is completely wrong or if the entire thing is setup incorrectly. I've never programmed an API before and have to learn it on the fly.
Controller
import { Controller, Get } from '@nestjs/common';
import { SearchEngineService } from './search-engine.service';
@Controller('tasks')
export class SearchEngineController {
constructor(private searchEngineService: SearchEngineService) {}
@Get()
processRequest() {
return this.searchEngineService.processRequest();
}
}
Service
import { Injectable } from '@nestjs/common';
@Injectable()
export class SearchEngineService {
processRequest() {
var request = require("request");
var searchResponse;
var webPage;
var parsedSearchResponse = [];
var subscriptionKey = "SUBSCRIPTION_KEY";
var customConfigId = "CONFIG_ID";
var searchTerm = "partner";
var info = {
url: 'https://api.cognitive.microsoft.com/bingcustomsearch/v7.0/search?'
+ 'q='
+ searchTerm
+ "&"
+ 'customconfig='
+ customConfigId,
headers: {
'Ocp-Apim-Subscription-Key' : subscriptionKey
}
}
request(info, function(error, response, body) {
searchResponse = JSON.parse(body);
console.log("\n");
for (var i = 0; i < searchResponse.webPages.value.length; ++i) {
webPage = searchResponse.webPages.value[i];
parsedSearchResponse.push(searchResponse.webPages.value[i]);
console.log('name: ' + parsedSearchResponse[i].name);
console.log('url: ' + parsedSearchResponse[i].url);
console.log('displayUrl: ' + parsedSearchResponse[i].displayUrl);
console.log('snippet: ' + parsedSearchResponse[i].snippet);
console.log('dateLastCrawled: ' + parsedSearchResponse[i].dateLastCrawled);
console.log();
}
console.log("\n###################################");
});
return parsedSearchResponse;
}
}