-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathevents.go
96 lines (80 loc) · 2.31 KB
/
events.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
package plunk
import (
"errors"
"fmt"
"net/http"
)
type EventPayload struct {
Event string `json:"event"`
Email string `json:"email"`
Data map[string]any `json:"data"` // See: https://docs.useplunk.com/guides/linking-data-to-contacts#linking-data-on-event-triggers
Subscribed bool `json:"subscribed"` // When you trigger an event for a contact, they will automatically be subscribed unless you pass subscribed: false along with the event.
}
type EventResponse struct {
Success bool `json:"success"`
Contact string `json:"contact"` // the ID of the contact that was triggered
Event string `json:"event"` // the ID of the event that was triggered
}
type Event struct {
ID string `json:"id"`
Name string `json:"name"`
CreatedAt string `json:"createdAt"`
UpdatedAt string `json:"updatedAt"`
ProjectID string `json:"projectId"`
CampaignID string `json:"campaignId"`
TemplateID string `json:"templateId"`
}
var (
ErrMissingEvent = errors.New("missing event")
ErrMissingEmail = errors.New("missing email")
ErrMissingEventID = errors.New("missing event id")
ErrCouldNotDeleteEvent = errors.New("could not delete event")
)
// Triggers an event and creates it if it doesn't exist.
func (p *Plunk) TriggerEvent(payload EventPayload) (*EventResponse, error) {
// validate payload
if payload.Event == "" {
return nil, ErrMissingEvent
}
if payload.Email == "" {
return nil, ErrMissingEmail
}
result := &EventResponse{}
url := p.url(eventsEndpoint)
resp, err := p.sendRequest(SendConfig{
Url: url,
Method: http.MethodPost,
Body: payload,
})
if err != nil {
return nil, err
}
err = decodeResponse(resp, result)
if err != nil {
return nil, err
}
p.logInfo(fmt.Sprintf("Event triggered: %s ", payload.Event))
return result, nil
}
// Deletes an event.
func (p *Plunk) DeleteEvent(id string) (*Event, error) {
if id == "" {
return nil, ErrMissingEventID
}
url := p.url(deleteEventEndpoint)
resp, err := p.sendRequest(SendConfig{
Url: url,
Method: http.MethodDelete,
Body: map[string]string{"id": id},
})
if err != nil {
return nil, err
}
result := &Event{}
err = decodeResponse(resp, result)
if err != nil {
return nil, err
}
p.logInfo(fmt.Sprintf("Event deleted: %s ", id))
return result, nil
}