-
Notifications
You must be signed in to change notification settings - Fork 1
/
turbostreams.go
91 lines (81 loc) · 2.54 KB
/
turbostreams.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
// Package handling provides reusable handlers.
package handling
import (
"context"
"github.com/pkg/errors"
"github.com/sargassum-world/godest"
"github.com/sargassum-world/godest/session"
"github.com/sargassum-world/godest/turbostreams"
"github.com/sargassum-world/pslive/internal/app/pslive/auth"
)
type DataModifier func(
ctx context.Context, a auth.Auth, data map[string]interface{},
) (modifications map[string]interface{}, err error)
func AddAuthData() DataModifier {
return func(
_ context.Context, a auth.Auth, data map[string]interface{},
) (modifications map[string]interface{}, err error) {
return map[string]interface{}{
"Auth": a,
}, nil
}
}
func ModifyData(
ctx context.Context, a auth.Auth, messages []turbostreams.Message, modifiers ...DataModifier,
) ([]turbostreams.Message, error) {
// TODO: move this function into github.com/sargassum-world/godest/turbostreams?
// (with a generic type for Auth)
modified := make([]turbostreams.Message, len(messages))
for i, m := range messages {
// Copy the template message
modified[i] = turbostreams.Message{
Action: m.Action,
Target: m.Target,
Template: m.Template,
}
if m.Action == turbostreams.ActionRemove {
// The contents of the stream element will be ignored anyways
modified[i].Template = ""
continue
}
// Copy the template data
d, ok := m.Data.(map[string]interface{})
if !ok {
return nil, errors.Errorf("unexpected turbo stream message data type: %T", m.Data)
}
data := make(map[string]interface{})
for key, value := range d {
data[key] = value
}
// Add data modifications
for _, modifier := range modifiers {
modifications, err := modifier(ctx, a, data)
if err != nil {
return nil, errors.Wrap(err, "couldn't modify template data")
}
for key, value := range modifications {
data[key] = value
}
}
modified[i].Data = data
}
return modified, nil
}
func HandleTSMsg(
r godest.TemplateRenderer, ss *session.Store, modifiers ...DataModifier,
) turbostreams.HandlerFunc {
modifiers = append([]DataModifier{AddAuthData()}, modifiers...)
return auth.HandleTS(
func(c *turbostreams.Context, a auth.Auth) (err error) {
// TODO: move this function into github.com/sargassum-world/fluitans/pkg/godest/turbostreams?
// (without prepending AddAuthData though, and with a generic type for Auth)
ctx := c.Context()
modified := c.Published()
if modified, err = ModifyData(ctx, a, modified, modifiers...); err != nil {
return err
}
return r.WriteTurboStream(c.MsgWriter(), modified...)
},
ss,
)
}