~evanj/evanjon.es

ref: 39a9390a16d658c8d7a1a67581c1a910b0e3bff0 evanjon.es/pkg/cms/cms.go -rw-r--r-- 2.1 KiB
39a9390aEvan M Jones Feat(css): Align middle. 1 year, 7 months ago
                                                                                
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
package cms

import (
	"context"
	"encoding/json"
	"errors"
	"fmt"
	"io/ioutil"
	"net/http"
)

var (
	ErrNoContent = errors.New("no content found for query")
)

type CMS struct {
	user, pass string
	space      int
	baseURL    string
	client     *http.Client
}

type Content struct {
	ContentID           string
	ContentParentTypeID string
	ContentValues       []ContentValue
}

type ContentValue struct {
	FieldType  string
	FieldName  string
	FieldValue string
}

func New(user, pass, baseURL string, space int) *CMS {
	return NewWithClient(user, pass, baseURL, space, http.DefaultClient)
}

func NewWithClient(user, pass, baseURL string, space int, client *http.Client) *CMS {
	return &CMS{
		user:    user,
		pass:    pass,
		space:   space,
		baseURL: baseURL,
		client:  client,
	}
}

func (cms *CMS) List(ctx context.Context, typeID int, order, field string) ([]Content, error) {
	url := fmt.Sprintf("%s/contenttype/%d/%d?order=%s&field=%s", cms.baseURL, cms.space, typeID, order, field)

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return nil, err
	}
	req.SetBasicAuth(cms.user, cms.pass)

	resp, err := cms.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var body struct {
		ContentList []Content
	}
	if err := json.Unmarshal(bytes, &body); err != nil {
		return nil, err
	}

	return body.ContentList, nil
}

func (cms *CMS) Find(ctx context.Context, typeID int, field, query string) (*Content, error) {
	url := fmt.Sprintf("%s/content/search?space=%d&contenttype=%d&field=%s&query=%s", cms.baseURL, cms.space, typeID, field, query)

	req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
	if err != nil {
		return nil, err
	}
	req.SetBasicAuth(cms.user, cms.pass)

	resp, err := cms.client.Do(req)
	if err != nil {
		return nil, err
	}
	defer resp.Body.Close()

	bytes, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, err
	}

	var body []Content
	if err := json.Unmarshal(bytes, &body); err != nil {
		return nil, err
	}

	if len(body) < 1 {
		return nil, ErrNoContent
	}

	return &body[0], nil
}