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.

82 lines
2.3 KiB

3 years ago
  1. package wow.doge.http4sdemo.dto
  2. import java.time.Instant
  3. import io.circe.Printer
  4. import io.circe.generic.semiauto._
  5. import io.scalaland.chimney.dsl._
  6. import org.http4s.EntityEncoder
  7. import org.http4s.circe.streamJsonArrayEncoderWithPrinterOf
  8. import slick.jdbc.JdbcProfile
  9. import wow.doge.http4sdemo.slickcodegen.Tables
  10. final case class Book(
  11. id: Int,
  12. title: String,
  13. authorId: Int,
  14. createdAt: Instant
  15. )
  16. object Book {
  17. def tupled = (Book.apply _).tupled
  18. implicit val ec = deriveCodec[Book]
  19. // implicit def streamEntityEncoder[F[_]]
  20. // : EntityEncoder[F, fs2.Stream[F, Book]] =
  21. // streamJsonArrayEncoderWithPrinterOf(Printer.noSpaces)
  22. def fromBooksRow(row: Tables.BooksRow) = row.transformInto[Book]
  23. def fromBooksTableFn(implicit profile: JdbcProfile) = {
  24. import profile.api._
  25. (b: Tables.Books) => (b.id, b.title, b.authorId, b.createdAt).mapTo[Book]
  26. }
  27. def fromBooksTable(implicit profile: JdbcProfile) =
  28. Tables.Books.map(fromBooksTableFn)
  29. }
  30. final case class NewBook(title: String, authorId: Int)
  31. object NewBook {
  32. def tupled = (NewBook.apply _).tupled
  33. implicit val decoder = deriveDecoder[NewBook]
  34. def fromBooksTable(implicit profile: JdbcProfile) = {
  35. import profile.api._
  36. Tables.Books.map(b => (b.title, b.authorId).mapTo[NewBook])
  37. }
  38. }
  39. final case class BookUpdate(title: Option[String], authorId: Option[Int]) {
  40. import com.softwaremill.quicklens._
  41. def update(row: Tables.BooksRow): Tables.BooksRow =
  42. row
  43. .modify(_.title)
  44. .setToIfDefined(title)
  45. .modify(_.authorId)
  46. .setToIfDefined(authorId)
  47. }
  48. object BookUpdate {
  49. implicit val decoder = deriveDecoder[BookUpdate]
  50. }
  51. final case class Author(id: Int, name: String)
  52. object Author {
  53. def tupled = (Author.apply _).tupled
  54. implicit val codec = deriveCodec[Author]
  55. implicit def streamEntityEncoder[F[_]]
  56. : EntityEncoder[F, fs2.Stream[F, Author]] =
  57. streamJsonArrayEncoderWithPrinterOf(Printer.noSpaces)
  58. }
  59. final case class NewAuthor(name: String)
  60. final case class BookWithAuthor(
  61. id: Int,
  62. title: String,
  63. author: Author,
  64. createdAt: Instant
  65. )
  66. object BookWithAuthor {
  67. def tupled = (BookWithAuthor.apply _).tupled
  68. implicit val codec = deriveCodec[BookWithAuthor]
  69. implicit def streamEntityEncoder[F[_]]
  70. : EntityEncoder[F, fs2.Stream[F, BookWithAuthor]] =
  71. streamJsonArrayEncoderWithPrinterOf(Printer.noSpaces)
  72. }