I want to get weather info for a city from OpenWeatherMap but I get a weird JSON response
Response the I got
{ "name": "dallas", "weather": { "source": { "source": {} } }, "_id": "61c335daeb8c6b030489996b", "__v": 0 }
cities.service.ts
@Injectable()
export class CitiesService {
constructor(
@InjectModel('City') private readonly cityModel: Model<City>,
private readonly httpService: HttpService
) {}
async createCity(createCityDto: CreateCityDto) {
const { name } = createCityDto;
// Get city weather from OpenWeatherMap
const weather = await this.httpService
.get(
`api.openweathermap.org/data/2.5/weather?q=${name}&appid=${process.env.OPEN_WEATHER_API_KEY}`,
)
.pipe(
map((response) => response.data),
map((data) => data),
);
console.log(weather);
const city = new this.cityModel({
name,
weather,
});
await city.save();
return city;
}
}
CodePudding user response:
@nestjs/axios
wraps all of the HTTP calls in RxJS Observables which are kind of like supercharged callbacks. Once you open an observable stream, you either need to only work inside that stream (using the .pipe
and operators as you've started for mapping the data) or you need to convert the Observable to a promise. The easiest way to do that is to use lastValueFrom
and wrap the entire Observbale with it (lastValueFrom(this.http.get().pipe())
). If you go with the former, tap
and switchMap
will probably be two operators to get the hang of as well, otherwise the lastValueFrom
approach can be await
ed as a normal promise.