Skip to content

Commit

Permalink
feat(jq): use id-based filtering to preserve original objects
Browse files Browse the repository at this point in the history
  • Loading branch information
nobe4 committed May 22, 2024
1 parent e8585b2 commit 7a5cd78
Showing 1 changed file with 14 additions and 12 deletions.
26 changes: 14 additions & 12 deletions internal/jq/jq.go
Original file line number Diff line number Diff line change
Expand Up @@ -13,40 +13,42 @@ func Filter(filter string, n notifications.Notifications) (notifications.Notific
return n, nil
}

query, err := gojq.Parse(fmt.Sprintf(".[] | select(%s)", filter))
filteredIDs := []string{}

// The filter does only selection, not extraction.
query, err := gojq.Parse(fmt.Sprintf(".[] | select(%s) | .id", filter))
if err != nil {
panic(err)
}

// gojq works only on any data, so we need to convert Notifications to
// interface{}.
// This also gives us back the JSON fields from the API.
// gojq works only on `any` data, so we need to convert Notifications to
// interface{}. This also gives us back the JSON fields from the API.
notificationsRaw, err := n.ToInterface()
if err != nil {
return nil, err
}

fitleredNotificationsRaw := []interface{}{}
iter := query.Run(notificationsRaw)
for {
v, ok := iter.Next()
if !ok {
break
}

if err, ok := v.(error); ok {
if err, ok := err.(*gojq.HaltError); ok && err.Value() == nil {
break
}
panic(err)
return nil, err
}

fitleredNotificationsRaw = append(fitleredNotificationsRaw, v)
}
newId, ok := v.(string)
if !ok {
return nil, fmt.Errorf("invalid filtered id %#v", v)
}

filteredNotifications, err := notifications.FromInterface(fitleredNotificationsRaw)
if err != nil {
return nil, err
filteredIDs = append(filteredIDs, newId)
}

return filteredNotifications, nil
return n.FilterFromIds(filteredIDs), nil
}

0 comments on commit 7a5cd78

Please sign in to comment.