Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion base/constant/const.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
package constant

import "github.com/yiran15/api-server/base/apitypes"
import apitypes "github.com/yiran15/api-server/base/types"

type userContextKey struct{}

Expand Down
8 changes: 5 additions & 3 deletions base/constant/errors.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,9 @@ import (
)

var (
ErrAuthFailed = errors.New("auth failed")
ErrNoPermission = errors.New("access forbidden")
ErrLoginFailed = errors.New("incorrect username or password")
ErrAuthFailed = errors.New("auth failed")
ErrNoPermission = errors.New("access forbidden")
ErrLoginFailed = errors.New("incorrect username or password")
ErrUserNotFound = errors.New("user not found")
ErrPasswordWrong = errors.New("password incorrect")
)
39 changes: 8 additions & 31 deletions base/data/database.go
Original file line number Diff line number Diff line change
@@ -1,47 +1,23 @@
package data

import (
"context"
"fmt"

"github.com/spf13/viper"
"github.com/yiran15/api-server/base/conf"
"github.com/yiran15/api-server/stores"
"go.uber.org/zap"
"gorm.io/driver/mysql"
"gorm.io/gorm"
"gorm.io/gorm/logger"
)

// type zapWriter struct {
// log *zap.Logger
// }
var dbInstance *gorm.DB

// func (w zapWriter) Printf(_ string, args ...interface{}) {
// // gorm: l.Printf(l.traceErrStr, utils.FileWithLineNum(), err, float64(elapsed.Nanoseconds())/1e6, rows, sql)
// if len(args) == 5 {
// w.log.Error("gorm log", zap.String("err", args[1].(error).Error()), zap.Float64("elapsed", args[2].(float64)), zap.String("rows", "-"), zap.String("sql", args[4].(string)))
// return
// }
// switch args[2].(type) {
// case int64:
// w.log.Info("gorm log", zap.Float64("elapsed", args[1].(float64)), zap.Int64("rows", args[2].(int64)), zap.String("sql", args[3].(string)))
// case string:
// w.log.Info("gorm log", zap.Float64("elapsed", args[1].(float64)), zap.String("rows", args[2].(string)), zap.String("sql", args[3].(string)))
// default:
// w.log.Info("gorm log", zap.Float64("elapsed", args[1].(float64)), zap.String("rows", "-"), zap.String("sql", args[3].(string)))
// }
// }

// newGormLogger create a new gorm logger
// func newGormLogger(z *zap.Logger) logger.Interface {
// return logger.New(
// zapWriter{log: z}, // 使用 zap writer
// logger.Config{
// SlowThreshold: time.Second, // 慢查询阈值
// LogLevel: logger.Info, // 级别
// Colorful: true,
// },
// )
// }
func GetDB(ctx context.Context) *gorm.DB {
return dbInstance.WithContext(ctx)
}

func NewDB() (*gorm.DB, func(), error) {
dsn, err := conf.GetMysqlDsn()
Expand All @@ -56,7 +32,7 @@ func NewDB() (*gorm.DB, func(), error) {
zap.S().Info("enable debug mode on the database")
}

dbInstance, err := gorm.Open(mysql.Open(dsn), &gorm.Config{
dbInstance, err = gorm.Open(mysql.Open(dsn), &gorm.Config{
DisableForeignKeyConstraintWhenMigrating: true,
Logger: dbLogger,
})
Expand All @@ -81,5 +57,6 @@ func NewDB() (*gorm.DB, func(), error) {
sqlDB.SetConnMaxLifetime(conf.GetMysqlMaxLifetime())

zap.S().Info("db connect success")
stores.SetDefault(dbInstance)
return dbInstance, func() { _ = sqlDB.Close() }, nil
}
10 changes: 10 additions & 0 deletions base/helper/gorm.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
package helper

import "gorm.io/gen/field"

func Sort(orderCol field.OrderExpr, direction string) field.Expr {
if direction == "desc" {
return orderCol.Desc()
}
return orderCol.Asc()
}
2 changes: 1 addition & 1 deletion base/middleware/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ package middleware

import (
"github.com/gin-gonic/gin"
"github.com/yiran15/api-server/base/apitypes"
apitypes "github.com/yiran15/api-server/base/types"
"github.com/yiran15/api-server/pkg/casbin"
"github.com/yiran15/api-server/pkg/jwt"
"github.com/yiran15/api-server/store"
Expand Down
2 changes: 1 addition & 1 deletion base/server/server.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,10 +8,10 @@ import (
"time"

"github.com/gin-gonic/gin"
"github.com/yiran15/api-server/base/apitypes"
"github.com/yiran15/api-server/base/conf"
"github.com/yiran15/api-server/base/constant"
"github.com/yiran15/api-server/base/router"
apitypes "github.com/yiran15/api-server/base/types"
"github.com/yiran15/api-server/controller"
"go.uber.org/zap"
)
Expand Down
24 changes: 23 additions & 1 deletion base/apitypes/api.go → base/types/api.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package apitypes
package types

import "github.com/yiran15/api-server/model"

Expand Down Expand Up @@ -38,3 +38,25 @@ type ApiInfo struct {
Path string `json:"path"`
Handler string `json:"handler"`
}

func NewApi(req *ApiCreateRequest) *model.Api {
return &model.Api{
Name: req.Name,
Path: req.Path,
Method: req.Method,
Description: req.Description,
}
}

func NewApiListResponse(apis []*model.Api, total int64, pageSize, page int) *ApiListResponse {
return &ApiListResponse{
ListResponse: &ListResponse{
Total: total,
Pagination: &Pagination{
Page: page,
PageSize: pageSize,
},
},
List: apis,
}
}
2 changes: 1 addition & 1 deletion base/apitypes/res.go → base/types/res.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package apitypes
package types

type Response struct {
Code int `json:"code"`
Expand Down
19 changes: 17 additions & 2 deletions base/apitypes/role.go → base/types/role.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package apitypes
package types

import "github.com/yiran15/api-server/model"
import (
"github.com/yiran15/api-server/model"
)

type RoleCreateRequest struct {
Name string `json:"name" binding:"required,ascii"`
Expand All @@ -25,3 +27,16 @@ type RoleListResponse struct {
*ListResponse
List []*model.Role `json:"list"`
}

func NewRoleListResponse(roles []*model.Role, total int64, pageIndex, pageSize int) *RoleListResponse {
return &RoleListResponse{
ListResponse: &ListResponse{
Pagination: &Pagination{
Page: pageIndex,
PageSize: pageSize,
},
Total: total,
},
List: roles,
}
}
2 changes: 1 addition & 1 deletion base/apitypes/types.go → base/types/types.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package apitypes
package types

type IDRequest struct {
ID int64 `uri:"id" binding:"required"`
Expand Down
11 changes: 9 additions & 2 deletions base/apitypes/user.go → base/types/user.go
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
package apitypes
package types

import (
"github.com/yiran15/api-server/model"
Expand Down Expand Up @@ -81,7 +81,14 @@ type OauthLoginResponse struct {
}

type OAuthActivateRequest struct {
ID string `uri:"id" binding:"required"`
ID int `uri:"id" binding:"required"`
Password string `json:"password" binding:"required,min=8"`
ConfirmPassword string `json:"confirmPassword" binding:"required,min=8"`
}

func NewUserLoginResponse(user *model.User, token string) *UserLoginResponse {
return &UserLoginResponse{
User: user,
Token: token,
}
}
4 changes: 4 additions & 0 deletions cmd/apiserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import (
"github.com/yiran15/api-server/base/conf"
"github.com/yiran15/api-server/base/constant"
baselog "github.com/yiran15/api-server/base/log"
v1 "github.com/yiran15/api-server/service/v1"
"go.uber.org/zap"
)

Expand Down Expand Up @@ -73,6 +74,9 @@ func runApp(_ *cobra.Command, _ []string) error {
return fmt.Errorf("init application faild: %w", err)
}
defer cleanup()

v1.NewStore()

if err := app.Run(ctx); err != nil {
return fmt.Errorf("run application faild: %w", err)
}
Expand Down
9 changes: 3 additions & 6 deletions cmd/init.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,10 +6,10 @@ import (

"github.com/spf13/cobra"
"github.com/spf13/viper"
"github.com/yiran15/api-server/base/apitypes"
"github.com/yiran15/api-server/base/conf"
"github.com/yiran15/api-server/base/constant"
"github.com/yiran15/api-server/base/data"
apitypes "github.com/yiran15/api-server/base/types"
"github.com/yiran15/api-server/model"
"github.com/yiran15/api-server/pkg/casbin"
"github.com/yiran15/api-server/pkg/jwt"
Expand Down Expand Up @@ -60,10 +60,7 @@ func getService() (*service, func(), error) {
}

provider := store.NewDBProvider(db)
userRepo := store.NewUserStore(provider)
roleRepo := store.NewRoleStore(provider)
apiRepo := store.NewApiStore(provider)
casbinStore := store.NewCasbinStore(provider)
txManager := store.NewTxManager(db)

redisClient, err := data.NewRDB()
Expand All @@ -86,8 +83,8 @@ func getService() (*service, func(), error) {
}
casbinManager := casbin.NewCasbinManager(casbinEnforcer)

userServicer := v1.NewUserService(userRepo, roleRepo, cacheStore, txManager, generateToken, nil, nil, nil)
roleServicer := v1.NewRoleService(roleRepo, apiRepo, casbinStore, casbinManager, txManager)
userServicer := v1.NewUserService(cacheStore, txManager, generateToken, nil, nil)
roleServicer := v1.NewRoleService(casbinManager)
apiServicer := v1.NewApiServicer(apiRepo)
return &service{
db: db,
Expand Down
20 changes: 8 additions & 12 deletions cmd/wire_gen.go

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

28 changes: 14 additions & 14 deletions controller/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ import (
"net/http"

"github.com/gin-gonic/gin"
"github.com/yiran15/api-server/base/apitypes"
"github.com/yiran15/api-server/base/constant"
"github.com/yiran15/api-server/base/types"
v1 "github.com/yiran15/api-server/service/v1"
)

Expand Down Expand Up @@ -34,8 +34,8 @@ func NewApiController(apiService v1.ApiServicer) ApiController {
// @Tags API管理
// @Accept json
// @Produce json
// @Param data body apitypes.ApiCreateRequest true "创建请求参数"
// @Success 200 {object} apitypes.Response "创建成功"
// @Param data body types.ApiCreateRequest true "创建请求参数"
// @Success 200 {object} types.Response "创建成功"
// @Router /api/v1/api [post]
func (receiver *apiController) CreateApi(c *gin.Context) {
ResponseOnlySuccess(c, receiver.apiService.CreateApi, bindTypeJson)
Expand All @@ -47,8 +47,8 @@ func (receiver *apiController) CreateApi(c *gin.Context) {
// @Tags API管理
// @Accept json
// @Produce json
// @Param data body apitypes.ApiUpdateRequest true "更新请求参数"
// @Success 200 {object} apitypes.Response "更新成功"
// @Param data body types.ApiUpdateRequest true "更新请求参数"
// @Success 200 {object} types.Response "更新成功"
// @Router /api/v1/api/:id [put]
func (receiver *apiController) UpdateApi(c *gin.Context) {
ResponseOnlySuccess(c, receiver.apiService.UpdateApi, bindTypeUri, bindTypeJson)
Expand All @@ -60,8 +60,8 @@ func (receiver *apiController) UpdateApi(c *gin.Context) {
// @Tags API管理
// @Accept json
// @Produce json
// @Param data body apitypes.IDRequest true "删除请求参数"
// @Success 200 {object} apitypes.Response "删除成功"
// @Param data body types.IDRequest true "删除请求参数"
// @Success 200 {object} types.Response "删除成功"
// @Router /api/v1/api/:id [delete]
func (receiver *apiController) DeleteApi(c *gin.Context) {
ResponseOnlySuccess(c, receiver.apiService.DeleteApi, bindTypeUri)
Expand All @@ -73,8 +73,8 @@ func (receiver *apiController) DeleteApi(c *gin.Context) {
// @Tags API管理
// @Accept json
// @Produce json
// @Param data body apitypes.IDRequest true "查询请求参数"
// @Success 200 {object} apitypes.Response{data=model.Api} "查询成功"
// @Param data body types.IDRequest true "查询请求参数"
// @Success 200 {object} types.Response{data=model.Api} "查询成功"
// @Router /api/v1/api/:id [get]
func (receiver *apiController) QueryApi(c *gin.Context) {
ResponseWithData(c, receiver.apiService.QueryApi, bindTypeUri)
Expand All @@ -86,8 +86,8 @@ func (receiver *apiController) QueryApi(c *gin.Context) {
// @Tags API管理
// @Accept json
// @Produce json
// @Param data query apitypes.ApiListRequest true "查询请求参数"
// @Success 200 {object} apitypes.Response{data=apitypes.ApiListResponse} "查询成功"
// @Param data query types.ApiListRequest true "查询请求参数"
// @Success 200 {object} types.Response{data=types.ApiListResponse} "查询成功"
// @Router /api/v1/api/ [get]
func (receiver *apiController) ListApi(c *gin.Context) {
ResponseWithData(c, receiver.apiService.ListApi, bindTypeUri, bindTypeQuery)
Expand All @@ -98,9 +98,9 @@ func (receiver *apiController) ListApi(c *gin.Context) {
// @Tags API管理
// @Accept json
// @Produce json
// @Success 200 {object} apitypes.Response{data=apitypes.ServerApiData} "查询成功"
// @Success 200 {object} types.Response{data=types.ServerApiData} "查询成功"
// @Router /api/v1/api/serverApi [get]
func (receiver *apiController) GetServerApi(c *gin.Context) {
c.JSON(http.StatusOK, apitypes.NewResponseWithOpts(http.StatusOK, apitypes.WithMsg("success"), apitypes.WithData(constant.ApiData)))
// c.JSON(http.StatusOK, apitypes.NewResponse(http.StatusOK, "success", constant.ApiData, ""))
c.JSON(http.StatusOK, types.NewResponseWithOpts(http.StatusOK, types.WithMsg("success"), types.WithData(constant.ApiData)))
// c.JSON(http.StatusOK, types.NewResponse(http.StatusOK, "success", constant.ApiData, ""))
}
Loading
Loading