product_variant.go 2.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485
  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: // TODO:
  35. case generated.ProductVariantSortKeysRelevance: // TODO:
  36. }
  37. return false
  38. })
  39. }
  40. if reverse != nil && *reverse {
  41. src = fun.Reverse(src)
  42. }
  43. connection.Nodes = src[:]
  44. connection.Nodes = fun.First(connection.Nodes, first)
  45. connection.Nodes = fun.Last(connection.Nodes, last)
  46. connection.Nodes, err = fun.WithCursor(connection.Nodes, after, model.GidVariant, true)
  47. if err != nil {
  48. return nil, fmt.Errorf("illegal cursor: %s", *after)
  49. }
  50. connection.Nodes, err = fun.WithCursor(connection.Nodes, before, model.GidVariant, false)
  51. if err != nil {
  52. return nil, fmt.Errorf("illegal cursor: %s", *before)
  53. }
  54. connection.PageInfo = model.NewPageInfo(connection.Nodes, model.GidVariant, src[0], src[len(src)-1])
  55. // Edges
  56. for i := range connection.Nodes {
  57. e := &generated.ProductVariantEdge{
  58. Node: connection.Nodes[i],
  59. }
  60. if c, err := model.NewSimpleCursor(e.Node.ID, model.GidVariant); err == nil {
  61. e.Cursor = *c.String()
  62. }
  63. connection.Edges = append(connection.Edges, e)
  64. }
  65. return connection, nil
  66. }