product.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  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 NewProductConnection(src []*generated.Product,
  10. after *string, before *string, first *int, last *int, reverse *bool, sortKey *generated.ProductCollectionSortKeys) (*generated.ProductConnection, error) {
  11. var (
  12. connection = &generated.ProductConnection{}
  13. err error
  14. )
  15. if len(src) == 0 {
  16. return connection, nil
  17. }
  18. if reverse != nil && *reverse {
  19. src = fun.Reverse(src)
  20. }
  21. //TODO: ProductCollectionSortKeysBestSelling
  22. //TODO: ProductCollectionSortKeysCollectionDefault
  23. //TODO: ProductCollectionSortKeysManual
  24. //TODO: ProductCollectionSortKeysRelevance
  25. if sortKey != nil && sortKey.IsValid() {
  26. sort.Slice(src[:], func(i, j int) bool {
  27. switch *sortKey {
  28. case generated.ProductCollectionSortKeysID:
  29. return src[i].ID < src[j].ID
  30. case generated.ProductCollectionSortKeysTitle:
  31. return src[i].Title < src[j].Title
  32. case generated.ProductCollectionSortKeysCreated:
  33. return src[i].CreatedAt < src[j].CreatedAt
  34. case generated.ProductCollectionSortKeysPrice:
  35. return src[i].PriceRange.MinVariantPrice.Amount < src[j].PriceRange.MinVariantPrice.Amount
  36. }
  37. return false
  38. })
  39. }
  40. connection.Nodes = src[:]
  41. connection.Nodes = fun.First(connection.Nodes, first)
  42. connection.Nodes = fun.Last(connection.Nodes, last)
  43. connection.Nodes, err = fun.WithCursor(connection.Nodes, after, model.GidProduct, true)
  44. if err != nil {
  45. return nil, fmt.Errorf("illegal cursor: %s", *after)
  46. }
  47. connection.Nodes, err = fun.WithCursor(connection.Nodes, before, model.GidProduct, false)
  48. if err != nil {
  49. return nil, fmt.Errorf("illegal cursor: %s", *before)
  50. }
  51. connection.PageInfo = model.NewPageInfo(connection.Nodes, model.GidProduct, src[0], src[len(src)-1])
  52. // Edges
  53. for i := range connection.Nodes {
  54. e := &generated.ProductEdge{
  55. Node: connection.Nodes[i],
  56. }
  57. if c, err := model.NewSimpleCursor(e.Node.ID, model.GidProduct); err == nil {
  58. e.Cursor = *c.String()
  59. }
  60. connection.Edges = append(connection.Edges, e)
  61. }
  62. return connection, nil
  63. }