public async Task <IActionResult> FetchAndStore( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, ILogger log) { log.LogInformation($"{nameof(FetchAndStore)} - Starting write function..."); // Read request string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); var zipCode = JsonConvert.DeserializeObject <string>(requestBody); if (string.IsNullOrWhiteSpace(zipCode)) { return(new BadRequestObjectResult("Invalid ZipCode")); } // Fetch Data from open weather map api var res = await _weatherMapService.GetWeatherData(zipCode); if (res == null) { return(new BadRequestObjectResult("Fail to retrieve weather data")); } // Map to Entity var weather = new ZipCodeWeather { ZipCode = zipCode, City = res.Name, Country = res.Sys.Country, WeatherDesc = res.Weather.FirstOrDefault().Description, Temp = res.Main.Temp, TempMin = res.Main.Temp_min, TempMax = res.Main.Temp_max, Wind = $"{res.Wind.Speed}mph {DegreeToDirectoin(res.Wind.Deg)}", Cloud = $"{res.Clouds.All}%", Pressure = $"{res.Main.Pressure}hpa", Longitude = res.Coord.Lon, Latitude = res.Coord.Lat, AsOfDate = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc).AddSeconds(res.Dt).ToLocalTime() }; // Insert into Database var response = await _dataService.InsertWeatherData(weather); return(new OkObjectResult(response)); }
/// <summary> /// InsertWeatherData /// </summary> /// <param name="weather"></param> /// <returns></returns> public async Task <ZipCodeWeather> InsertWeatherData(ZipCodeWeather weather) { _logger.LogInformation("Insert Weather Data..."); var result = await _context.ZipCodeWeather.FindAsync(weather.ZipCode); ZipCodeWeather response; if (result != null) { // update result.City = weather.City; result.Country = weather.Country; result.WeatherDesc = weather.WeatherDesc; result.Temp = weather.Temp; result.TempMin = weather.TempMin; result.TempMax = weather.TempMax; result.Wind = weather.Wind; result.Cloud = weather.Cloud; result.Pressure = weather.Pressure; result.Longitude = weather.Longitude; result.Latitude = weather.Latitude; result.AsOfDate = weather.AsOfDate; response = result; } else { // insert var entityEntry = await _context.ZipCodeWeather.AddAsync(weather); response = entityEntry.Entity; } var recordCount = await _context.SaveChangesAsync(); _logger.LogInformation($"{recordCount} records added or updated successfully."); return(response); }