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