product_variant.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687
  1. package helper
  2. import (
  3. "fmt"
  4. "github.com/gshopify/service-wrapper/fun"
  5. "github.com/gshopify/service-wrapper/model"
  6. "gshopper.com/gshopify/products/graphql/generated"
  7. "sort"
  8. )
  9. func NewProductVariantConnection(src []*generated.ProductVariant,
  10. after *string, before *string, first *int, last *int, reverse *bool, sortKey *generated.ProductVariantSortKeys) (*generated.ProductVariantConnection, error) {
  11. var (
  12. connection = &generated.ProductVariantConnection{}
  13. err error
  14. )
  15. if len(src) == 0 {
  16. return connection, nil
  17. }
  18. if sortKey != nil && sortKey.IsValid() {
  19. sort.Slice(src[:], func(i, j int) bool {
  20. switch *sortKey {
  21. case generated.ProductVariantSortKeysID:
  22. return src[i].ID < src[j].ID
  23. case generated.ProductVariantSortKeysTitle:
  24. return src[i].Title < src[j].Title
  25. case generated.ProductVariantSortKeysSku:
  26. var isku, jsku string
  27. if src[i].Sku != nil {
  28. isku = *src[i].Sku
  29. }
  30. if src[j].Sku != nil {
  31. jsku = *src[j].Sku
  32. }
  33. return isku < jsku
  34. case generated.ProductVariantSortKeysPosition:
  35. return ExtractMetaPosition(model.GidVariant, src[i].Metafields) <
  36. ExtractMetaPosition(model.GidVariant, src[j].Metafields)
  37. case generated.ProductVariantSortKeysRelevance: // TODO:
  38. }
  39. return false
  40. })
  41. }
  42. if reverse != nil && *reverse {
  43. src = fun.Reverse(src)
  44. }
  45. connection.Nodes = src[:]
  46. connection.Nodes = fun.First(connection.Nodes, first)
  47. connection.Nodes = fun.Last(connection.Nodes, last)
  48. connection.Nodes, err = fun.WithCursor(connection.Nodes, after, model.GidVariant, true)
  49. if err != nil {
  50. return nil, fmt.Errorf("illegal cursor: %s", *after)
  51. }
  52. connection.Nodes, err = fun.WithCursor(connection.Nodes, before, model.GidVariant, false)
  53. if err != nil {
  54. return nil, fmt.Errorf("illegal cursor: %s", *before)
  55. }
  56. connection.PageInfo = model.NewPageInfo(connection.Nodes, model.GidVariant, src[0], src[len(src)-1])
  57. // Edges
  58. for i := range connection.Nodes {
  59. e := &generated.ProductVariantEdge{
  60. Node: connection.Nodes[i],
  61. }
  62. if c, err := model.NewCursor(e.Node.ID, model.GidVariant); err == nil {
  63. e.Cursor = *c.String()
  64. }
  65. connection.Edges = append(connection.Edges, e)
  66. }
  67. return connection, nil
  68. }