aboutsummaryrefslogtreecommitdiffhomepage
path: root/integration/nunuxkeeper/nunuxkeeper.go
blob: 4ea5c45b0922cfeeea8e48039de90c7069290913 (plain)
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
// Copyright 2017 Frédéric Guillot. All rights reserved.
// Use of this source code is governed by the Apache 2.0
// license that can be found in the LICENSE file.

package nunuxkeeper

import (
	"fmt"
	"net/url"
	"path"

	"github.com/miniflux/miniflux/http/client"
)

// Document structure of a Nununx Keeper document
type Document struct {
	Title       string `json:"title,omitempty"`
	Origin      string `json:"origin,omitempty"`
	Content     string `json:"content,omitempty"`
	ContentType string `json:"contentType,omitempty"`
}

// Client represents an Nunux Keeper client.
type Client struct {
	baseURL string
	apiKey  string
}

// AddEntry sends an entry to Nunux Keeper.
func (c *Client) AddEntry(link, title, content string) error {
	doc := &Document{
		Title:       title,
		Origin:      link,
		Content:     content,
		ContentType: "text/html",
	}

	apiURL, err := getAPIEndpoint(c.baseURL, "/v2/documents")
	if err != nil {
		return err
	}

	clt := client.New(apiURL)
	clt.WithCredentials("api", c.apiKey)
	response, err := clt.PostJSON(doc)
	if response.HasServerFailure() {
		return fmt.Errorf("nunux-keeper: unable to send entry, status=%d", response.StatusCode)
	}

	return err
}

// NewClient returns a new Nunux Keeepr client.
func NewClient(baseURL, apiKey string) *Client {
	return &Client{baseURL: baseURL, apiKey: apiKey}
}

func getAPIEndpoint(baseURL, pathURL string) (string, error) {
	u, err := url.Parse(baseURL)
	if err != nil {
		return "", fmt.Errorf("nunux-keeper: invalid API endpoint: %v", err)
	}
	u.Path = path.Join(u.Path, pathURL)
	return u.String(), nil
}