-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathwriter.go
More file actions
61 lines (49 loc) · 1.16 KB
/
writer.go
File metadata and controls
61 lines (49 loc) · 1.16 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
package goro
import (
"bytes"
"context"
"encoding/json"
"fmt"
"sort"
)
type streamWriter struct {
stream string
slinger Slinger
}
const (
writePath = "/streams/%s"
eventContentType = "application/vnd.eventstore.events+json"
)
// NewWriter creates a new Writer for a stream
func NewWriter(slinger Slinger, stream string) Writer {
return &streamWriter{
stream: stream,
slinger: slinger,
}
}
// Write implements the Writer interface. It writes events in a bulk after sorting them in version order
func (w streamWriter) Write(ctx context.Context, expectedVersion int64, events ...Event) error {
b := new(bytes.Buffer)
path := fmt.Sprintf(writePath, w.stream)
data := append(Events{}, events...)
sort.Sort(data)
if err := json.NewEncoder(b).Encode(data); err != nil {
return err
}
req, err := w.slinger.
Sling().
Post(path).
Body(b).
Set("Content-Type", eventContentType).
Set("ES-ExpectedVersion", fmt.Sprintf("%d", expectedVersion)).
Request()
if err != nil {
return err
}
req = req.WithContext(ctx)
resp, err := w.slinger.Sling().Do(req, nil, nil)
if err != nil {
return err
}
return relevantError(resp.StatusCode)
}