feat(api): add search option for game

This commit is contained in:
rick 2022-11-14 18:40:20 +01:00
parent ad0c287729
commit ebeb1c63ad
Signed by: Rick
GPG key ID: 4A6223D66294EB20
3 changed files with 61 additions and 0 deletions

View file

@ -2,6 +2,7 @@ package controllers
import (
"cds/dao"
"cds/models"
"fmt"
"github.com/gofiber/fiber/v2"
@ -33,3 +34,31 @@ func GetGameById(c *fiber.Ctx) error {
}
}
}
// @Summary Renvoie une liste de 10 jeux dont le nom contient la requête.
// @Produce json
// @Success 200 {object} List models.Game
// @Failure 403
// @Failure 500
// @Router /games/search?name={name} [get]
func FindGame(c *fiber.Ctx) error {
token := c.Cookies("token", "")
if token == "" {
return c.SendStatus(fiber.StatusForbidden)
} else {
name := c.Query("name", "")
games, err := dao.SearchSimilarNames(name)
if err != nil {
return c.Status(fiber.StatusInternalServerError).JSON(fiber.Map{
"error": fmt.Sprint(err),
})
} else {
res := []models.Game{}
for e := games.Front(); e != nil; e = e.Next() {
res = append(res, e.Value.(models.Game))
}
return c.Status(fiber.StatusOK).JSON(res)
}
}
}

View file

@ -2,10 +2,12 @@ package dao
import (
"cds/models"
"container/list"
"context"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo/options"
)
func GetGameByAppId(id uint) (game *models.Game, err error) {
@ -36,3 +38,32 @@ func GetGameById(id string) (game *models.Game, err error) {
return &result, nil
}
}
func SearchSimilarNames(name string) (ret *list.List, err error) {
ret = list.New()
db, _ := get()
defer disconnect(db.Client())
coll := db.Collection("games")
regex := bson.D{{"$regex", ".*" + name + ".*"}}
opt := options.Find().SetLimit(10)
var result models.Game
cur, err := coll.Find(context.TODO(), bson.D{{"name", regex}}, opt)
if err != nil {
return nil, err
}
for cur.Next(context.TODO()) {
err = cur.Decode(&result)
if err != nil {
return nil, err
} else {
ret.PushBack(result)
}
}
return ret, nil
}

View file

@ -7,5 +7,6 @@ import (
)
func GameRoute(route fiber.Router) {
route.Get("/search", controllers.FindGame)
route.Get("/:id", controllers.GetGameById)
}