thing.go 2.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package mappers
  2. import (
  3. "sort"
  4. "git.dmitriygnatenko.ru/dima/homethings/internal/dto"
  5. "git.dmitriygnatenko.ru/dima/homethings/internal/models"
  6. )
  7. func ToAddThingRequest(req dto.AddThingRequest) models.AddThingRequest {
  8. return models.AddThingRequest{
  9. Title: req.Title,
  10. Description: req.Description,
  11. }
  12. }
  13. func ToUpdateThingRequest(id uint64, req dto.UpdateThingRequest) models.UpdateThingRequest {
  14. return models.UpdateThingRequest{
  15. ID: id,
  16. Title: req.Title,
  17. Description: req.Description,
  18. }
  19. }
  20. func ToAddPlaceThingRequest(thingID uint64, placeID uint64) models.AddPlaceThingRequest {
  21. return models.AddPlaceThingRequest{
  22. PlaceID: placeID,
  23. ThingID: thingID,
  24. }
  25. }
  26. func ToUpdatePlaceThingRequest(thingID uint64, placeID uint64) models.UpdatePlaceThingRequest {
  27. return models.UpdatePlaceThingRequest{
  28. ThingID: thingID,
  29. PlaceID: placeID,
  30. }
  31. }
  32. func ToThingResponse(req models.Thing) dto.ThingResponse {
  33. return dto.ThingResponse{
  34. ID: req.ID,
  35. PlaceID: req.PlaceID,
  36. Title: req.Title,
  37. Description: req.Description,
  38. CreatedAt: req.CreatedAt.Format(defaultDateTimeLayout),
  39. UpdatedAt: req.UpdatedAt.Format(defaultDateTimeLayout),
  40. }
  41. }
  42. func ToThingsResponse(things []models.Thing) dto.ThingsResponse {
  43. res := make([]dto.ThingResponse, 0, len(things))
  44. for _, thing := range things {
  45. res = append(res, ToThingResponse(thing))
  46. }
  47. return dto.ThingsResponse{Things: res}
  48. }
  49. func ToThingsExtResponse(things []models.Thing, tags []models.ThingTag) dto.ThingsExtResponse {
  50. res := make([]dto.ThingExtResponse, 0, len(things))
  51. groupedTags := make(map[uint64][]dto.TagResponse)
  52. for _, tag := range tags {
  53. if _, ok := groupedTags[tag.ThingID]; !ok {
  54. groupedTags[tag.ThingID] = make([]dto.TagResponse, 0)
  55. }
  56. groupedTags[tag.ThingID] = append(groupedTags[tag.ThingID], ThingTagToTagResponse(tag))
  57. }
  58. for _, thing := range things {
  59. var thingTags []dto.TagResponse
  60. if t, ok := groupedTags[thing.ID]; ok {
  61. sort.Slice(t, func(i, j int) bool {
  62. return t[i].Title < t[j].Title
  63. })
  64. thingTags = t
  65. }
  66. res = append(res, dto.ThingExtResponse{
  67. ThingResponse: ToThingResponse(thing),
  68. Tags: thingTags,
  69. })
  70. }
  71. return dto.ThingsExtResponse{Things: res}
  72. }