/// <summary> /// /// </summary> /// <param name="openLibraryId"></param> /// <returns></returns> public async Task <OpenLibraryBook?> GetBook(string openLibraryId) { return(await this.cache.GetOrCreateAsync($"OL-BOOK-{openLibraryId}", async (_) => { try { openLibraryId = openLibraryId.Replace("/works/", ""); using HttpClient client = this.clientFactory.CreateClient(); HttpResponseMessage response = await client.GetAsync($"{baseUrl}/works/{openLibraryId}.json"); if (!response.IsSuccessStatusCode) { return null; } string responseString = await response.Content.ReadAsStringAsync(); OpenLibraryBook book = JsonConvert.DeserializeObject <OpenLibraryBook>(responseString); book.Authors = (await book.AuthorsKeys.SelectAsync(async(author) => await this.GetAuthor(author.Author.Key))) .Where(a => a != null) .ToList() !; return book; } catch { return null; } })); }
/// <summary> /// Creates a post from a model /// </summary> /// <param name="postModel">The model for creation</param> /// <returns> /// The newly created post as a PostModel /// </returns> public async Task <PostModel> CreatePost(AuthUserModel authUser, PostModel postModel, OpenLibraryService openLibraryService) { // Get the information OpenLibraryBook opBook = await openLibraryService.GetBookInformation(postModel.ISBN); // Determine how to handle author string author = null; if (opBook == null) { throw new ArgumentException("This is an invalid ISBN, please try again using a correct number"); } else { if (opBook.by_statement == null && opBook.authors != null) { // Get the author statement OpenLibraryAuthor opauthor = await openLibraryService.GetAuthorInformation(opBook.authors.FirstOrDefault().key); if (opauthor != null) { author = opauthor.name; } } else { author = opBook.by_statement; } Post post = new Post { Title = postModel.Title, Body = postModel.Body, Posted_At = DateTime.Now, Posted_ById = authUser.Id, ISBN = postModel.ISBN, BookTitle = opBook.title, WorksId = opBook.works.FirstOrDefault()?.key.Replace("/works/", ""), Author = author }; context.Posts.Add(post); context.SaveChanges(); return(this.GetPost(post.Id, null)); } }