Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 18 additions & 2 deletions docs-site/content/docs/reference/user.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -13,12 +13,28 @@ Look at a seller. USER is a user hash, a profile URL, or the web slug (name-1234

## `wallapop user items`

Active listings
Active Items

```bash
wallapop user items USER
wallapop user items USER [flags]
```

List a seller's active Items. Wallapop pages this endpoint 40 Items at a
time: a plain call returns one page with its next_page cursor, --all walks
every page (bounded at 50 pages), --next resumes from a previous cursor
(single page, or the whole walk when combined with --all).

```bash
wallapop user items p8j35kmwr7z9
wallapop user items p8j35kmwr7z9 --all
wallapop user items p8j35kmwr7z9 --next "$(wallapop user items p8j35kmwr7z9 | jq -r .next_page)"
```

| Flag | Type | Default | Description |
| --- | --- | --- | --- |
| `--all` | bool | `false` | walk every page until exhausted (bounded) |
| `--next` | string | - | continue from a previous next_page token |

## `wallapop user reviews`

Reviews received
Expand Down
156 changes: 156 additions & 0 deletions internal/cli/cli_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -516,6 +516,162 @@ func TestUserBySlugURLAndHash(t *testing.T) {
}
}

// user items pagination

func TestUserItemsReturnsPageWithNextCursor(t *testing.T) {
h := newHarness(t)
h.login()
h.fake.UserItemsPageSize = 2
for i := 0; i < 5; i++ {
h.fake.AddItem(fakewallapop.Item{Hash: "hash" + padHash(i), Title: "Bike", Seller: fakewallapop.OtherHash})
}
r := h.must("", "user", "items", fakewallapop.OtherHash)
var page struct {
Items []struct{ Hash string }
NextPage string `json:"next_page"`
}
decode(t, r.stdout, &page)
if len(page.Items) != 2 || page.NextPage == "" {
t.Fatalf("got %d items, next %q", len(page.Items), page.NextPage)
}
reqs := h.fake.RequestsTo("/api/v3/users/" + fakewallapop.OtherHash + "/items")
if len(reqs) != 1 || reqs[0].Query.Get("since") != "" {
t.Fatalf("first page request: %d, query %v", len(reqs), reqs[0].Query)
}
next := page.NextPage

r = h.must("", "user", "items", fakewallapop.OtherHash, "--next", next)
decode(t, r.stdout, &page)
if len(page.Items) != 2 {
t.Fatalf("second page got %d items", len(page.Items))
}
reqs = h.fake.RequestsTo("/api/v3/users/" + fakewallapop.OtherHash + "/items")
if len(reqs) != 2 || reqs[1].Query.Get("since") != next {
t.Fatalf("second page did not pass since=%q: %v", next, reqs[len(reqs)-1].Query)
}
if page.NextPage == "" {
t.Fatal("second page lost the next cursor")
}

r = h.must("", "user", "items", fakewallapop.OtherHash, "--next", page.NextPage)
var last map[string]any
decode(t, r.stdout, &last)
if got, ok := last["next_page"]; !ok || got != "" {
t.Fatalf("last page must carry an empty next_page key, got %q present=%v", got, ok)
}
if n := len(last["items"].([]any)); n != 1 {
t.Fatalf("last page: %d items", n)
}
}

func TestUserItemsAllWalksEveryPage(t *testing.T) {
h := newHarness(t)
h.login()
h.fake.UserItemsPageSize = 2
for i := 0; i < 5; i++ {
h.fake.AddItem(fakewallapop.Item{Hash: "hash" + padHash(i), Title: "Bike", Seller: fakewallapop.OtherHash})
}
r := h.must("", "user", "items", fakewallapop.OtherHash, "--all")
var page struct {
Items []struct{ Hash string }
NextPage string `json:"next_page"`
}
decode(t, r.stdout, &page)
if len(page.Items) != 5 || page.NextPage != "" {
Comment thread
sourcery-ai[bot] marked this conversation as resolved.
Resolved
t.Fatalf("got %d items, next %q", len(page.Items), page.NextPage)
}
// Count alone would let a duplicate hide an omission: assert the whole
// ordered listing.
want := []string{"hash00000000", "hash00000001", "hash00000002", "hash00000003", "hash00000004"}
for i, it := range page.Items {
if it.Hash != want[i] {
t.Fatalf("item %d = %s, want %s", i, it.Hash, want[i])
}
}
if n := len(h.fake.RequestsTo("/api/v3/users/" + fakewallapop.OtherHash + "/items")); n != 3 {
t.Fatalf("expected 3 sequential page requests, got %d", n)
}
if strings.Contains(r.stderr, "warning") {
t.Fatalf("unexpected warning: %s", r.stderr)
}
}

func TestUserItemsAllStopsAtBoundWithWarning(t *testing.T) {
h := newHarness(t)
h.login()
h.fake.UserItemsPageSize = 1
for i := 0; i < 60; i++ {
h.fake.AddItem(fakewallapop.Item{Hash: "hash" + padHash(i), Title: "Bike", Seller: fakewallapop.OtherHash})
}
r := h.must("", "user", "items", fakewallapop.OtherHash, "--all")
var page struct {
Items []struct{ Hash string }
NextPage string `json:"next_page"`
}
decode(t, r.stdout, &page)
if len(page.Items) != 50 || page.NextPage != "50" {
t.Fatalf("bound walk: %d items, next %q", len(page.Items), page.NextPage)
}
if !strings.Contains(r.stderr, "stopped after 50 pages") {
t.Fatalf("missing bound warning: %s", r.stderr)
}
if n := len(h.fake.RequestsTo("/api/v3/users/" + fakewallapop.OtherHash + "/items")); n != 50 {
t.Fatalf("expected bounded 50 requests, got %d", n)
}
resume := h.must("", "user", "items", fakewallapop.OtherHash, "--next", page.NextPage)
var resumed struct {
Items []struct{ Hash string } `json:"items"`
}
decode(t, resume.stdout, &resumed)
if len(resumed.Items) != 1 || resumed.Items[0].Hash != "hash00000050" {
t.Fatalf("resume from %q returned %d items starting at %q", page.NextPage, len(resumed.Items), resumed.Items[0].Hash)
}
}

func TestUserItemsAllRejectsRepeatedCursor(t *testing.T) {
h := newHarness(t)
h.login()
h.fake.UserItemsPageSize = 1
h.fake.UserItemsStickyCursor = "1"
for i := 0; i < 3; i++ {
h.fake.AddItem(fakewallapop.Item{Hash: "hash" + padHash(i), Title: "Bike", Seller: fakewallapop.OtherHash})
}
r := h.run("", "user", "items", fakewallapop.OtherHash, "--all")
if r.code == 0 || !strings.Contains(r.stderr, "cursor did not advance") {
t.Fatalf("expected stalled cursor error, exit %d stderr %q", r.code, r.stderr)
}
var partial struct {
Items []struct{ Hash string } `json:"items"`
Next string `json:"next_page"`
}
decode(t, r.stdout, &partial)
if len(partial.Items) != 2 || partial.Next != "1" {
t.Fatalf("stalled walk lost partial results/cursor: %+v", partial)
}
}

func TestUserItemsAllPreservesPagesWhenLaterRequestFails(t *testing.T) {
h := newHarness(t)
h.login()
h.fake.UserItemsPageSize = 2
h.fake.UserItemsFailSince = "2"
for i := 0; i < 5; i++ {
h.fake.AddItem(fakewallapop.Item{Hash: "hash" + padHash(i), Title: "Bike", Seller: fakewallapop.OtherHash})
}
r := h.run("", "user", "items", fakewallapop.OtherHash, "--all")
if r.code == 0 || !strings.Contains(r.stderr, "500") {
t.Fatalf("expected later-page error, exit %d stderr %q", r.code, r.stderr)
}
var partial struct {
Items []struct{ Hash string } `json:"items"`
Next string `json:"next_page"`
}
decode(t, r.stdout, &partial)
if len(partial.Items) != 2 || partial.Next != "2" {
t.Fatalf("failed walk lost partial results/cursor: %+v", partial)
}
}

// chat

func TestChatSendPublishesWebShapedPayload(t *testing.T) {
Expand Down
99 changes: 86 additions & 13 deletions internal/cli/item.go
Original file line number Diff line number Diff line change
Expand Up @@ -575,6 +575,16 @@ func (v reviewsView) Pretty(w io.Writer, color bool) {
output.Table(w, color, []string{"DATE", "SCORE", "BY", "ITEM", "COMMENT"}, rows)
}

// userItemsView is itemsView for `user items`, with next_page always present:
// an absent key would be indistinguishable from a CLI without pagination, so
// consumers reading the field explicitly get "" on the last page.
type userItemsView struct {
Items []wallapop.Item `json:"items"`
NextPage string `json:"next_page"`
}

func (v userItemsView) Pretty(w io.Writer, color bool) { itemsView(v).Pretty(w, color) }

func (a *App) userCmd() *cobra.Command {
cmd := &cobra.Command{
Use: "user",
Expand All @@ -584,35 +594,67 @@ func (a *App) userCmd() *cobra.Command {
resolve := func(cmd *cobra.Command, ref string) (string, error) {
return a.Client.ResolveUserHash(cmd.Context(), ref)
}
cmd.AddCommand(
&cobra.Command{
Use: "show USER", Short: "Profile and stats", Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
hash, err := resolve(cmd, args[0])
var itemsNext string
var itemsAll bool
var itemsCmd = &cobra.Command{
Use: "items USER", Short: "Active Items", Args: cobra.ExactArgs(1),
Long: `List a seller's active Items. Wallapop pages this endpoint 40 Items at a
time: a plain call returns one page with its next_page cursor, --all walks
every page (bounded at 50 pages), --next resumes from a previous cursor
(single page, or the whole walk when combined with --all).

Examples:
wallapop user items p8j35kmwr7z9
wallapop user items p8j35kmwr7z9 --all
wallapop user items p8j35kmwr7z9 --next "$(wallapop user items p8j35kmwr7z9 | jq -r .next_page)"`,
RunE: func(cmd *cobra.Command, args []string) error {
hash, err := resolve(cmd, args[0])
if err != nil {
return err
}
if itemsAll {
items, truncated, err := a.allUserItems(cmd.Context(), hash, itemsNext)
view := userItemsView{Items: items, NextPage: truncated}
if err != nil {
// The pages already fetched are still real data: print
// them (with the cursor to resume from) and then fail
// with the request error, so a partial walk need not be
// repeated from the beginning.
_ = a.Printer.Print(view)
return err
}
u, err := a.Client.User(cmd.Context(), hash)
if err != nil {
return err
if truncated != "" {
// The walk hit its bound: say so on stderr, and keep the cursor in
// the JSON so callers can pick up where this left off.
fmt.Fprintf(a.Stderr, "wallapop: warning: stopped after %d pages (%d items); more pages remain, continue with --next\n", maxUserItemPages, len(items))
}
return a.Printer.Print(userView(u))
},
return a.Printer.Print(view)
}
items, cursor, err := a.Client.UserItemsPage(cmd.Context(), hash, itemsNext)
if err != nil {
return err
}
return a.Printer.Print(userItemsView{Items: items, NextPage: cursor})
},
}
itemsCmd.Flags().StringVar(&itemsNext, "next", "", "continue from a previous next_page token")
itemsCmd.Flags().BoolVar(&itemsAll, "all", false, "walk every page until exhausted (bounded)")
cmd.AddCommand(
&cobra.Command{
Use: "items USER", Short: "Active listings", Args: cobra.ExactArgs(1),
Use: "show USER", Short: "Profile and stats", Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
hash, err := resolve(cmd, args[0])
if err != nil {
return err
}
items, err := a.Client.UserItems(cmd.Context(), hash)
u, err := a.Client.User(cmd.Context(), hash)
if err != nil {
return err
}
return a.Printer.Print(itemsView{Items: items})
return a.Printer.Print(userView(u))
},
},
itemsCmd,
&cobra.Command{
Use: "reviews USER", Short: "Reviews received", Args: cobra.ExactArgs(1),
RunE: func(cmd *cobra.Command, args []string) error {
Expand All @@ -631,6 +673,37 @@ func (a *App) userCmd() *cobra.Command {
return cmd
}

// maxUserItemPages bounds `user items --all` (40 items per page, so 2000
// items at most); hitting it is a warning, not an error.
const maxUserItemPages = 50

// allUserItems walks a seller's pages sequentially, from since ("" = start)
// until the cursor runs out or the bound is hit. When truncated, it returns
// the last cursor so the caller can warn and let consumers resume.
func (a *App) allUserItems(ctx context.Context, hash, since string) (items []wallapop.Item, truncated string, err error) {
items = []wallapop.Item{}
for page := 0; page < maxUserItemPages; page++ {
batch, cursor, err := a.Client.UserItemsPage(ctx, hash, since)
if err != nil {
// Keep what succeeded and the cursor to resume from; the caller
// prints the partial result and still reports this error.
return items, since, err
}
items = append(items, batch...)
if cursor == "" {
return items, "", nil
}
// A cursor repeated unchanged means the API stopped advancing the
// walk: report it as truncated (not exhausted) so the caller warns
// and can resume, instead of seeing an incomplete walk as complete.
if cursor == since {
return items, since, fmt.Errorf("user items pagination cursor did not advance (since=%q)", since)
}
since = cursor
}
return items, since, nil
}

func (a *App) meCmd() *cobra.Command {
cmd := &cobra.Command{Use: "me", Short: "Your own account: profile, listings, favorites"}
var sold bool
Expand Down
Loading