-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtransactional.go
More file actions
98 lines (82 loc) · 2.24 KB
/
transactional.go
File metadata and controls
98 lines (82 loc) · 2.24 KB
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
package loops
import (
"bytes"
"encoding/json"
"fmt"
"net/http"
"net/url"
)
type TransactionalEmail struct {
ID string `json:"id"`
Name string `json:"name"`
LastUpdated string `json:"lastUpdated"`
DataVariables []string `json:"dataVariables"`
}
type Attachment struct {
Filename string `json:"filename"`
ContentType string `json:"contentType"`
Data string `json:"data"`
}
type SendTransactionalRequest struct {
Email string `json:"email"`
TransactionalID string `json:"transactionalId"`
AddToAudience *bool `json:"addToAudience,omitempty"`
DataVariables map[string]any `json:"dataVariables,omitempty"`
Attachments []Attachment `json:"attachments,omitempty"`
IdempotencyKey string `json:"-"`
}
func (c *Client) SendTransactional(req SendTransactionalRequest) error {
b, err := json.Marshal(req)
if err != nil {
return fmt.Errorf("failed to encode request: %w", err)
}
httpReq, err := c.newRequest(http.MethodPost, "/transactional", bytes.NewReader(b))
if err != nil {
return err
}
if req.IdempotencyKey != "" {
httpReq.Header.Set("Idempotency-Key", req.IdempotencyKey)
}
resp, err := c.do(httpReq)
if err != nil {
return err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return errorFromResponse(resp)
}
return nil
}
func (c *Client) ListTransactional(params PaginationParams) ([]TransactionalEmail, *Pagination, error) {
q := url.Values{}
if params.PerPage != "" {
q.Set("perPage", params.PerPage)
}
if params.Cursor != "" {
q.Set("cursor", params.Cursor)
}
path := "/transactional"
if len(q) > 0 {
path += "?" + q.Encode()
}
req, err := c.newRequest(http.MethodGet, path, nil)
if err != nil {
return nil, nil, err
}
resp, err := c.do(req)
if err != nil {
return nil, nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, nil, errorFromResponse(resp)
}
var result struct {
Pagination Pagination `json:"pagination"`
Data []TransactionalEmail `json:"data"`
}
if err := json.NewDecoder(resp.Body).Decode(&result); err != nil {
return nil, nil, fmt.Errorf("failed to decode response: %w", err)
}
return result.Data, &result.Pagination, nil
}