You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

67 lines
1.9 KiB

4 years ago
4 years ago
  1. package com.example.user.slick.services
  2. import javax.inject._
  3. import scala.concurrent.ExecutionContext
  4. // import slick.jdbc.JdbcProfile
  5. import slick.jdbc.JdbcBackend.Database
  6. import scala.concurrent.Future
  7. import com.example.models._
  8. import com.example.user.slick.dbios.SlickLibraryDbio
  9. import com.example.services.LibraryService
  10. // import slick.jdbc.H2Profile.api._
  11. @Singleton
  12. class SlickLibraryService @Inject() (
  13. db: Database,
  14. libraryDbio: SlickLibraryDbio
  15. )(implicit ec: ExecutionContext)
  16. extends LibraryService {
  17. import libraryDbio.profile.api._
  18. override def getAuthorsForBook(id: Long): Future[Seq[(Author, Book)]] = {
  19. db.run {
  20. libraryDbio
  21. .getAuthorsForBook(id)
  22. .map(_.map {
  23. case (x, y) => {
  24. (libraryDbio.authorsRowToAuthor(x), libraryDbio.booksRowToBooks(y))
  25. }
  26. })
  27. }
  28. }
  29. // Simple function that returns a book
  30. def findBookById(id: Long): Future[Option[Book]] =
  31. db.run(libraryDbio.findBookById(id).map(_.map(libraryDbio.booksRowToBooks)))
  32. // Simple function that returns a list of books with it's author
  33. def findBooksWithAuthor: Future[Seq[(Book, Author)]] =
  34. db.run(libraryDbio.findBooksWithAuthor.map { lst =>
  35. lst.map(tup => {
  36. val (x, y) = tup
  37. (libraryDbio.booksRowToBooks(x), libraryDbio.authorsRowToAuthor(y))
  38. })
  39. })
  40. // Insert a book and an author composing two DBIOs in a transaction
  41. def insertBookAndAuthor(
  42. book: NewBook,
  43. author: NewAuthor
  44. ): Future[(Long, Long)] = {
  45. val action = for {
  46. authorId <- libraryDbio.insertAuthor2(author)
  47. bookId <- libraryDbio.insertBook2(book.copy(authorId = authorId))
  48. } yield (
  49. // libraryDbio.booksRowToBooks(book),
  50. // libraryDbio.authorsRowToAuthor(author)
  51. bookId,
  52. authorId
  53. )
  54. db.run(action.transactionally)
  55. }
  56. def findBookById2(id: Long) =
  57. db.run(libraryDbio.findBookById(id).map(_.map(_.title)))
  58. }
  59. case class Book2(title: String)