Exemplo n.º 1
0
        public List <BookResource> GetBooks([FromQuery] int?authorId,
                                            [FromQuery] List <int> bookIds,
                                            [FromQuery] string titleSlug,
                                            [FromQuery] bool includeAllAuthorBooks = false)
        {
            if (!authorId.HasValue && !bookIds.Any() && titleSlug.IsNullOrWhiteSpace())
            {
                var books = _bookService.GetAllBooks();

                var authors  = _authorService.GetAllAuthors().ToDictionary(x => x.AuthorMetadataId);
                var editions = _editionService.GetAllMonitoredEditions().GroupBy(x => x.BookId).ToDictionary(x => x.Key, y => y.ToList());

                foreach (var book in books)
                {
                    book.Author = authors[book.AuthorMetadataId];
                    if (editions.TryGetValue(book.Id, out var bookEditions))
                    {
                        book.Editions = bookEditions;
                    }
                    else
                    {
                        book.Editions = new List <Edition>();
                    }
                }

                return(MapToResource(books, false));
            }

            if (authorId.HasValue)
            {
                var books = _bookService.GetBooksByAuthor(authorId.Value);

                var author   = _authorService.GetAuthor(authorId.Value);
                var editions = _editionService.GetEditionsByAuthor(authorId.Value)
                               .GroupBy(x => x.BookId)
                               .ToDictionary(x => x.Key, y => y.ToList());

                foreach (var book in books)
                {
                    book.Author = author;
                    if (editions.TryGetValue(book.Id, out var bookEditions))
                    {
                        book.Editions = bookEditions;
                    }
                    else
                    {
                        book.Editions = new List <Edition>();
                    }
                }

                return(MapToResource(books, false));
            }

            if (titleSlug.IsNotNullOrWhiteSpace())
            {
                var book = _bookService.FindBySlug(titleSlug);

                if (book == null)
                {
                    return(MapToResource(new List <Book>(), false));
                }

                if (includeAllAuthorBooks)
                {
                    return(MapToResource(_bookService.GetBooksByAuthor(book.AuthorId), false));
                }
                else
                {
                    return(MapToResource(new List <Book> {
                        book
                    }, false));
                }
            }

            return(MapToResource(_bookService.GetBooks(bookIds), false));
        }