Skip to content

Commit 4c1765e

Browse files
authored
Merge pull request #179 from Quaver/clan-search
Add clan search by name or tag
2 parents ed3a6f3 + bb6ee65 commit 4c1765e

3 files changed

Lines changed: 39 additions & 0 deletions

File tree

cmd/api/server.go

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -100,6 +100,7 @@ func initializeRoutes(engine *gin.Engine) {
100100

101101
// Clans
102102
engine.POST("/v2/clan", middleware.RequireAuth, handlers.CreateHandler(handlers.CreateClan))
103+
engine.GET("/v2/clan/search/:name", handlers.CreateHandler(handlers.SearchClans))
103104
engine.GET("/v2/clan/:id", handlers.CreateHandler(handlers.GetClan))
104105
engine.POST("/v2/clan/:id", middleware.RequireAuth, handlers.CreateHandler(handlers.UpdateClan))
105106
engine.DELETE("/v2/clan/:id", middleware.RequireAuth, handlers.CreateHandler(handlers.DeleteClan))

db/clans.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -126,6 +126,25 @@ func GetClanByName(name string) (*Clan, error) {
126126
return clan, nil
127127
}
128128

129+
// SearchClansByName Searches for clans whose name or tag starts with the query
130+
func SearchClansByName(searchQuery string) ([]*Clan, error) {
131+
clans := make([]*Clan, 0)
132+
likeQuery := fmt.Sprintf("%v%%", searchQuery)
133+
134+
result := SQL.
135+
Preload("Stats").
136+
Where("clans.name LIKE ? OR clans.tag LIKE ?", likeQuery, likeQuery).
137+
Limit(50).
138+
Order("id ASC").
139+
Find(&clans)
140+
141+
if result.Error != nil {
142+
return nil, result.Error
143+
}
144+
145+
return clans, nil
146+
}
147+
129148
// GetClanByTag Gets a clan from the db by its tag (case-sensitive)
130149
func GetClanByTag(tag string) (*Clan, error) {
131150
var clan *Clan

handlers/clans.go

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,25 @@ func GetClan(c *gin.Context) *APIError {
140140
return nil
141141
}
142142

143+
// SearchClans Searches for clans by name and returns them
144+
// Endpoint: /v2/clan/search/:name
145+
func SearchClans(c *gin.Context) *APIError {
146+
name := c.Param("name")
147+
148+
if name == "" {
149+
return APIErrorBadRequest("You must supply a valid name to search.")
150+
}
151+
152+
clans, err := db.SearchClansByName(name)
153+
154+
if err != nil {
155+
return APIErrorServerError("Error searching for clans", err)
156+
}
157+
158+
c.JSON(http.StatusOK, gin.H{"clans": clans})
159+
return nil
160+
}
161+
143162
// UpdateClan Updates data about a clan
144163
// Endpoint: PATCH /v2/clan/:id
145164
func UpdateClan(c *gin.Context) *APIError {

0 commit comments

Comments
 (0)