1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- package helper
- import (
- "fmt"
- "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, sortKey *generated.ProductCollectionSortKeys) (*generated.ProductConnection, error) {
- var (
- connection = &generated.ProductConnection{}
- err error
- )
- if len(src) == 0 {
- return connection, nil
- }
- if reverse != nil && *reverse {
- 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)
- connection.Nodes, err = fun.WithCursor(connection.Nodes, after, model.GidProduct, true)
- if err != nil {
- return nil, fmt.Errorf("illegal cursor: %s", *after)
- }
- connection.Nodes, err = fun.WithCursor(connection.Nodes, before, model.GidProduct, false)
- if err != nil {
- return nil, fmt.Errorf("illegal cursor: %s", *before)
- }
- connection.PageInfo = model.NewPageInfo(connection.Nodes, model.GidProduct, src[0], src[len(src)-1])
- // Edges
- for i := range connection.Nodes {
- e := &generated.ProductEdge{
- Node: connection.Nodes[i],
- }
- if c, err := model.NewSimpleCursor(e.Node.ID, model.GidProduct); err == nil {
- e.Cursor = *c.String()
- }
- connection.Edges = append(connection.Edges, e)
- }
- return connection, nil
- }
|