public async Task <IActionResult> PostWeather([FromBody] WeatherForCreationDto weatherForCreation) { // check for cached weather var cachedWeather = checkCache(weatherForCreation); if (cachedWeather != null) { cachedWeather.Cached = true; // persist to db _context.Weather.Add(cachedWeather); await _context.SaveChangesAsync(); return(CreatedAtAction(nameof(GetWeather), new { id = cachedWeather.Id }, cachedWeather)); } // if not cached, call to openweather api using (var client = new HttpClient()) { try { // query openweather client.BaseAddress = new Uri(_openWeatherConfig.Value.Uri); var query = $"?appid={_openWeatherConfig.Value.Key}&units=imperial&lat={weatherForCreation.Lat}&lon={weatherForCreation.Lng}"; var response = await client.GetAsync(query); var content = await response.Content.ReadAsStringAsync(); var weatherResponse = JsonConvert.DeserializeObject <OpenWeatherResponse>(content); // create new weather var weather = new Weather { Address = weatherForCreation.Address, CurrentTemp = (int)Convert.ToDouble(weatherResponse.Main.CurrentTemp), MinTemp = (int)Convert.ToDouble(weatherResponse.Main.MinTemp), MaxTemp = (int)Convert.ToDouble(weatherResponse.Main.MaxTemp), Zip = weatherForCreation.Zip, Cached = false }; // cache the weather cacheWeather(weather); // persist to db _context.Weather.Add(weather); await _context.SaveChangesAsync(); return(CreatedAtAction(nameof(GetWeather), new { id = weather.Id }, weather)); } catch (HttpRequestException httpRequestException) { return(BadRequest($"Error getting weather from OpenWeather: {httpRequestException.Message}")); } } }
private Weather checkCache(WeatherForCreationDto weatherForCreationDto) { // use zip as cache key else address var key = weatherForCreationDto.Zip == null ? weatherForCreationDto.Address : weatherForCreationDto.Zip.ToString(); var cached = _cache.Get(key); if (cached == null) { return(null); } using (var ms = new MemoryStream(cached)) { var cachedWeather = new BinaryFormatter() .Deserialize(ms) as Weather; return(cachedWeather); } }