docs(lighthouse,postcard,signpost): compile README Go examples via src= (quick-261118-qsd)
This commit is contained in:
@@ -79,18 +79,10 @@ centrifugo:
|
|||||||
|
|
||||||
A plugin imports the driver package for its side effect, builds the service at Boot, installs a user lookup and registers its channel authorizers:
|
A plugin imports the driver package for its side effect, builds the service at Boot, installs a user lookup and registers its channel authorizers:
|
||||||
|
|
||||||
```go
|
```go src=modules/lighthouse/example_test.go#RoomsPlugin.Boot
|
||||||
package acme
|
// Boot builds the realtime service, installs the user lookup and registers
|
||||||
|
// the room authorizer.
|
||||||
import (
|
func (p *RoomsPlugin) Boot(app *backpack.App) error {
|
||||||
"context"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/lighthouse"
|
|
||||||
_ "git.golem15.com/golem15/summercms/modules/lighthouse/centrifugo"
|
|
||||||
)
|
|
||||||
|
|
||||||
func (p *Plugin) Boot(app *backpack.App) error {
|
|
||||||
svc, err := lighthouse.From(app)
|
svc, err := lighthouse.From(app)
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return err
|
return err
|
||||||
@@ -112,8 +104,9 @@ func (p *Plugin) Boot(app *backpack.App) error {
|
|||||||
|
|
||||||
and mounts the driver's routes once:
|
and mounts the driver's routes once:
|
||||||
|
|
||||||
```go
|
```go src=modules/lighthouse/example_test.go#RoomsPlugin.Routes
|
||||||
func (p *Plugin) Routes(r pact.Router) error {
|
// Routes mounts the driver's routes once.
|
||||||
|
func (p *RoomsPlugin) Routes(r pact.Router) error {
|
||||||
return lighthouse.Mount(r, p.realtime.Driver(), lighthouse.Surfaces{
|
return lighthouse.Mount(r, p.realtime.Driver(), lighthouse.Surfaces{
|
||||||
UserAuth: surf.Use("jwt.auth"),
|
UserAuth: surf.Use("jwt.auth"),
|
||||||
ServerToServer: surf.Use(),
|
ServerToServer: surf.Use(),
|
||||||
@@ -124,10 +117,10 @@ func (p *Plugin) Routes(r pact.Router) error {
|
|||||||
|
|
||||||
A model package stays free of realtime code; the plugin binds the model at Boot:
|
A model package stays free of realtime code; the plugin binds the model at Boot:
|
||||||
|
|
||||||
```go
|
```go src=modules/lighthouse/example_test.go#bind
|
||||||
err := lighthouse.Bind[models.Post](svc, lighthouse.Binding[models.Post]{
|
return lighthouse.Bind[Post](svc, lighthouse.Binding[Post]{
|
||||||
Alias: "blog.post",
|
Alias: "blog.post",
|
||||||
Channels: func(ctx context.Context, tx *gorm.DB, p *models.Post) ([]string, error) {
|
Channels: func(ctx context.Context, tx *gorm.DB, p *Post) ([]string, error) {
|
||||||
return []string{"blog:" + strconv.FormatUint(uint64(p.BlogID), 10)}, nil
|
return []string{"blog:" + strconv.FormatUint(uint64(p.BlogID), 10)}, nil
|
||||||
},
|
},
|
||||||
})
|
})
|
||||||
@@ -135,21 +128,20 @@ err := lighthouse.Bind[models.Post](svc, lighthouse.Binding[models.Post]{
|
|||||||
|
|
||||||
A bulk import suppresses the per-row events and publishes one summary after commit:
|
A bulk import suppresses the per-row events and publishes one summary after commit:
|
||||||
|
|
||||||
```go
|
```go src=modules/lighthouse/example_test.go#bulk
|
||||||
err := lighthouse.WithoutBroadcasting[models.Post](ctx, func(ctx context.Context) error {
|
return lighthouse.WithoutBroadcasting[Post](ctx, func(ctx context.Context) error {
|
||||||
return lagoon.Transaction(ctx, gdb, func(ctx context.Context, tx *gorm.DB) error {
|
return lagoon.Transaction(ctx, db, func(ctx context.Context, tx *gorm.DB) error {
|
||||||
for _, p := range posts {
|
for _, title := range titles {
|
||||||
if err := tx.Create(&p).Error; err != nil {
|
if err := tx.Create(&Post{BlogID: 7, Title: title}).Error; err != nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
return svc.Emit(ctx, tx, lighthouse.Broadcast{
|
return svc.Emit(ctx, tx, lighthouse.Broadcast{
|
||||||
Channels: []string{"blog:7"},
|
Channels: []string{"blog:7"},
|
||||||
Event: "blog.bulk_updated",
|
Event: "blog.posts_imported",
|
||||||
Payload: struct {
|
Payload: struct {
|
||||||
Reason string `json:"reason"`
|
Count int `json:"count"`
|
||||||
Count int `json:"count"`
|
}{len(titles)},
|
||||||
}{"import", len(posts)},
|
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
})
|
})
|
||||||
@@ -157,7 +149,7 @@ err := lighthouse.WithoutBroadcasting[models.Post](ctx, func(ctx context.Context
|
|||||||
|
|
||||||
Tests select the memory driver and read what was published:
|
Tests select the memory driver and read what was published:
|
||||||
|
|
||||||
```go
|
```go src=modules/lighthouse/example_test.go#publications
|
||||||
mem := svc.Driver().(*lighthouse.MemoryDriver)
|
mem := svc.Driver().(*lighthouse.MemoryDriver)
|
||||||
for _, pub := range mem.Publications() {
|
for _, pub := range mem.Publications() {
|
||||||
fmt.Println(pub.Method, pub.Channels, pub.Event)
|
fmt.Println(pub.Method, pub.Channels, pub.Event)
|
||||||
|
|||||||
@@ -2,8 +2,12 @@ package lighthouse_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net/http"
|
||||||
|
"slices"
|
||||||
"strconv"
|
"strconv"
|
||||||
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
@@ -11,6 +15,9 @@ import (
|
|||||||
"git.golem15.com/golem15/summercms/modules/compass"
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
"git.golem15.com/golem15/summercms/modules/lagoon"
|
"git.golem15.com/golem15/summercms/modules/lagoon"
|
||||||
"git.golem15.com/golem15/summercms/modules/lighthouse"
|
"git.golem15.com/golem15/summercms/modules/lighthouse"
|
||||||
|
_ "git.golem15.com/golem15/summercms/modules/lighthouse/centrifugo"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/surf"
|
||||||
"gorm.io/gorm"
|
"gorm.io/gorm"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -194,3 +201,145 @@ func TestDocsBroadcast(t *testing.T) {
|
|||||||
t.Fatalf("summary = %+v %s", pubs[1], pubs[1].Payload)
|
t.Fatalf("summary = %+v %s", pubs[1], pubs[1].Payload)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// RoomsPlugin is the acme.rooms plugin: room:{id} channels for members.
|
||||||
|
type RoomsPlugin struct {
|
||||||
|
realtime *lighthouse.Service
|
||||||
|
}
|
||||||
|
|
||||||
|
// lookupAcmeUser stands in for the application's own user model.
|
||||||
|
func lookupAcmeUser(ctx context.Context, id uint) (lighthouse.User, bool, error) {
|
||||||
|
if id != 42 {
|
||||||
|
return lighthouse.User{}, false, nil
|
||||||
|
}
|
||||||
|
name := "Ada"
|
||||||
|
return lighthouse.User{ID: id, Name: &name}, true, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
// isRoomMember stands in for the application's own membership query.
|
||||||
|
func isRoomMember(ctx context.Context, userID uint, roomID int64) bool {
|
||||||
|
return userID == 42 && roomID == 7
|
||||||
|
}
|
||||||
|
|
||||||
|
// Boot builds the realtime service, installs the user lookup and registers
|
||||||
|
// the room authorizer.
|
||||||
|
func (p *RoomsPlugin) Boot(app *backpack.App) error {
|
||||||
|
svc, err := lighthouse.From(app)
|
||||||
|
if err != nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
p.realtime = svc
|
||||||
|
svc.SetUserLookup(func(ctx context.Context, id uint) (lighthouse.User, bool, error) {
|
||||||
|
return lookupAcmeUser(ctx, id) // the application's own user model
|
||||||
|
})
|
||||||
|
// Allow room:{id} to members only; re-checked on every subscribe.
|
||||||
|
return svc.Registry().Register("room", lighthouse.AuthorizerFunc(
|
||||||
|
func(ctx context.Context, userID uint, channel string) lighthouse.Result {
|
||||||
|
if isRoomMember(ctx, userID, lighthouse.ChannelID(channel)) {
|
||||||
|
return lighthouse.Allowed(nil)
|
||||||
|
}
|
||||||
|
return lighthouse.Denied("not a room member")
|
||||||
|
}))
|
||||||
|
}
|
||||||
|
|
||||||
|
// Routes mounts the driver's routes once.
|
||||||
|
func (p *RoomsPlugin) Routes(r pact.Router) error {
|
||||||
|
return lighthouse.Mount(r, p.realtime.Driver(), lighthouse.Surfaces{
|
||||||
|
UserAuth: surf.Use("jwt.auth"),
|
||||||
|
ServerToServer: surf.Use(),
|
||||||
|
Middleware: surf.Use("throttle:acme-realtime"),
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
// routeRecorder is a pact.Router that records each route with its
|
||||||
|
// middleware, standing in for surf's router.
|
||||||
|
type routeRecorder struct {
|
||||||
|
prefix string
|
||||||
|
middleware []string
|
||||||
|
lines *[]string
|
||||||
|
}
|
||||||
|
|
||||||
|
func (r routeRecorder) group(prefix string, mw []string, raw bool, fn func(pact.Router)) {
|
||||||
|
if raw {
|
||||||
|
mw = append([]string{"raw"}, mw...)
|
||||||
|
}
|
||||||
|
fn(routeRecorder{strings.TrimSuffix(r.prefix+prefix, "/"), append(slices.Clone(r.middleware), mw...), r.lines})
|
||||||
|
}
|
||||||
|
func (r routeRecorder) add(method, path string, mw []string) {
|
||||||
|
*r.lines = append(*r.lines, method+" "+r.prefix+path+" "+strings.Join(append(slices.Clone(r.middleware), mw...), ","))
|
||||||
|
}
|
||||||
|
func (r routeRecorder) Group(p string, mw []string, fn func(pact.Router)) { r.group(p, mw, false, fn) }
|
||||||
|
func (r routeRecorder) GroupRaw(p string, mw []string, fn func(pact.Router)) {
|
||||||
|
r.group(p, mw, true, fn)
|
||||||
|
}
|
||||||
|
func (r routeRecorder) Get(p string, _ http.HandlerFunc, mw ...string) { r.add("GET", p, mw) }
|
||||||
|
func (r routeRecorder) Post(p string, _ http.HandlerFunc, mw ...string) { r.add("POST", p, mw) }
|
||||||
|
func (r routeRecorder) Put(p string, _ http.HandlerFunc, mw ...string) { r.add("PUT", p, mw) }
|
||||||
|
func (r routeRecorder) Patch(p string, _ http.HandlerFunc, mw ...string) { r.add("PATCH", p, mw) }
|
||||||
|
func (r routeRecorder) Delete(p string, _ http.HandlerFunc, mw ...string) { r.add("DELETE", p, mw) }
|
||||||
|
func (routeRecorder) Where(string, string) {}
|
||||||
|
func (routeRecorder) WhereIn(string, ...string) {}
|
||||||
|
|
||||||
|
// TestDocsRoomsPlugin boots the README's plugin on the centrifugo driver,
|
||||||
|
// checks its user lookup and room authorizer, and mounts its routes.
|
||||||
|
func TestDocsRoomsPlugin(t *testing.T) {
|
||||||
|
app, err := newApp(map[string]any{"realtime.driver": "centrifugo", "realtime.centrifugo.token_secret": "docs-secret"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
p := &RoomsPlugin{}
|
||||||
|
if err := p.Boot(app); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
ctx := t.Context()
|
||||||
|
if u, ok, err := p.realtime.User(ctx, 42); err != nil || !ok || u.Name == nil || *u.Name != "Ada" {
|
||||||
|
t.Fatalf("User(42) = %+v, %v, %v", u, ok, err)
|
||||||
|
}
|
||||||
|
room, ok := p.realtime.Registry().Get("room")
|
||||||
|
if !ok {
|
||||||
|
t.Fatal("no room authorizer")
|
||||||
|
}
|
||||||
|
if !room.Authorize(ctx, 42, "room:7").Allowed || room.Authorize(ctx, 42, "room:8").Reason() != "not a room member" {
|
||||||
|
t.Fatal("room authorizer does not follow membership")
|
||||||
|
}
|
||||||
|
|
||||||
|
var lines []string
|
||||||
|
if err := p.Routes(routeRecorder{lines: &lines}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
want := []string{
|
||||||
|
"GET /api/realtime/token jwt.auth,throttle:acme-realtime",
|
||||||
|
"POST /api/realtime/subscribe raw,throttle:acme-realtime",
|
||||||
|
}
|
||||||
|
if !slices.Equal(lines, want) {
|
||||||
|
t.Fatalf("routes = %q, want %q", lines, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func ExampleMemoryDriver() {
|
||||||
|
app, err := newApp(map[string]any{"realtime.driver": "memory"})
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
svc, err := lighthouse.From(app)
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
// Code under test publishes; here the example calls the driver itself.
|
||||||
|
ctx := context.Background()
|
||||||
|
_ = svc.Driver().Publish(ctx, "blog:7", "blog.post_updated", json.RawMessage(`{"id":1}`))
|
||||||
|
_ = svc.Driver().Broadcast(ctx, []string{"blog:7", "blog:8"}, "blog.posts_imported", json.RawMessage(`{"count":3}`))
|
||||||
|
|
||||||
|
// docs:start publications
|
||||||
|
mem := svc.Driver().(*lighthouse.MemoryDriver)
|
||||||
|
for _, pub := range mem.Publications() {
|
||||||
|
fmt.Println(pub.Method, pub.Channels, pub.Event)
|
||||||
|
}
|
||||||
|
// docs:end publications
|
||||||
|
|
||||||
|
// Output:
|
||||||
|
// publish [blog:7] blog.post_updated
|
||||||
|
// broadcast [blog:7 blog:8] blog.posts_imported
|
||||||
|
}
|
||||||
|
|||||||
@@ -62,7 +62,9 @@ func TestFromSelectsDriver(t *testing.T) {
|
|||||||
}
|
}
|
||||||
t.Run("unknown_lists_registered", func(t *testing.T) {
|
t.Run("unknown_lists_registered", func(t *testing.T) {
|
||||||
_, err := From(configApp(t, map[string]any{"realtime.driver": "nope"}))
|
_, err := From(configApp(t, map[string]any{"realtime.driver": "nope"}))
|
||||||
if err == nil || !strings.Contains(err.Error(), `unknown realtime.driver "nope"`) || !strings.Contains(err.Error(), "acme-nil-driver, log, memory, null") {
|
// example_test.go imports lighthouse/centrifugo, so "centrifugo" may
|
||||||
|
// sit between the drivers this package's tests register.
|
||||||
|
if err == nil || !strings.Contains(err.Error(), `unknown realtime.driver "nope"`) || !strings.Contains(err.Error(), "acme-nil-driver, ") || !strings.Contains(err.Error(), "log, memory, null") {
|
||||||
t.Fatalf("err = %v", err)
|
t.Fatalf("err = %v", err)
|
||||||
}
|
}
|
||||||
})
|
})
|
||||||
|
|||||||
@@ -48,18 +48,9 @@ Hi **{{ .name }}**, thanks for joining the blog.
|
|||||||
|
|
||||||
and sends it through the mailer the runtime published:
|
and sends it through the mailer the runtime published:
|
||||||
|
|
||||||
```go
|
```go src=modules/postcard/example_test.go#sendWelcome
|
||||||
package blog
|
// sendWelcome sends the welcome mail through the mailer published at boot.
|
||||||
|
func sendWelcome(ctx context.Context, app *backpack.App, email, name string) error {
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/postcard"
|
|
||||||
)
|
|
||||||
|
|
||||||
func SendWelcome(ctx context.Context, app *backpack.App, email, name string) error {
|
|
||||||
mailer, ok := app.Lookup[postcard.Mailer]()
|
mailer, ok := app.Lookup[postcard.Mailer]()
|
||||||
if !ok {
|
if !ok {
|
||||||
return errors.New("mailer not published")
|
return errors.New("mailer not published")
|
||||||
@@ -74,17 +65,7 @@ func SendWelcome(ctx context.Context, app *backpack.App, email, name string) err
|
|||||||
|
|
||||||
In tests, build the catalog and mailer directly and inspect what was sent:
|
In tests, build the catalog and mailer directly and inspect what was sent:
|
||||||
|
|
||||||
```go
|
```go src=modules/postcard/example_test.go#TestWelcomeMail
|
||||||
package blog
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"testing"
|
|
||||||
"testing/fstest"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/postcard"
|
|
||||||
)
|
|
||||||
|
|
||||||
func TestWelcomeMail(t *testing.T) {
|
func TestWelcomeMail(t *testing.T) {
|
||||||
mailFS := fstest.MapFS{"views/mail/welcome.htm": {Data: []byte("subject = \"Welcome, {{ .name }}\"\n==\nHi **{{ .name }}**.\n")}}
|
mailFS := fstest.MapFS{"views/mail/welcome.htm": {Data: []byte("subject = \"Welcome, {{ .name }}\"\n==\nHi **{{ .name }}**.\n")}}
|
||||||
cat := postcard.NewCatalog()
|
cat := postcard.NewCatalog()
|
||||||
@@ -123,30 +104,14 @@ NOTE: {{ .text }}
|
|||||||
<div class="note">{{ .text }}</div>
|
<div class="note">{{ .text }}</div>
|
||||||
```
|
```
|
||||||
|
|
||||||
and declares it next to its templates:
|
and declares it next to its templates (`mailFS` is the plugin's `views/mail` directory, embedded with `//go:embed views/mail`; the plugin asserts `var _ pact.HasMailPartials = BlogPlugin{}`):
|
||||||
|
|
||||||
```go
|
```go src=modules/postcard/example_test.go#BlogPlugin.MailPartialsFS
|
||||||
package blog
|
func (BlogPlugin) MailPartialsFS() fs.FS { return mailFS }
|
||||||
|
```
|
||||||
|
|
||||||
import (
|
```go src=modules/postcard/example_test.go#BlogPlugin.MailPartials
|
||||||
"embed"
|
func (BlogPlugin) MailPartials() []string {
|
||||||
"io/fs"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/pact"
|
|
||||||
)
|
|
||||||
|
|
||||||
//go:embed views/mail
|
|
||||||
var mailFS embed.FS
|
|
||||||
|
|
||||||
type Plugin struct{}
|
|
||||||
|
|
||||||
var _ pact.HasMailPartials = Plugin{}
|
|
||||||
|
|
||||||
func (Plugin) ID() string { return "acme.blog" }
|
|
||||||
|
|
||||||
func (Plugin) MailPartialsFS() fs.FS { return mailFS }
|
|
||||||
|
|
||||||
func (Plugin) MailPartials() []string {
|
|
||||||
return []string{"acme.blog::mail.partials.note"}
|
return []string{"acme.blog::mail.partials.note"}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
@@ -236,18 +201,12 @@ An override never stops mail:
|
|||||||
|
|
||||||
`postcard.NewMailer` takes a source through `postcard.Options.Overrides`; any `postcard.OverrideSource` works, which is how a test supplies overrides without a database:
|
`postcard.NewMailer` takes a source through `postcard.Options.Overrides`; any `postcard.OverrideSource` works, which is how a test supplies overrides without a database:
|
||||||
|
|
||||||
```go
|
```go src=modules/postcard/example_test.go#fixedOverrides
|
||||||
package blog
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/postcard"
|
|
||||||
)
|
|
||||||
|
|
||||||
// fixedOverrides overrides one template with a fixed subject and body.
|
// fixedOverrides overrides one template with a fixed subject and body.
|
||||||
type fixedOverrides struct{}
|
type fixedOverrides struct{}
|
||||||
|
```
|
||||||
|
|
||||||
|
```go src=modules/postcard/example_test.go#fixedOverrides.MailOverrides
|
||||||
func (fixedOverrides) MailOverrides(_ context.Context, template string) (postcard.Overrides, error) {
|
func (fixedOverrides) MailOverrides(_ context.Context, template string) (postcard.Overrides, error) {
|
||||||
if template != "acme.blog::mail.welcome" {
|
if template != "acme.blog::mail.welcome" {
|
||||||
return postcard.Overrides{}, nil
|
return postcard.Overrides{}, nil
|
||||||
@@ -257,7 +216,9 @@ func (fixedOverrides) MailOverrides(_ context.Context, template string) (postcar
|
|||||||
Body: "Good to see you, **{{ .name }}**.",
|
Body: "Good to see you, **{{ .name }}**.",
|
||||||
}}, nil
|
}}, nil
|
||||||
}
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
```go src=modules/postcard/example_test.go#newTestMailer
|
||||||
func newTestMailer(cat *postcard.Catalog, driver postcard.Driver) postcard.Mailer {
|
func newTestMailer(cat *postcard.Catalog, driver postcard.Driver) postcard.Mailer {
|
||||||
return postcard.NewMailer(cat, driver, postcard.Options{Overrides: fixedOverrides{}})
|
return postcard.NewMailer(cat, driver, postcard.Options{Overrides: fixedOverrides{}})
|
||||||
}
|
}
|
||||||
@@ -324,17 +285,7 @@ Sample values are strings and are used only by `postcard.Editor`; `Send` never r
|
|||||||
|
|
||||||
`postcard.EditorFrom` returns the `postcard.Editor` of the mailer `postcard.Activate` published. Admin code describes unsaved content as a `postcard.Draft` and asks the editor to check, render or send it:
|
`postcard.EditorFrom` returns the `postcard.Editor` of the mailer `postcard.Activate` published. Admin code describes unsaved content as a `postcard.Draft` and asks the editor to check, render or send it:
|
||||||
|
|
||||||
```go
|
```go src=modules/postcard/example_test.go#previewWelcome
|
||||||
package blog
|
|
||||||
|
|
||||||
import (
|
|
||||||
"context"
|
|
||||||
"errors"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/backpack"
|
|
||||||
"git.golem15.com/golem15/summercms/modules/postcard"
|
|
||||||
)
|
|
||||||
|
|
||||||
// previewWelcome renders an edited welcome mail without saving it.
|
// previewWelcome renders an edited welcome mail without saving it.
|
||||||
func previewWelcome(ctx context.Context, app *backpack.App, subject, body string) (postcard.Preview, error) {
|
func previewWelcome(ctx context.Context, app *backpack.App, subject, body string) (postcard.Preview, error) {
|
||||||
editor, ok := postcard.EditorFrom(app)
|
editor, ok := postcard.EditorFrom(app)
|
||||||
|
|||||||
@@ -2,10 +2,16 @@ package postcard_test
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"io/fs"
|
||||||
"strings"
|
"strings"
|
||||||
|
"testing"
|
||||||
"testing/fstest"
|
"testing/fstest"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/compass"
|
||||||
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
"git.golem15.com/golem15/summercms/modules/postcard"
|
"git.golem15.com/golem15/summercms/modules/postcard"
|
||||||
)
|
)
|
||||||
|
|
||||||
@@ -25,6 +31,12 @@ Hi **{{ .name }}**, thanks for joining the blog.
|
|||||||
==
|
==
|
||||||
<div class="blog-mail">{{ .Content }}</div>
|
<div class="blog-mail">{{ .Content }}</div>
|
||||||
<style>{{ .brandCss }}{{ .css }}</style>
|
<style>{{ .brandCss }}{{ .css }}</style>
|
||||||
|
`)},
|
||||||
|
"views/mail/partials/note.htm": {Data: []byte(`name = "Note"
|
||||||
|
==
|
||||||
|
NOTE: {{ .text }}
|
||||||
|
==
|
||||||
|
<div class="note">{{ .text }}</div>
|
||||||
`)},
|
`)},
|
||||||
}
|
}
|
||||||
|
|
||||||
@@ -71,3 +83,153 @@ func ExampleMailer_Send() {
|
|||||||
// true
|
// true
|
||||||
// true 1
|
// true 1
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// sendWelcome sends the welcome mail through the mailer published at boot.
|
||||||
|
func sendWelcome(ctx context.Context, app *backpack.App, email, name string) error {
|
||||||
|
mailer, ok := app.Lookup[postcard.Mailer]()
|
||||||
|
if !ok {
|
||||||
|
return errors.New("mailer not published")
|
||||||
|
}
|
||||||
|
return mailer.Send(ctx, postcard.Message{
|
||||||
|
Template: "acme.blog::mail.welcome",
|
||||||
|
To: []string{email},
|
||||||
|
Vars: map[string]any{"name": name},
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
func TestWelcomeMail(t *testing.T) {
|
||||||
|
mailFS := fstest.MapFS{"views/mail/welcome.htm": {Data: []byte("subject = \"Welcome, {{ .name }}\"\n==\nHi **{{ .name }}**.\n")}}
|
||||||
|
cat := postcard.NewCatalog()
|
||||||
|
if err := cat.Register("acme.blog", mailFS, []string{"acme.blog::mail.welcome"}, nil); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
driver := postcard.NewMemoryDriver()
|
||||||
|
mailer := postcard.NewMailer(cat, driver, postcard.Options{From: "blog@example.com"})
|
||||||
|
msg := postcard.Message{Template: "acme.blog::mail.welcome", To: []string{"ada@example.com"}, Vars: map[string]any{"name": "Ada"}}
|
||||||
|
if err := mailer.Send(context.Background(), msg); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := driver.Messages()[0].Subject; got != "Welcome, Ada" {
|
||||||
|
t.Fatalf("subject = %q", got)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// BlogPlugin is the acme.blog plugin; only its mail partials are shown.
|
||||||
|
type BlogPlugin struct{}
|
||||||
|
|
||||||
|
var _ pact.HasMailPartials = BlogPlugin{}
|
||||||
|
|
||||||
|
func (BlogPlugin) ID() string { return "acme.blog" }
|
||||||
|
|
||||||
|
func (BlogPlugin) MailPartialsFS() fs.FS { return mailFS }
|
||||||
|
|
||||||
|
func (BlogPlugin) MailPartials() []string {
|
||||||
|
return []string{"acme.blog::mail.partials.note"}
|
||||||
|
}
|
||||||
|
|
||||||
|
// fixedOverrides overrides one template with a fixed subject and body.
|
||||||
|
type fixedOverrides struct{}
|
||||||
|
|
||||||
|
func (fixedOverrides) MailOverrides(_ context.Context, template string) (postcard.Overrides, error) {
|
||||||
|
if template != "acme.blog::mail.welcome" {
|
||||||
|
return postcard.Overrides{}, nil
|
||||||
|
}
|
||||||
|
return postcard.Overrides{Template: &postcard.TemplateOverride{
|
||||||
|
Subject: "Hello, {{ .name }}",
|
||||||
|
Body: "Good to see you, **{{ .name }}**.",
|
||||||
|
}}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func newTestMailer(cat *postcard.Catalog, driver postcard.Driver) postcard.Mailer {
|
||||||
|
return postcard.NewMailer(cat, driver, postcard.Options{Overrides: fixedOverrides{}})
|
||||||
|
}
|
||||||
|
|
||||||
|
// previewWelcome renders an edited welcome mail without saving it.
|
||||||
|
func previewWelcome(ctx context.Context, app *backpack.App, subject, body string) (postcard.Preview, error) {
|
||||||
|
editor, ok := postcard.EditorFrom(app)
|
||||||
|
if !ok {
|
||||||
|
return postcard.Preview{}, errors.New("mailer not published")
|
||||||
|
}
|
||||||
|
draft := postcard.Draft{
|
||||||
|
Kind: postcard.KindTemplate,
|
||||||
|
Name: "acme.blog::mail.welcome",
|
||||||
|
Subject: subject,
|
||||||
|
Body: body,
|
||||||
|
}
|
||||||
|
if problem := editor.Validate(ctx, draft); problem != nil {
|
||||||
|
// problem.Field and problem.Rule say what to show next to which field.
|
||||||
|
return postcard.Preview{}, problem
|
||||||
|
}
|
||||||
|
return editor.Preview(ctx, draft)
|
||||||
|
}
|
||||||
|
|
||||||
|
// docsCatalog registers the example's welcome template and blog layout.
|
||||||
|
func docsCatalog(t *testing.T) *postcard.Catalog {
|
||||||
|
t.Helper()
|
||||||
|
cat := postcard.NewCatalog()
|
||||||
|
err := cat.Register("acme.blog", mailFS,
|
||||||
|
[]string{"acme.blog::mail.welcome"},
|
||||||
|
map[string]string{"blog": "acme.blog::mail.layouts.blog"})
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
return cat
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDocsMailer publishes a mailer on an app, boots BlogPlugin's partials
|
||||||
|
// into it and runs sendWelcome, previewWelcome and newTestMailer.
|
||||||
|
func TestDocsMailer(t *testing.T) {
|
||||||
|
ctx := t.Context()
|
||||||
|
app := backpack.New(&compass.Config{})
|
||||||
|
if err := sendWelcome(ctx, app, "ada@example.com", "Ada"); err == nil {
|
||||||
|
t.Fatal("sendWelcome without a mailer succeeded")
|
||||||
|
}
|
||||||
|
driver := postcard.NewMemoryDriver()
|
||||||
|
if err := app.Publish(postcard.NewMailer(docsCatalog(t), driver, postcard.Options{From: "blog@example.com"})); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if err := postcard.BootPlugin(app, BlogPlugin{}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := sendWelcome(ctx, app, "ada@example.com", "Ada"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := driver.Messages()[0].Subject; got != "Welcome, Ada" {
|
||||||
|
t.Fatalf("subject = %q", got)
|
||||||
|
}
|
||||||
|
|
||||||
|
preview, err := previewWelcome(ctx, app, "Hi {{ .name }}",
|
||||||
|
"Thanks for joining.\n\n{{ partial \"acme.blog::mail.partials.note\" \"text\" \"Reply any time\" }}\n")
|
||||||
|
if err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if !strings.Contains(preview.HTML, `<div class="note">Reply any time</div>`) || !strings.Contains(preview.Text, "NOTE: Reply any time") {
|
||||||
|
t.Fatalf("preview = %+v", preview)
|
||||||
|
}
|
||||||
|
var problem *postcard.DraftError
|
||||||
|
if _, err := previewWelcome(ctx, app, "Hi {{ .name", "Body"); !errors.As(err, &problem) || problem.Field != "subject" {
|
||||||
|
t.Fatalf("broken subject: %v", err)
|
||||||
|
}
|
||||||
|
|
||||||
|
// The declarations BootPlugin and the mailer call through interfaces.
|
||||||
|
p := BlogPlugin{}
|
||||||
|
if names := p.MailPartials(); len(names) != 1 {
|
||||||
|
t.Fatalf("MailPartials() = %v", names)
|
||||||
|
}
|
||||||
|
if _, err := fs.Stat(p.MailPartialsFS(), "views/mail/partials/note.htm"); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if o, err := (fixedOverrides{}).MailOverrides(ctx, "acme.blog::mail.other"); err != nil || o.Template != nil {
|
||||||
|
t.Fatalf("MailOverrides(other) = %+v, %v", o, err)
|
||||||
|
}
|
||||||
|
|
||||||
|
overridden := postcard.NewMemoryDriver()
|
||||||
|
mailer := newTestMailer(docsCatalog(t), overridden)
|
||||||
|
if err := mailer.Send(ctx, postcard.Message{Template: "acme.blog::mail.welcome", To: []string{"ada@example.com"}, Vars: map[string]any{"name": "Ada"}}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
if got := overridden.Messages()[0]; got.Subject != "Hello, Ada" || !strings.Contains(got.Text, "Good to see you, **Ada**.") {
|
||||||
|
t.Fatalf("overridden = %q %q", got.Subject, got.Text)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
@@ -32,57 +32,60 @@ Use cases:
|
|||||||
|
|
||||||
A content plugin registers its types:
|
A content plugin registers its types:
|
||||||
|
|
||||||
```go
|
```go src=modules/signpost/example_test.go#BlogPlugin.MenuItemTypes
|
||||||
package blog
|
// MenuItemTypes registers acme-post, which points at one post, and
|
||||||
|
// acme-all-posts, which lists every post. The list type names acme-post in
|
||||||
import (
|
// PatternFrom, so a host override of the post URL reaches its items too.
|
||||||
"context"
|
func (p BlogPlugin) MenuItemTypes() []pact.MenuItemType {
|
||||||
"strings"
|
|
||||||
|
|
||||||
"git.golem15.com/golem15/summercms/modules/pact"
|
|
||||||
)
|
|
||||||
|
|
||||||
var _ pact.HasMenuItemTypes = (*Plugin)(nil)
|
|
||||||
|
|
||||||
type Plugin struct{}
|
|
||||||
|
|
||||||
func (p *Plugin) MenuItemTypes() []pact.MenuItemType {
|
|
||||||
return []pact.MenuItemType{{
|
return []pact.MenuItemType{{
|
||||||
Key: "acme-post",
|
Key: "acme-post",
|
||||||
Label: "acme.blog::lang.menuitem.post",
|
Label: "acme.blog::lang.menuitem.post",
|
||||||
DefaultPattern: "/blog/:slug",
|
DefaultPattern: "/blog/:slug",
|
||||||
Placeholders: []string{":slug"},
|
Placeholders: []string{":slug"},
|
||||||
References: func(ctx context.Context) ([]pact.MenuItemReference, error) {
|
References: p.postReferences,
|
||||||
return []pact.MenuItemReference{{Value: "hello-world", Label: "Hello world"}}, nil
|
Resolve: p.resolvePost,
|
||||||
},
|
|
||||||
Resolve: func(ctx context.Context, in pact.MenuItemResolve) (*pact.ResolvedMenuItem, error) {
|
|
||||||
url := strings.ReplaceAll(in.Pattern, ":slug", in.Reference)
|
|
||||||
return &pact.ResolvedMenuItem{
|
|
||||||
Title: "Hello world",
|
|
||||||
URL: url,
|
|
||||||
Alternates: []pact.MenuItemAlternate{{Locale: "en", URL: url, Title: "Hello world"}},
|
|
||||||
}, nil
|
|
||||||
},
|
|
||||||
}, {
|
}, {
|
||||||
Key: "acme-all-posts",
|
Key: "acme-all-posts",
|
||||||
Label: "acme.blog::lang.menuitem.all_posts",
|
Label: "acme.blog::lang.menuitem.all_posts",
|
||||||
DefaultPattern: "/blog/:slug",
|
DefaultPattern: "/blog/:slug",
|
||||||
PatternFrom: "acme-post",
|
PatternFrom: "acme-post",
|
||||||
Nesting: true,
|
Nesting: true,
|
||||||
Resolve: resolveAllPosts,
|
DynamicItems: true,
|
||||||
|
Resolve: p.resolveAllPosts,
|
||||||
}}
|
}}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
A menu plugin resolves an entry and serves the reference dropdown of its form:
|
A menu plugin resolves an entry and serves the reference dropdown of its form:
|
||||||
|
|
||||||
```go
|
```go src=modules/signpost/example_test.go#ExampleRegistry_Resolve
|
||||||
|
app := exampleApp()
|
||||||
|
blog := BlogPlugin{posts: []BlogPost{{Slug: "hello", Title: "Hello"}, {Slug: "again", Title: "Again"}}}
|
||||||
|
if err := signpost.Activate(app, []BlogPlugin{blog}); err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
reg, _ := app.Lookup[*signpost.Registry]()
|
reg, _ := app.Lookup[*signpost.Registry]()
|
||||||
item, err := reg.Resolve(ctx, entry.Type, entry.Reference, entry.URLPattern, true, "")
|
item, err := reg.Resolve(context.Background(), "acme-all-posts", "", "", true, "")
|
||||||
|
if err != nil {
|
||||||
|
fmt.Println(err)
|
||||||
|
return
|
||||||
|
}
|
||||||
|
for _, child := range item.Items {
|
||||||
|
fmt.Println(child.Title, child.URL)
|
||||||
|
}
|
||||||
|
// Output:
|
||||||
|
// Hello /news/hello
|
||||||
|
// Again /news/again
|
||||||
|
```
|
||||||
|
|
||||||
func (c entriesController) DependentOptions(ctx context.Context, field string, values map[string]any) (pact.DependentOptionSet, error) {
|
```go src=modules/signpost/example_test.go#EntriesController.DependentOptions
|
||||||
|
// DependentOptions serves the reference dropdown: the references of the
|
||||||
|
// menu item type chosen in the type field, with their depth.
|
||||||
|
func (c EntriesController) DependentOptions(ctx context.Context, field string, values map[string]any) (pact.DependentOptionSet, error) {
|
||||||
typ, _ := values["type"].(string)
|
typ, _ := values["type"].(string)
|
||||||
return signpost.ReferenceOptions(ctx, c.registry(), typ)
|
reg, _ := c.app.Lookup[*signpost.Registry]()
|
||||||
|
return signpost.ReferenceOptions(ctx, reg, typ)
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
@@ -90,38 +93,64 @@ func (c entriesController) DependentOptions(ctx context.Context, field string, v
|
|||||||
|
|
||||||
A record type adds a `pact.ContentDescriptor`: the admin controller that edits the records, their morph type, and a `Describe` that answers each locale's URL (built from the pattern it receives, as `Resolve` builds alternates), title, description, image and word count:
|
A record type adds a `pact.ContentDescriptor`: the admin controller that edits the records, their morph type, and a `Describe` that answers each locale's URL (built from the pattern it receives, as `Resolve` builds alternates), title, description, image and word count:
|
||||||
|
|
||||||
```go
|
```go src=modules/signpost/example_content_test.go#NewsPlugin.MenuItemTypes
|
||||||
{
|
// MenuItemTypes registers acme-article with a content descriptor: the
|
||||||
Key: "acme-post",
|
// controller that edits articles, their morph type, what kind of record an
|
||||||
DefaultPattern: "/blog/:slug",
|
// article is, the MCP tool that edits one, Describe and Match.
|
||||||
Resolve: resolvePost,
|
func (p NewsPlugin) MenuItemTypes() []pact.MenuItemType {
|
||||||
Content: &pact.ContentDescriptor{
|
return []pact.MenuItemType{{
|
||||||
Controller: "acme.blog.posts",
|
Key: "acme-article",
|
||||||
Model: "acme_blog_posts",
|
Label: "acme.news::lang.menuitem.article",
|
||||||
Describe: func(ctx context.Context, in pact.ContentDescribe) (*pact.ContentRecord, error) {
|
DefaultPattern: "/news/:slug",
|
||||||
post, err := loadPost(ctx, in.ID)
|
Placeholders: []string{":slug", ":id"},
|
||||||
if err != nil || post == nil {
|
Resolve: p.resolve,
|
||||||
return nil, err
|
Content: &pact.ContentDescriptor{
|
||||||
}
|
Controller: "acme.news.articles",
|
||||||
return &pact.ContentRecord{
|
Model: "acme_news_articles",
|
||||||
ID: in.ID,
|
Kind: pact.ContentKindArticle,
|
||||||
Published: post.Published,
|
Tools: map[string]string{pact.ContentToolEdit: "acme_update_article"},
|
||||||
Locales: []pact.ContentLocale{{
|
Describe: p.describe,
|
||||||
Locale: "en",
|
Match: p.match,
|
||||||
URL: strings.ReplaceAll(in.Pattern, ":slug", post.Slug),
|
|
||||||
Title: post.Title,
|
|
||||||
}},
|
|
||||||
}, nil
|
|
||||||
},
|
},
|
||||||
},
|
}}
|
||||||
}
|
}
|
||||||
```
|
```
|
||||||
|
|
||||||
The descriptor may also say what kind of record the type holds and which MCP tool edits one (`Kind: pact.ContentKindArticle`, `Tools: map[string]string{pact.ContentToolEdit: "acme_update_post"}`), and `Describe` may report the record's `PublishedAt`, `Parents`, `Authors` and `TopHeading`, and per locale its `Images`, `Videos` and `Headings` (see [Content descriptors](../../docs/plugins/menu-item-types.md#content-descriptors)). Every one of them is optional.
|
```go src=modules/signpost/example_content_test.go#NewsPlugin.describe
|
||||||
|
// describe answers one article per locale; the URL is built from the
|
||||||
|
// layered pattern it receives. Besides the page defaults it reports the
|
||||||
|
// first publication, the author and the body's heading outline, whose
|
||||||
|
// headings start at level 2 because the page renders the title as the level-1
|
||||||
|
// heading.
|
||||||
|
func (p NewsPlugin) describe(_ context.Context, in pact.ContentDescribe) (*pact.ContentRecord, error) {
|
||||||
|
for _, a := range p.articles {
|
||||||
|
if a.ID != in.ID {
|
||||||
|
continue
|
||||||
|
}
|
||||||
|
url := strings.NewReplacer(":slug", a.Slug, ":id", a.ID).Replace(in.Pattern)
|
||||||
|
headings := []pact.ContentHeading{}
|
||||||
|
for _, h := range a.Headings {
|
||||||
|
headings = append(headings, pact.ContentHeading{Level: 2, Text: h})
|
||||||
|
}
|
||||||
|
published := a.PublishedAt
|
||||||
|
return &pact.ContentRecord{
|
||||||
|
ID: a.ID,
|
||||||
|
Published: a.Published,
|
||||||
|
PublishedAt: &published,
|
||||||
|
Authors: []pact.ContentPerson{{Name: a.Author}},
|
||||||
|
TopHeading: 2,
|
||||||
|
Locales: []pact.ContentLocale{{Locale: "en", URL: url, Title: a.Title, Headings: headings}},
|
||||||
|
}, nil
|
||||||
|
}
|
||||||
|
return nil, nil
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The descriptor may also say what kind of record the type holds and which MCP tool edits one (`Kind` and `Tools` above), match a public path back to a record (`Match`), and `Describe` may report the record's `PublishedAt`, `Parents`, `Authors` and `TopHeading`, and per locale its `Images`, `Videos` and `Headings` (see [Content descriptors](../../docs/plugins/menu-item-types.md#content-descriptors)). Every one of them is optional.
|
||||||
|
|
||||||
A consumer maps a record event to its type and reads the record's new URL:
|
A consumer maps a record event to its type and reads the record's new URL:
|
||||||
|
|
||||||
```go
|
```go src=modules/signpost/example_content_test.go#listen
|
||||||
app.Events.Listen("acme.audit", func(ctx context.Context, ev *pact.RecordSaved) error {
|
app.Events.Listen("acme.audit", func(ctx context.Context, ev *pact.RecordSaved) error {
|
||||||
reg, _ := app.Lookup[*signpost.Registry]()
|
reg, _ := app.Lookup[*signpost.Registry]()
|
||||||
typ, ok := reg.ContentTypeForModel(ev.Model)
|
typ, ok := reg.ContentTypeForModel(ev.Model)
|
||||||
@@ -132,7 +161,7 @@ app.Events.Listen("acme.audit", func(ctx context.Context, ev *pact.RecordSaved)
|
|||||||
if err != nil || rec == nil {
|
if err != nil || rec == nil {
|
||||||
return err
|
return err
|
||||||
}
|
}
|
||||||
log.Printf("%s now lives at %s", ev.ID, rec.Locales[0].URL)
|
logger.Printf("%s now lives at %s", ev.ID, rec.Locales[0].URL)
|
||||||
return nil
|
return nil
|
||||||
})
|
})
|
||||||
```
|
```
|
||||||
|
|||||||
@@ -1,11 +1,15 @@
|
|||||||
package signpost_test
|
package signpost_test
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"log"
|
||||||
"strings"
|
"strings"
|
||||||
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
"git.golem15.com/golem15/summercms/modules/backpack"
|
||||||
"git.golem15.com/golem15/summercms/modules/pact"
|
"git.golem15.com/golem15/summercms/modules/pact"
|
||||||
"git.golem15.com/golem15/summercms/modules/signpost"
|
"git.golem15.com/golem15/summercms/modules/signpost"
|
||||||
)
|
)
|
||||||
@@ -130,3 +134,46 @@ func ExampleRegistry_MatchPath() {
|
|||||||
// 2026-10-01 Ada 2 2
|
// 2026-10-01 Ada 2 2
|
||||||
// acme-article 7 true
|
// acme-article 7 true
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// listenForMoves registers a consumer that maps every saved record to its
|
||||||
|
// content type and logs the record's URL.
|
||||||
|
func listenForMoves(app *backpack.App, logger *log.Logger) {
|
||||||
|
// docs:start listen
|
||||||
|
app.Events.Listen("acme.audit", func(ctx context.Context, ev *pact.RecordSaved) error {
|
||||||
|
reg, _ := app.Lookup[*signpost.Registry]()
|
||||||
|
typ, ok := reg.ContentTypeForModel(ev.Model)
|
||||||
|
if !ok {
|
||||||
|
return nil
|
||||||
|
}
|
||||||
|
rec, err := reg.Describe(ctx, typ.Key, ev.ID, "")
|
||||||
|
if err != nil || rec == nil {
|
||||||
|
return err
|
||||||
|
}
|
||||||
|
logger.Printf("%s now lives at %s", ev.ID, rec.Locales[0].URL)
|
||||||
|
return nil
|
||||||
|
})
|
||||||
|
// docs:end listen
|
||||||
|
}
|
||||||
|
|
||||||
|
// TestDocsRecordListener fires record events for an article and for a model
|
||||||
|
// no content type declares through listenForMoves.
|
||||||
|
func TestDocsRecordListener(t *testing.T) {
|
||||||
|
app := exampleApp() // its menu_items.yaml overrides acme-post of BlogPlugin
|
||||||
|
news := NewsPlugin{articles: []Article{{ID: "7", Slug: "launch", Title: "Launch", Published: true}}}
|
||||||
|
if err := signpost.Activate(app, []interface{ ID() string }{BlogPlugin{}, news}); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
var buf bytes.Buffer
|
||||||
|
listenForMoves(app, log.New(&buf, "", 0))
|
||||||
|
for _, ev := range []*pact.RecordSaved{
|
||||||
|
{Model: "acme_news_articles", ID: "7"},
|
||||||
|
{Model: "acme_shop_orders", ID: "3"},
|
||||||
|
} {
|
||||||
|
if err := app.Events.Fire(t.Context(), ev); err != nil {
|
||||||
|
t.Fatal(err)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if got, want := buf.String(), "7 now lives at /news/launch\n"; got != want {
|
||||||
|
t.Fatalf("log = %q, want %q", got, want)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user