Przeglądaj źródła

ProductConnection

- implement sorts: id, title, created_at, price
Alexey Kim 2 lat temu
rodzic
commit
5bcaf6e463
2 zmienionych plików z 24 dodań i 2 usunięć
  1. 23 1
      graphql/helper/product.go
  2. 1 1
      graphql/query_product.go

+ 23 - 1
graphql/helper/product.go

@@ -5,10 +5,11 @@ import (
 	"github.com/gshopify/service-wrapper/fun"
 	"github.com/gshopify/service-wrapper/model"
 	"gshopper.com/gshopify/products/graphql/generated"
+	"sort"
 )
 
 func NewProductConnection(src []*generated.Product,
-	after *string, before *string, first *int, last *int, reverse *bool) (*generated.ProductConnection, error) {
+	after *string, before *string, first *int, last *int, reverse *bool, sortKey *generated.ProductCollectionSortKeys) (*generated.ProductConnection, error) {
 	var (
 		connection = &generated.ProductConnection{}
 		err        error
@@ -22,6 +23,27 @@ func NewProductConnection(src []*generated.Product,
 		src = fun.Reverse(src)
 	}
 
+	//TODO: ProductCollectionSortKeysBestSelling
+	//TODO: ProductCollectionSortKeysCollectionDefault
+	//TODO: ProductCollectionSortKeysManual
+	//TODO: ProductCollectionSortKeysRelevance
+	if sortKey != nil && sortKey.IsValid() {
+		sort.Slice(src[:], func(i, j int) bool {
+			switch *sortKey {
+			case generated.ProductCollectionSortKeysID:
+				return src[i].ID < src[j].ID
+			case generated.ProductCollectionSortKeysTitle:
+				return src[i].Title < src[j].Title
+			case generated.ProductCollectionSortKeysCreated:
+				return src[i].CreatedAt < src[j].CreatedAt
+			case generated.ProductCollectionSortKeysPrice:
+				return src[i].PriceRange.MinVariantPrice.Amount < src[j].PriceRange.MinVariantPrice.Amount
+			}
+
+			return false
+		})
+	}
+
 	connection.Nodes = src[:]
 	connection.Nodes = fun.First(connection.Nodes, first)
 	connection.Nodes = fun.Last(connection.Nodes, last)

+ 1 - 1
graphql/query_product.go

@@ -72,7 +72,7 @@ func (r *collectionResolver) Products(ctx context.Context, collection *generated
 		return nil, err
 	}
 
-	return helper.NewProductConnection(products, after, before, first, last, reverse)
+	return helper.NewProductConnection(products, after, before, first, last, reverse, sort)
 }
 
 func (r *productResolver) Options(ctx context.Context, product *generated.Product, first *int) ([]*generated.ProductOption, error) {