public async Task ShouldRetrievePhotosFromNasaApiNoSpecifiedCamera() { var options = new DbContextOptionsBuilder <NasaContext>() .UseInMemoryDatabase(databaseName: "Nasa") .Options; using (var context = new NasaContext(options)) { var rover = _fixture.Create <Business.Models.Rover>(); var camera = _fixture.Build <Business.Models.Camera>() .With(x => x.Rover, rover) .With(x => x.RoverId, rover.Id) .Create(); context.Rovers.Add(rover); context.Cameras.Add(camera); context.SaveChanges(); var query = _fixture.Build <GetPhotos.Query>() .With(x => x.RoverId, rover.Id) .Without(x => x.Camera) .Create(); var expectedPhotos = _fixture.Build <Business.Models.Photo>() .With(x => x.Camera, camera) .With(x => x.EarthDate, query.Date.Date) .CreateMany() .ToList(); var expectedResult = new GetPhotos.Result { Photos = expectedPhotos.Select(x => new GetPhotos.Photo { Id = x.Id, ImgSrc = x.ImgSrc }).ToList() }; _api.GetPhotos(Arg.Is <string>(x => x == rover.Name), Arg.Is <DateTime>(x => x == query.Date.Date)) .Returns(new PhotoResponse { Photos = expectedPhotos }); var handler = new GetPhotos.Handler(_api, context); var result = await handler.Handle(query, CancellationToken.None); //Check Result result.Should().BeEquivalentTo(expectedResult); //Check db to make sure they were inserted properly context.Photos.Should().NotBeEmpty(); foreach (var photo in expectedPhotos) { context.Photos.Should().Contain(photo); } //Make sure the api was actually hit await _api.Received().GetPhotos(Arg.Is <string>(x => x == rover.Name), Arg.Is <DateTime>(x => x == query.Date.Date)); } }
public async Task <Result> Handle(Query query, CancellationToken cancellationToken) { //Check to see if the photos have already been gathered (will fail if it's today) var gathered = false; if (query.Date.Date != DateTime.Today) { gathered = _context.Photos.Any(x => x.EarthDate == query.Date.Date && x.Camera.Rover.Id == query.RoverId); } if (!gathered) { var rover = _context.Rovers.FirstOrDefault(x => x.Id == query.RoverId); if (rover == null) { throw new Exception("Invalid rover Id"); } //Call Nasa Api to get photos var result = await _api.GetPhotos(rover.Name, query.Date.Date); var gatheredPhotos = result.Photos; foreach (var photo in gatheredPhotos) { photo.Camera = _context.Cameras.FirstOrDefault(x => x.RoverId == rover.Id && x.Name == photo.Camera.Name); photo.CameraId = photo.Camera.Id; } //Save photos to db _context.Photos.AddRange(gatheredPhotos); await _context.SaveChangesAsync(cancellationToken); } //filter photos based on information sent from client var photos = await _context.Photos.Where(x => x.EarthDate == query.Date.Date && x.Camera.Rover.Id == query.RoverId && (query.Camera == null || x.Camera.Name == query.Camera)) .Select(x => new Photo { Id = x.Id, ImgSrc = x.ImgSrc }) .ToListAsync(cancellationToken); //return photos return(new Result { Photos = photos }); }