I'm trying to optimise multiple made to an 3rd party API (Spotify) in my NestJS API. My code is working but I do not find a way to optimise it.
@Get('')
async getAllData(@Req() req: Request) {
const token = req.cookies.access_token;
const user = this.userService.getCurrentUserProfile(token);
const periods = ['short_term', 'medium_term', 'long_term'];
const types = ['artists', 'tracks'];
const getUserTopData = async () => {
const promise = [];
types.forEach((type) => {
periods.forEach(async (period) => {
promise.push(
this.personalizationService.getUserTopArtistsTracks(
type as 'artists' | 'tracks',
{
time_range: period as
| 'short_term'
| 'medium_term'
| 'long_term',
limit: 1,
},
token,
),
);
});
});
return promise;
};
const promises = await getUserTopData();
const [
artistsShortTerm,
artistsMediumTerm,
artistsLongTerm,
tracksShortTerm,
tracksMediumTerm,
tracksLongTerm,
] = promises;
return Promise.all([
user,
artistsShortTerm,
artistsMediumTerm,
artistsLongTerm,
tracksShortTerm,
tracksMediumTerm,
tracksLongTerm,
])
.then((values) => {
const user = values[0];
const artistsShortTerm = values[1];
const artistsMediumTerm = values[2];
const artistsLongTerm = values[3];
const tracksShortTerm = values[4];
const tracksMediumTerm = values[5];
const tracksLongTerm = values[6];
return {
user,
artistsShortTerm,
artistsMediumTerm,
artistsLongTerm,
tracksShortTerm,
tracksMediumTerm,
tracksLongTerm,
};
})
.catch((err) => {
return err;
});
}
this.personalizationService.getUserTopArtistsTracks() function which executes the request :
export class PersonalizationService {
constructor(private httpService: HttpService) {}
async getUserTopArtistsTracks(
type: 'artists' | 'tracks',
query: {
time_range: 'short_term' | 'medium_term' | 'long_term';
limit: number;
offset?: number;
},
token: string,
): Promise<SpotifyApi.UsersTopArtistsResponse> {
const topArtists = this.httpService
.get<SpotifyApi.UsersTopArtistsResponse>(
`https://api.spotify.com/v1/me/top/${type}?${qs.stringify(query)}`,
{
headers: { Authorization: `Bearer ${token}` },
},
)
.toPromise();
return (await topArtists).data;
}
}
A call to my controller on NestJS return a JSON like that :
I think my code is too long and that there is a more shorter way to do it. But I don't see how.
