Bladeren bron

feat: 话题列表

runningwater 5 maanden geleden
bovenliggende
commit
0a6db82f1b

+ 2 - 1
app/cmd/make/tpls/seeder.tpl

@@ -3,11 +3,12 @@ package seeders
 import (
 	"fmt"
 
+	"gorm.io/gorm"
+
 	"github.com/runningwater/gohub/database/factories"
 	"github.com/runningwater/gohub/pkg/console"
 	"github.com/runningwater/gohub/pkg/logger"
 	"github.com/runningwater/gohub/pkg/seed"
-	"gorm.io/gorm"
 )
 
 func init() {

+ 13 - 4
app/http/controllers/api/v1/topics_controller.go

@@ -14,10 +14,19 @@ type TopicsController struct {
 	BaseApiController
 }
 
-// func (ctrl *TopicsController) Index(c *gin.Context) {
-//     topics := topic.All()
-//     response.Data(c, topics)
-// }
+func (ctrl *TopicsController) Index(c *gin.Context) {
+	request := requests.PaginationRequest{}
+	if ok := requests.Validate(c, &request, requests.Pagination); !ok {
+		return
+	}
+
+	data, pager := topic.Paginate(c, 10)
+
+	response.JSON(c, gin.H{
+		"data":  data,
+		"pager": pager,
+	})
+}
 
 func (ctrl *TopicsController) Store(c *gin.Context) {
 

+ 26 - 0
database/factories/topic_factory.go

@@ -0,0 +1,26 @@
+// Package factories 存放 topic 工厂方法
+package factories
+
+import (
+	"github.com/bxcodec/faker/v4"
+
+	"github.com/runningwater/gohub/app/models/topic"
+)
+
+func MakeTopics(times int) []topic.Topic {
+	var objs []topic.Topic
+
+	// 设置唯一值, 如 Topic 模型中的某个字段需要唯一
+	faker.SetGenerateUniqueValues(true)
+
+	for range times {
+		model := topic.Topic{
+			Title:      faker.Sentence(),
+			Body:       faker.Paragraph(),
+			UserID:     "1",
+			CategoryID: "3",
+		}
+		objs = append(objs, model)
+	}
+	return objs
+}

+ 1 - 0
database/seeders/init.go

@@ -10,5 +10,6 @@ func Initialize() {
 	seed.SetRunOrder([]string{
 		"UsersTableSeeder",
 		"CategoriesTableSeeder",
+		"TopicsTableSeeder",
 	})
 }

+ 31 - 0
database/seeders/topic_seeder.go

@@ -0,0 +1,31 @@
+package seeders
+
+import (
+	"fmt"
+
+	"gorm.io/gorm"
+
+	"github.com/runningwater/gohub/database/factories"
+	"github.com/runningwater/gohub/pkg/console"
+	"github.com/runningwater/gohub/pkg/logger"
+	"github.com/runningwater/gohub/pkg/seed"
+)
+
+func init() {
+	// 添加 Seeder
+	seed.Add("TopicsTableSeeder", func(db *gorm.DB) {
+		// 创建 10 个用户对象
+		topics := factories.MakeTopics(10)
+
+		// 批量插入到数据库
+		result := db.Table("topics").Create(&topics)
+
+		if err := result.Error; err != nil {
+			logger.LogIf(err)
+			return
+		}
+
+		// 打印成功信息
+		console.Success(fmt.Sprintf("Table [%v] %v rows seeded", result.Statement.Table, result.RowsAffected))
+	})
+}

+ 1 - 0
routes/api.go

@@ -69,6 +69,7 @@ func RegisterAPIRoutes(router *gin.Engine) {
 		tpc := new(controllers.TopicsController)
 		tpcGroup := v1.Group("/topics")
 		{
+			tpcGroup.GET("", tpc.Index)
 			tpcGroup.POST("", middlewares.AuthJWT(), tpc.Store)
 			tpcGroup.PUT("/:id", middlewares.AuthJWT(), tpc.Update)
 			tpcGroup.DELETE("/:id", middlewares.AuthJWT(), tpc.Delete)