connection.go 2.3 KB

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