123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687 |
- 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:
- return ExtractMetaPosition(model.GidVariant, src[i].Metafields) <
- ExtractMetaPosition(model.GidVariant, src[j].Metafields)
- 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.NewCursor(e.Node.ID, model.GidVariant); err == nil {
- e.Cursor = *c.String()
- }
- connection.Edges = append(connection.Edges, e)
- }
- return connection, nil
- }
|