Exploring Typescript/Javascript is a new adventure for me, especially as I delve into the world of rxjs. Here's a snippet of code that I've been working with:
return this.http.get<IXenoCantoResponse>(`${this.corsAnywhereUrl}${this.xenoCantoApiBaseUrl}${this.formatSearchTerm(searchTerm)}${this.recordingLength}`)
.pipe(
map(o => ({
numRecordings: o.numRecordings,
numSpecies: o.numSpecies,
page: o.page,
numPages: o.numPages,
recordings: o.recordings
}))
);
This code helps in mapping responses from a public API to an interface called IXenoCanto
:
export interface IXenoCantoResponse {
numRecordings: string;
numSpecies: string;
page: string;
numPages: string;
recordings: [];
}
The part that catches my interest is within the recordings[]
. I utilize the data from these recordings to generate URLs and incorporate them into another object:
data.forEach((element, index) => {
let sub = element.sono['full'].substr(0, this.getPosition(element.sono['full'], '\/', 6));
urls.push({
id: index + 1,
url: `${sub}${element['file-name']}`
});
});
export interface IVoice {
id: number;
url: string;
}
Although this code fulfills its purpose, I'm constantly seeking ways to enhance its efficiency.
I've pondered whether it's feasible to directly map the response array of type any[]
to IVoice[]
in the initial mapping code. Thus, I attempted modifying the IXenoCantoResponse interface like this:
export interface IXenoCantoResponse {
numRecordings: string;
numSpecies: string;
page: string;
numPages: string;
recordings: IVoice[]
}
Subsequently, my aim was to map the []
response directly to IVoice[]
, something along the lines of:
return this.http.get<IXenoCantoResponse>(`${this.corsAnywhereUrl}${this.xenoCantoApiBaseUrl}${this.formatSearchTerm(searchTerm)}${this.recordingLength}`)
.pipe(
map(o =>
o.recordings.map((element, index) => {
id: index + 1,
url: `${element.sono['full'].substr(0, this.getPosition(element.sono['full'], '\/', 6))}${element['file-name']}`
})
);
Thus far, my attempts in implementing this second approach have been unsuccessful. Perhaps, configuring the map
operator with an array object poses a challenge. Can anyone provide guidance on how to proceed?
Edit:
Each object within the mentioned recordings array adheres to the following format:
{
"id": "477551",
"gen": "Troglodytes",
...
}