Exemple #1
0
        public async Task <Payload <Book> > AddBookByIsbnAsync(
            AddBookByIsbnInput input,
            [Service] IGetClaimsProvider claimsProvider,
            [Service] IBookApiService apiService,
            [ScopedService] BookRefDbContext context)
        {
            if (context.Books.Any(e => e.Identifier == input.Isbn))
            {
                return(new Payload <Book>(BuildSingleError(new BookException($"Book with isbn '{input.Isbn}' already in database."))));
            }
            var apiResult = apiService.FindBook(input.Isbn);

            if (apiResult.IsNone)
            {
                return(new Payload <Book>(BuildSingleError(new BookException($"{input.Isbn} not found in service"))));
            }

            apiResult = new BookService().MatchAuthors(context.Authors.ToList(), apiResult);

            var book = apiResult.IfNone(new Book("", "", ""));

            var validationResult = new BookValidator().Validate(book);

            if (!validationResult.IsValid)
            {
                return(new Payload <Book>(BuildErrorList(validationResult.Errors)));
            }


            context.Books.Add(book);
            await context.SaveChangesAsync();

            return(new Payload <Book>(book));
        }
Exemple #2
0
        public static IHost MigrateDatabase(
            this IHost webHost)
        {
            using var scope = webHost.Services.CreateScope();
            var appContextFactory = scope.ServiceProvider.GetRequiredService <IDbContextFactory <BookRefDbContext> >();
            var service           = scope.ServiceProvider.GetRequiredService <IBookApiService>();

            using BookRefDbContext dbContext =
                      appContextFactory.CreateDbContext();
            //var repository = scope.ServiceProvider.GetRequiredService<AggregateRepository>();
            try
            {
                var env = scope.ServiceProvider.GetRequiredService <IWebHostEnvironment>();
                dbContext.Database.EnsureCreated();
                if (env.IsProduction())
                {
                    // not working with in memory dbs
                    dbContext.Database.Migrate();
                }

                if (!dbContext.Books.Any())
                {
                    var task = Task.Run(async() => await new SampleDataSeeder(dbContext, service).SeedAll());
                    task.GetAwaiter().GetResult();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                //Log errors or do anything you think it's needed
                throw;
            }

            return(webHost);
        }
Exemple #3
0
        //private readonly AggregateRepository _repository;

        public SampleDataSeeder(
            BookRefDbContext context,
            IBookApiService service)
        {
            _context = context;
            _service = service;
            //_repository = repository;
        }
 protected override async Task <IReadOnlyDictionary <long, BookRecommedation> > LoadBatchAsync(
     IReadOnlyList <long> keys,
     CancellationToken cancellationToken)
 {
     await using BookRefDbContext dbContext =
                     _dbContextFactory.CreateDbContext();
     return(await dbContext.BookRecommedations
            .Where(s => keys.Contains(s.Id))
            .ToDictionaryAsync(t => t.Id, cancellationToken));
 }
Exemple #5
0
        public async Task <Payload <bool> > RemoveAsync(
            RemoveFromLibraryInput input,
            [ScopedService] BookRefDbContext context,
            [Service] IGetClaimsProvider claimsProvider)
        {
            var library = context.Libraries.First(e => e.Id == claimsProvider.LibraryId);
            var pl      = library.RemoveBook(input.PersonalBookId);

            await context.SaveChangesAsync();

            return(new Payload <bool>(true));
        }
Exemple #6
0
        public async Task <Payload <BookRecommedation> > UpdateNoteAsync(
            UpdateNoteInput input,
            [ScopedService] BookRefDbContext context,
            [Service] IGetClaimsProvider claimsProvider)
        {
            var library       = context.Libraries.First(e => e.Id == claimsProvider.LibraryId);
            var recommedation = library.UpdateRecommendationNote(input.noteId, input.content);

            await context.SaveChangesAsync();

            return(new Payload <BookRecommedation>(recommedation));
        }
Exemple #7
0
        public async Task <Payload <PersonalBook> > ChangeColorCodeAsync(
            ChangeColorCodeInput input,
            [ScopedService] BookRefDbContext context,
            [Service] IGetClaimsProvider claimsProvider)
        {
            var library = context.Libraries.First(e => e.Id == claimsProvider.LibraryId);
            var pb      = library.ChangeColorCode(input.PersonalBookId, input.ColorCode);

            await context.SaveChangesAsync();

            return(new Payload <PersonalBook>(pb));
        }
Exemple #8
0
        public async Task <Payload <Book> > AddAuthorAsync(
            AddExistingAuthorInput input,
            [ScopedService] BookRefDbContext context)
        {
            var book   = context.Books.Find(input.BookId);
            var author = context.Authors.Find(input.AuthorId);

            book.AddAuthor(author);

            await context.SaveChangesAsync();

            return(new Payload <Book>(book));
        }
Exemple #9
0
            public async Task <IEnumerable <Book> > GetBooksAsync(
                Category category,
                [ScopedService] BookRefDbContext dbContext,
                BookByIdDataLoader bookById,
                CancellationToken cancellationToken)
            {
                long[] bookIds = await dbContext.Categories
                                 .Where(s => s.Id == category.Id)
                                 .SelectMany(s => s.BookCategories.Select(t => t.BookId))
                                 .ToArrayAsync();

                return(await bookById.LoadAsync(bookIds, cancellationToken));
            }
Exemple #10
0
            public async Task <IEnumerable <Book> > GetBooksAsync(
                Author author,
                [ScopedService] BookRefDbContext dbContext,
                BookByIdDataLoader bookById,
                CancellationToken cancellationToken)
            {
                long[] bookIds = await dbContext.Books
                                 .Where(s => s.Id == author.Id)
                                 .Select(s => s.Id)
                                 .ToArrayAsync();

                return(await bookById.LoadAsync(bookIds, cancellationToken));
            }
Exemple #11
0
        public async Task <IQueryable <PersonalBook> > GetBooksAsync(
            PersonalBookByIdDataLoader dataLoader,
            [Service] IGetClaimsProvider claimsProvider,
            [ScopedService] BookRefDbContext context,
            CancellationToken cancellationToken)
        {
            var ids = context.Libraries
                      .Include(e => e.MyBooks)
                      .First(e => e.Id == claimsProvider.LibraryId)
                      .MyBooks.Select(e => e.Id);

            return((await dataLoader.LoadAsync(ids.ToArray(), cancellationToken)).AsQueryable());
        }
Exemple #12
0
        public async Task <Payload <Book> > RemoveCategoryAsync(
            RemoveCategoryInput input,
            [ScopedService] BookRefDbContext context)
        {
            // Primary remove check
            var book     = context.Books.Find(input.BookId);
            var category = context.Categories.Find(input.CategoryId);

            book.RemoveCategory(category);

            await context.SaveChangesAsync();

            return(new Payload <Book>(book));
        }
Exemple #13
0
        public async Task <MyRecommendations> GetRecommendationsForBook(
            [ID(nameof(Book))] long id,
            BookByIdDataLoader dataLoader,
            [Service] IGetClaimsProvider claimsProvider,
            [ScopedService] BookRefDbContext context,
            CancellationToken cancellationToken)
        {
            var library = context.Libraries
                          .First(e => e.Id == claimsProvider.LibraryId);
            var result = new MyRecommendations();
            var source = await dataLoader.LoadAsync(id, cancellationToken);

            result.SourceBook           = source;
            result.BookRecommedations   = library.BookRecommedations.Where(e => e.SourceBookId == source.Id).ToList();
            result.PersonRecommedations = library.PersonRecommedations.Where(e => e.SourceBookId == source.Id).ToList();
            return(result);
        }
Exemple #14
0
        public async Task <Payload <Book> > AddBookAsync(
            AddBookInput input,
            [Service] IGetClaimsProvider claimsProvider,
            [ScopedService] BookRefDbContext context)
        {
            var book = new Book(input.Identifier, input.Title, claimsProvider.Username)
            {
                Subtitle = input.Subtitle
            };
            var validationResult = new BookValidator().Validate(book);

            if (!validationResult.IsValid)
            {
                return(new Payload <Book>(BuildErrorList(validationResult.Errors)));
            }

            context.Books.Add(book);
            await context.SaveChangesAsync();

            return(new Payload <Book>(book));
        }
Exemple #15
0
        public async Task <Payload <PersonalBook> > MoveBookInLibraryAsync(
            MoveBookToLibraryInput input,
            [ScopedService] BookRefDbContext context,
            [Service] IGetClaimsProvider claimsProvider)
        {
            var library = context.Libraries.First(e => e.Id == claimsProvider.LibraryId);
            var book    = context.Books.Find(input.BookId);

            try
            {
                library.AddNewBook(book, input.Status, input.ColorCode);
            }
            catch (LibraryException ex)
            {
                return(new Payload <PersonalBook>(BuildSingleError(ex)));
            }

            await context.SaveChangesAsync();

            return(new Payload <PersonalBook>(library.MyBooks.Last()));
        }
Exemple #16
0
        public async Task <Payload <Guid> > NewUserAsync(
            NewUserInput input,
            [ScopedService] BookRefDbContext context)
        {
            if (context.Users.Any(e => e.Username.ToLower() == input.Username))
            {
                return(new Payload <Guid>(PayloadHelper.BuildSingleError(new Exception("Username already taken"))));
            }

            var user = new User(input.Username, input.Email);

            user.SetPassword(input.Password);
            await context.Users.AddAsync(user);

            var library = new PersonalLibrary(Guid.NewGuid(), user);
            await context.Libraries.AddAsync(library);

            await context.SaveChangesAsync();

            return(new Payload <Guid>(library.Id));
        }
Exemple #17
0
        public async Task <Payload <Book> > AddCategoryAsync(
            AddCategoryInput input,
            [ScopedService] BookRefDbContext context)
        {
            // Primary checks
            var book     = context.Books.Find(input.BookId);
            var category = context.Categories.Find(input.CategoryId);

            try
            {
                book.AddCategory(category, input.IsPrimary);
            }
            catch (System.Exception ex)
            {
                return(new Payload <Book>(BuildSingleError(ex)));
            }

            await context.SaveChangesAsync();

            return(new Payload <Book>(book));
        }
Exemple #18
0
        public async Task <Payload <PersonRecommedation> > AddPersonRecommendationAsync(
            AddPersonRecommendationInput input,
            [ScopedService] BookRefDbContext context,
            [Service] IGetClaimsProvider claimsProvider)
        {
            var library = context.Libraries.First(e => e.Id == claimsProvider.LibraryId);
            var source  = context.Books.First(e => e.Id == input.SourceBookId);
            var target  = context.Authors.First(e => e.Id == input.TargetPersonId);

            try
            {
                library.AddPersonRecommendation(source, target, input.Note != null ? input.Note : "");
            }
            catch (LibraryException ex)
            {
                return(new Payload <PersonRecommedation>(BuildSingleError(ex)));
            }

            await context.SaveChangesAsync();

            return(new Payload <PersonRecommedation>(library.PersonRecommedations.Last()));
        }
Exemple #19
0
        public async Task <Payload <string> > SingInAsync(
            SingInInput input,
            [ScopedService] BookRefDbContext context)
        {
            var user = context.Users.FirstOrDefault(e => e.Username == input.Username);

            if (user is null)
            {
                Log.Information("User '{Username}' not found in database", input.Username);
                return(new Payload <string>(PayloadHelper.BuildSingleError(new Exception("Bad username or password"))));
            }


            var isValid = BCrypt.Net.BCrypt.Verify(input.Password, user.Password);

            if (!isValid)
            {
                Log.Information("Password from user '{Username}' is not valid", input.Username);
                return(new Payload <string>(PayloadHelper.BuildSingleError(new Exception("Bad username or password"))));
            }


            return(new Payload <string>(BuildToken(user.Username, user.PersonalLibraryId)));
        }
Exemple #20
0
 public IQueryable <Book> GetAllBooks(
     [ScopedService] BookRefDbContext context) =>
 context.Books;
Exemple #21
0
 public Task <List <Category> > GetCategoriesAsync([ScopedService] BookRefDbContext context) =>
 context.Categories.ToListAsync();
Exemple #22
0
 public Task <List <Speaker> > GetSpeakersAsync([ScopedService] BookRefDbContext context) =>
 context.Speakers.ToListAsync();
Exemple #23
0
 public Task <List <Author> > GetAuthorsAsync(
     [ScopedService] BookRefDbContext context) =>
 context.Authors.ToListAsync();
Exemple #24
0
 public Task <List <PersonRecommedation> > GetPeopleRecommendationsForBook(
     [ID(nameof(Book))] long id,
     [ScopedService] BookRefDbContext context) =>
 context.PersonRecommedations.Where(e => e.SourceBookId == id).ToListAsync();
Exemple #25
0
 public Task <List <PersonRecommedation> > GetPeopleRecommendations(
     [ScopedService] BookRefDbContext context) =>
 context.PersonRecommedations.ToListAsync();
Exemple #26
0
 public Task <List <BookRecommedation> > GetAllBookRecommendations(
     [ScopedService] BookRefDbContext context) =>
 context.BookRecommedations.ToListAsync();
Exemple #27
0
 public static void InitializeDbForTests(
     BookRefDbContext _context)
 {
 }
Exemple #28
0
 public ApiHealthCheck(
     BookRefDbContext ctx) =>