From 1a7fc53c98f06f79955d217f91c8a5553e5a27b3 Mon Sep 17 00:00:00 2001 From: Ethan Koenig Date: Fri, 6 Jan 2017 02:05:09 -0500 Subject: [PATCH] API endpoint for stargazers (#597) --- models/star.go | 12 ++++++------ routers/api/v1/api.go | 1 + routers/api/v1/repo/star.go | 25 +++++++++++++++++++++++++ 3 files changed, 32 insertions(+), 6 deletions(-) create mode 100644 routers/api/v1/repo/star.go diff --git a/models/star.go b/models/star.go index e2feb2c4b6..923bab57b5 100644 --- a/models/star.go +++ b/models/star.go @@ -63,12 +63,12 @@ func IsStaring(userID, repoID int64) bool { // GetStargazers returns the users that starred the repo. func (repo *Repository) GetStargazers(page int) ([]*User, error) { users := make([]*User, 0, ItemsPerPage) - err := x. - Limit(ItemsPerPage, (page-1)*ItemsPerPage). - Where("star.repo_id = ?", repo.ID). - Join("LEFT", "star", "`user`.id = star.uid"). - Find(&users) - return users, err + sess := x.Where("star.repo_id = ?", repo.ID). + Join("LEFT", "star", "`user`.id = star.uid") + if page > 0 { + sess = sess.Limit(ItemsPerPage, (page-1)*ItemsPerPage) + } + return users, sess.Find(&users) } // GetStarredRepos returns the repos the user starred. diff --git a/routers/api/v1/api.go b/routers/api/v1/api.go index c35f9afa6f..cc773150e6 100644 --- a/routers/api/v1/api.go +++ b/routers/api/v1/api.go @@ -326,6 +326,7 @@ func RegisterRoutes(m *macaron.Macaron) { Patch(reqRepoWriter(), bind(api.EditMilestoneOption{}), repo.EditMilestone). Delete(reqRepoWriter(), repo.DeleteMilestone) }) + m.Get("/stargazers", repo.ListStargazers) m.Group("/subscription", func() { m.Get("", user.IsWatching) m.Put("", user.Watch) diff --git a/routers/api/v1/repo/star.go b/routers/api/v1/repo/star.go new file mode 100644 index 0000000000..20e7e4e508 --- /dev/null +++ b/routers/api/v1/repo/star.go @@ -0,0 +1,25 @@ +// Copyright 2017 The Gitea Authors. All rights reserved. +// Use of this source code is governed by a MIT-style +// license that can be found in the LICENSE file. + +package repo + +import ( + api "code.gitea.io/sdk/gitea" + + "code.gitea.io/gitea/modules/context" +) + +// ListStargazers list a repository's stargazers +func ListStargazers(ctx *context.APIContext) { + stargazers, err := ctx.Repo.Repository.GetStargazers(-1) + if err != nil { + ctx.Error(500, "GetStargazers", err) + return + } + users := make([]*api.User, len(stargazers)) + for i, stargazer := range stargazers { + users[i] = stargazer.APIFormat() + } + ctx.JSON(200, users) +}