Add GetUserByID (#513)

Co-authored-by: Jochen Hunz <j.hunz@anchorpoint.app>
Co-authored-by: Lunny Xiao <xiaolunwen@gmail.com>
Reviewed-on: https://gitea.com/gitea/go-sdk/pulls/513
Reviewed-by: 6543 <6543@obermui.de>
Reviewed-by: Lunny Xiao <xiaolunwen@gmail.com>
Co-authored-by: J0Nes90 <j0nes90@noreply.gitea.io>
Co-committed-by: J0Nes90 <j0nes90@noreply.gitea.io>
This commit is contained in:
J0Nes90 2021-04-05 11:23:50 +08:00 committed by 6543
parent 00ddb6b116
commit e11a4f7f3b
3 changed files with 56 additions and 3 deletions

View file

@ -6,6 +6,8 @@ package gitea
import (
"fmt"
"net/url"
"strconv"
"time"
)
@ -44,3 +46,24 @@ func (c *Client) GetMyUserInfo() (*User, *Response, error) {
resp, err := c.getParsedResponse("GET", "/user", nil, nil, u)
return u, resp, err
}
// GetUserByID returns user by a given user ID
func (c *Client) GetUserByID(id int64) (*User, *Response, error) {
if id < 0 {
return nil, nil, fmt.Errorf("invalid user id %d", id)
}
query := make(url.Values)
query.Add("uid", strconv.FormatInt(id, 10))
users, resp, err := c.searchUsers(query.Encode())
if err != nil {
return nil, resp, err
}
if len(users) == 1 {
return users[0], resp, err
}
return nil, resp, fmt.Errorf("user not found with id %d", id)
}

View file

@ -34,11 +34,15 @@ func (opt *SearchUsersOption) QueryEncode() string {
return query.Encode()
}
// SearchUsers finds users by query
func (c *Client) SearchUsers(opt SearchUsersOption) ([]*User, *Response, error) {
func (c *Client) searchUsers(rawQuery string) ([]*User, *Response, error) {
link, _ := url.Parse("/users/search")
link.RawQuery = opt.QueryEncode()
link.RawQuery = rawQuery
userResp := new(searchUsersResponse)
resp, err := c.getParsedResponse("GET", link.String(), nil, nil, &userResp)
return userResp.Users, resp, err
}
// SearchUsers finds users by query
func (c *Client) SearchUsers(opt SearchUsersOption) ([]*User, *Response, error) {
return c.searchUsers(opt.QueryEncode())
}

View file

@ -171,6 +171,32 @@ func TestUserEmail(t *testing.T) {
assert.NoError(t, err)
}
func TestGetUserByID(t *testing.T) {
log.Println("== TestGetUserByID ==")
c := newTestClient()
user1 := createTestUser(t, "user1", c)
user2 := createTestUser(t, "user2", c)
r1, _, err := c.GetUserByID(user1.ID)
assert.NoError(t, err)
assert.NotNil(t, r1)
assert.Equal(t, user1.UserName, r1.UserName)
r2, _, err := c.GetUserByID(user2.ID)
assert.NoError(t, err)
assert.NotNil(t, r2)
assert.Equal(t, user2.UserName, r2.UserName)
r3, _, err := c.GetUserByID(42)
assert.Error(t, err)
assert.Nil(t, r3)
r4, _, err := c.GetUserByID(-1)
assert.Error(t, err)
assert.Nil(t, r4)
}
func createTestUser(t *testing.T, username string, client *Client) *User {
user, _, _ := client.GetUserInfo(username)
if user.ID != 0 {