Skip to content

Commit

Permalink
bind interface{ Arrow() Arrow }
Browse files Browse the repository at this point in the history
  • Loading branch information
fogfish committed Aug 18, 2023
1 parent 15fa7ac commit 3f15064
Show file tree
Hide file tree
Showing 2 changed files with 50 additions and 1 deletion.
16 changes: 16 additions & 0 deletions http/types.go
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,22 @@ func Join(arrows ...Arrow) Arrow {
}
}

// Bind composes HTTP arrows to high-order function
// In contrast with Join, input is arrow builders
// (a ⟼ b, b ⟼ c, c ⟼ d) ⤇ a ⟼ d
func Bind(arrows ...interface{ Arrow() Arrow }) Arrow {
return func(cat *Context) error {
for _, arrow := range arrows {
f := arrow.Arrow()
if err := f(cat); err != nil {
return err
}
}

return nil
}
}

// GET composes HTTP arrows to high-order function for HTTP GET request
// (a ⟼ b, b ⟼ c, c ⟼ d) ⤇ a ⟼ d
func GET(arrows ...Arrow) Arrow { return method(http.MethodGet, arrows) }
Expand Down
35 changes: 34 additions & 1 deletion http/types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -67,8 +67,13 @@ func TestJoin(t *testing.T) {
defer ts.Close()

req := µ.GET(
ø.URI("%s/ok", ø.Authority(ts.URL)),
ø.URI("%s/opts", ø.Authority(ts.URL)),
µ.Join(
ø.Param("a", "1"),
ø.Param("b", "2"),
),
ƒ.Code(µ.StatusOK),
ƒ.Match(`{"opts": "a=1&b=2"}`),
)
cat := µ.New()
err := cat.IO(context.Background(), req)
Expand Down Expand Up @@ -100,6 +105,31 @@ func TestJoinCats(t *testing.T) {
)
}

type opt struct{ key, val string }

func (opt opt) Arrow() µ.Arrow { return ø.Param(opt.key, opt.val) }

func TestBind(t *testing.T) {
ts := mock()
defer ts.Close()

req := µ.GET(
ø.URI("%s/opts", ø.Authority(ts.URL)),
µ.Bind(
opt{"a", "1"},
opt{"b", "2"},
),
ƒ.Code(µ.StatusOK),
ƒ.Match(`{"opts": "a=1&b=2"}`),
)
cat := µ.New()
err := cat.IO(context.Background(), req)

it.Then(t).Should(
it.Nil(err),
)
}

func TestIOWithContext(t *testing.T) {
ts := mock()
defer ts.Close()
Expand Down Expand Up @@ -189,6 +219,9 @@ func mock() *httptest.Server {
w.Write([]byte("site=example.com"))
case r.URL.Path == "/ok":
w.WriteHeader(http.StatusOK)
case r.URL.Path == "/opts":
w.Header().Add("Content-Type", "application/json")
w.Write([]byte(`{"opts": "` + r.URL.RawQuery + `"}`))
default:
w.WriteHeader(http.StatusBadRequest)
}
Expand Down

0 comments on commit 3f15064

Please sign in to comment.