12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576 |
- package helper
- import (
- "fmt"
- "github.com/gshopify/service-wrapper/fun"
- "github.com/gshopify/service-wrapper/model"
- "gshopper.com/gshopify/products/graphql/generated"
- "sort"
- )
- func NewCollectionConnection(src []*generated.Collection,
- after *string, before *string, first *int, last *int, reverse *bool) (*generated.CollectionConnection, error) {
- var (
- connection = &generated.CollectionConnection{}
- err error
- )
- if len(src) == 0 {
- return connection, nil
- }
- 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)
- if connection.Nodes, err = fun.WithCursor(connection.Nodes, after, model.GidCollection, true); err != nil {
- return nil, fmt.Errorf("illegal cursor: %s", *after)
- }
- if connection.Nodes, err = fun.WithCursor(connection.Nodes, before, model.GidCollection, false); err != nil {
- return nil, fmt.Errorf("illegal cursor: %s", *before)
- }
- connection.PageInfo = model.NewPageInfo(connection.Nodes, model.GidCollection, src[0], src[len(src)-1])
- // Edges
- for i := range connection.Nodes {
- e := &generated.CollectionEdge{
- Node: connection.Nodes[i],
- }
- if c, err := model.NewCursor(e.Node.ID, model.GidCollection); err == nil {
- e.Cursor = *c.String()
- }
- connection.Edges = append(connection.Edges, e)
- }
- return connection, nil
- }
- // SortCollections TODO: CollectionSortKeysRelevance
- func SortCollections(src []*generated.Collection, sortKey *generated.CollectionSortKeys) []*generated.Collection {
- if sortKey == nil || !sortKey.IsValid() {
- return src[:]
- }
- sort.Slice(src[:], func(i, j int) bool {
- switch *sortKey {
- case generated.CollectionSortKeysID:
- return src[i].ID < src[j].ID
- case generated.CollectionSortKeysTitle:
- return src[i].Title < src[j].Title
- case generated.CollectionSortKeysUpdatedAt:
- return src[i].UpdatedAt < src[j].UpdatedAt
- }
- return false
- })
- return src[:]
- }
|