Browse Source

NewProductVariantConnection

- add
Alexey Kim 2 years ago
parent
commit
096d49501a
1 changed files with 85 additions and 0 deletions
  1. 85 0
      graphql/helper/product_variant.go

+ 85 - 0
graphql/helper/product_variant.go

@@ -0,0 +1,85 @@
+package helper
+
+import (
+	"fmt"
+	"github.com/gshopify/service-wrapper/fun"
+	"github.com/gshopify/service-wrapper/model"
+	"gshopper.com/gshopify/products/graphql/generated"
+	"sort"
+)
+
+func NewProductVariantConnection(src []*generated.ProductVariant,
+	after *string, before *string, first *int, last *int, reverse *bool, sortKey *generated.ProductVariantSortKeys) (*generated.ProductVariantConnection, error) {
+
+	var (
+		connection = &generated.ProductVariantConnection{}
+		err        error
+	)
+
+	if len(src) == 0 {
+		return connection, nil
+	}
+
+	if sortKey != nil && sortKey.IsValid() {
+		sort.Slice(src[:], func(i, j int) bool {
+
+			switch *sortKey {
+			case generated.ProductVariantSortKeysID:
+				return src[i].ID < src[j].ID
+			case generated.ProductVariantSortKeysTitle:
+				return src[i].Title < src[j].Title
+			case generated.ProductVariantSortKeysSku:
+				var isku, jsku string
+
+				if src[i].Sku != nil {
+					isku = *src[i].Sku
+				}
+
+				if src[j].Sku != nil {
+					jsku = *src[j].Sku
+				}
+
+				return isku < jsku
+			case generated.ProductVariantSortKeysPosition: // TODO:
+			case generated.ProductVariantSortKeysRelevance: // TODO:
+			}
+
+			return false
+		})
+	}
+
+	if reverse != nil && *reverse {
+		src = fun.Reverse(src)
+	}
+
+	connection.Nodes = src[:]
+	connection.Nodes = fun.First(connection.Nodes, first)
+	connection.Nodes = fun.Last(connection.Nodes, last)
+
+	connection.Nodes, err = fun.WithCursor(connection.Nodes, after, model.GidVariant, true)
+	if err != nil {
+		return nil, fmt.Errorf("illegal cursor: %s", *after)
+	}
+
+	connection.Nodes, err = fun.WithCursor(connection.Nodes, before, model.GidVariant, false)
+	if err != nil {
+		return nil, fmt.Errorf("illegal cursor: %s", *before)
+	}
+
+	connection.PageInfo = model.NewPageInfo(connection.Nodes, model.GidVariant, src[0], src[len(src)-1])
+
+	// Edges
+	for i := range connection.Nodes {
+		e := &generated.ProductVariantEdge{
+			Node: connection.Nodes[i],
+		}
+
+		if c, err := model.NewSimpleCursor(e.Node.ID, model.GidVariant); err == nil {
+			e.Cursor = *c.String()
+		}
+
+		connection.Edges = append(connection.Edges, e)
+	}
+
+	return connection, nil
+}