connection.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293
  1. package model
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. "git.beejay.kim/Craft/Api/connection"
  6. "github.com/samber/lo"
  7. "math"
  8. )
  9. type Connection[T connection.Cursor] struct {
  10. Edges []T `json:"edges"`
  11. PageInfo *PageInfo `json:"page_info"`
  12. }
  13. func (c *Connection[T]) Reverse() {
  14. c.Edges = lo.Reverse[T](c.Edges)
  15. }
  16. func (c *Connection[T]) Grain(after, before *string) error {
  17. if after != nil && before != nil {
  18. return fmt.Errorf("illegal agruments: only one of `after` or `before` can be used at a time")
  19. }
  20. if len(c.Edges) == 0 {
  21. c.PageInfo = &PageInfo{}
  22. return nil
  23. }
  24. edges := lo.FlatMap[T, string](c.Edges, func(item T, _ int) []string {
  25. return []string{item.Cursor()}
  26. })
  27. c.PageInfo = &PageInfo{
  28. StartCursor: lo.ToPtr(edges[0]),
  29. EndCursor: lo.ToPtr(edges[(len(edges) - 1)]),
  30. }
  31. if after != nil {
  32. if idx := lo.IndexOf(edges, *after); idx != -1 {
  33. c.Edges = lo.Slice[T](c.Edges, idx+1, math.MaxUint32)
  34. }
  35. }
  36. if before != nil {
  37. if idx := lo.IndexOf(edges, *before); idx != -1 {
  38. c.Edges = lo.Subset[T](c.Edges, -idx, math.MaxUint32)
  39. }
  40. }
  41. return nil
  42. }
  43. func (c *Connection[T]) Slice(first, last *int) error {
  44. if first != nil && last != nil {
  45. return fmt.Errorf("illegal agruments: only one of `first` or `last` can be used at a time")
  46. }
  47. if first != nil {
  48. c.Edges = lo.Slice[T](c.Edges, 0, *first)
  49. }
  50. if last != nil {
  51. c.Edges = lo.Subset[T](c.Edges, -*last, math.MaxUint32)
  52. }
  53. if len(c.Edges) < 1 {
  54. c.PageInfo.HasPreviousPage = c.PageInfo.StartCursor != nil
  55. c.PageInfo.HasNextPage = c.PageInfo.EndCursor != nil
  56. c.PageInfo.StartCursor = nil
  57. c.PageInfo.EndCursor = nil
  58. } else {
  59. c.PageInfo.HasPreviousPage = !(*c.PageInfo.StartCursor == c.Edges[0].Cursor())
  60. c.PageInfo.HasNextPage = !(*c.PageInfo.EndCursor == c.Edges[len(c.Edges)-1].Cursor())
  61. c.PageInfo.StartCursor = lo.ToPtr(c.Edges[0].Cursor())
  62. c.PageInfo.EndCursor = lo.ToPtr(c.Edges[len(c.Edges)-1].Cursor())
  63. }
  64. return nil
  65. }
  66. func (c Connection[T]) Marshal() ([]byte, error) {
  67. return json.Marshal(c.Edges)
  68. }
  69. func (c *Connection[T]) Unmarshal(data []byte) error {
  70. return json.Unmarshal(data, &c.Edges)
  71. }
  72. func (c Connection[T]) Key() string {
  73. var zero []T
  74. return fmt.Sprintf("connection-edges-%T", zero)
  75. }