This repository has been archived by the owner on Jun 18, 2021. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 64
/
space.go
110 lines (88 loc) · 2.34 KB
/
space.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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package contentful
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"strconv"
)
// SpacesService model
type SpacesService service
// Space model
type Space struct {
Sys *Sys `json:"sys,omitempty"`
Name string `json:"name,omitempty"`
DefaultLocale string `json:"defaultLocale,omitempty"`
}
// MarshalJSON for custom json marshaling
func (space *Space) MarshalJSON() ([]byte, error) {
return json.Marshal(&struct {
Name string `json:"name,omitempty"`
DefaultLocale string `json:"defaultLocale,omitempty"`
}{
Name: space.Name,
DefaultLocale: space.DefaultLocale,
})
}
// GetVersion returns entity version
func (space *Space) GetVersion() int {
version := 1
if space.Sys != nil {
version = space.Sys.Version
}
return version
}
// List creates a spaces collection
func (service *SpacesService) List() *Collection {
req, _ := service.c.newRequest("GET", "/spaces", nil, nil)
col := NewCollection(&CollectionOptions{})
col.c = service.c
col.req = req
return col
}
// Get returns a single space entity
func (service *SpacesService) Get(spaceID string) (*Space, error) {
path := fmt.Sprintf("/spaces/%s", spaceID)
req, err := service.c.newRequest(http.MethodGet, path, nil, nil)
if err != nil {
return &Space{}, err
}
var space Space
if ok := service.c.do(req, &space); ok != nil {
return &Space{}, ok
}
return &space, nil
}
// Upsert updates or creates a new space
func (service *SpacesService) Upsert(space *Space) error {
bytesArray, err := json.Marshal(space)
if err != nil {
return err
}
var path string
var method string
if space.Sys != nil && space.Sys.CreatedAt != "" {
path = fmt.Sprintf("/spaces/%s", space.Sys.ID)
method = http.MethodPut
} else {
path = "/spaces"
method = http.MethodPost
}
req, err := service.c.newRequest(method, path, nil, bytes.NewReader(bytesArray))
if err != nil {
return err
}
req.Header.Set("X-Contentful-Version", strconv.Itoa(space.GetVersion()))
return service.c.do(req, space)
}
// Delete the given space
func (service *SpacesService) Delete(space *Space) error {
path := fmt.Sprintf("/spaces/%s", space.Sys.ID)
req, err := service.c.newRequest(http.MethodDelete, path, nil, nil)
if err != nil {
return err
}
version := strconv.Itoa(space.Sys.Version)
req.Header.Set("X-Contentful-Version", version)
return service.c.do(req, nil)
}