forked from bold-commerce/go-shopify
-
Notifications
You must be signed in to change notification settings - Fork 0
/
collection.go
82 lines (69 loc) · 2.63 KB
/
collection.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package goshopify
import (
"fmt"
"net/http"
"time"
)
const collectionsBasePath = "collections"
// CollectionService is an interface for interfacing with the collection endpoints
// of the Shopify API.
// See: https://help.shopify.com/api/reference/products/collection
type CollectionService interface {
Get(collectionID int64, options interface{}) (*Collection, error)
ListProducts(collectionID int64, options interface{}) ([]Product, error)
ListProductsWithPagination(collectionID int64,options interface{}) ([]Product, *Pagination, error)
}
// CollectionServiceOp handles communication with the collection related methods of
// the Shopify API.
type CollectionServiceOp struct {
client *Client
}
// Collection represents a Shopify collection
type Collection struct {
ID int64 `json:"id"`
Handle string `json:"handle"`
Title string `json:"title"`
UpdatedAt *time.Time `json:"updated_at"`
BodyHTML string `json:"body_html"`
SortOrder string `json:"sort_order"`
TemplateSuffix string `json:"template_suffix"`
Image Image `json:"image"`
PublishedAt *time.Time `json:"published_at"`
PublishedScope string `json:"published_scope"`
}
// Represents the result from the collections/X.json endpoint
type CollectionResource struct {
Collection *Collection `json:"collection"`
}
// Get individual collection
func (s *CollectionServiceOp) Get(collectionID int64, options interface{}) (*Collection, error) {
path := fmt.Sprintf("%s/%d.json", collectionsBasePath, collectionID)
resource := new(CollectionResource)
err := s.client.Get(path, resource, options)
return resource.Collection, err
}
// List products for a collection
func (s *CollectionServiceOp) ListProducts(collectionID int64, options interface{}) ([]Product, error) {
products, _, err := s.ListProductsWithPagination(collectionID, options)
if err != nil {
return nil, err
}
return products, nil
}
// List products for a collection and return pagination to retrieve next/previous results.
func (s *CollectionServiceOp) ListProductsWithPagination(collectionID int64,options interface{}) ([]Product, *Pagination, error) {
path := fmt.Sprintf("%s/%d/products.json", collectionsBasePath, collectionID)
resource := new(ProductsResource)
headers := http.Header{}
headers, err := s.client.createAndDoGetHeaders("GET", path, nil, options, resource)
if err != nil {
return nil, nil, err
}
// Extract pagination info from header
linkHeader := headers.Get("Link")
pagination, err := extractPagination(linkHeader)
if err != nil {
return nil, nil, err
}
return resource.Products, pagination, nil
}