- 使用 Squirrel 与 sqlx 实现分类查询 - 集中组装依赖并向 handler 注入 model 接口 - 显式转换分类响应 DTO,统一空列表输出 - 补充路由与 handler 测试,同步架构文档 BREAKING CHANGE: 将 GET /hello 替换为 GET /test,响应由问候字符串改为分类列表
47 lines
1019 B
Go
47 lines
1019 B
Go
package model
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
|
|
sq "github.com/Masterminds/squirrel"
|
|
"github.com/jmoiron/sqlx"
|
|
)
|
|
|
|
type Category struct {
|
|
ID int64 `db:"id"`
|
|
Slug string `db:"slug"`
|
|
Title string `db:"title"`
|
|
Sort int `db:"sort"`
|
|
}
|
|
|
|
type CategoryModel interface {
|
|
FindAll(ctx context.Context) ([]*Category, error)
|
|
}
|
|
type defaultCategoryModel struct {
|
|
db *sqlx.DB
|
|
}
|
|
|
|
func NewCategoryModel(db *sqlx.DB) CategoryModel {
|
|
return &defaultCategoryModel{db: db}
|
|
}
|
|
func (m *defaultCategoryModel) FindAll(ctx context.Context) ([]*Category, error) {
|
|
query, args, err := sq.
|
|
Select("id", "slug", "title", "sort").
|
|
From("public.categories").
|
|
Where(sq.GtOrEq{"sort": 1}).
|
|
OrderBy("sort ASC", "id ASC").
|
|
Limit(10).
|
|
PlaceholderFormat(sq.Dollar).
|
|
ToSql()
|
|
if err != nil {
|
|
return nil, fmt.Errorf("squirrel 出错: %w", err)
|
|
}
|
|
rows := make([]*Category, 0)
|
|
err = m.db.SelectContext(ctx, &rows, query, args...)
|
|
if err != nil {
|
|
return nil, fmt.Errorf("数据库查询出错: %w", err)
|
|
}
|
|
return rows, err
|
|
}
|