feat: 新增简易版ioc

This commit is contained in:
meilin.huang
2024-01-21 22:52:20 +08:00
parent f4a64b96a9
commit f27d3d200f
106 changed files with 815 additions and 707 deletions

View File

@@ -49,13 +49,14 @@
"@typescript-eslint/parser": "^6.7.4", "@typescript-eslint/parser": "^6.7.4",
"@vitejs/plugin-vue": "^5.0.3", "@vitejs/plugin-vue": "^5.0.3",
"@vue/compiler-sfc": "^3.4.14", "@vue/compiler-sfc": "^3.4.14",
"code-inspector-plugin": "^0.4.5",
"dotenv": "^16.3.1", "dotenv": "^16.3.1",
"eslint": "^8.35.0", "eslint": "^8.35.0",
"eslint-plugin-vue": "^9.19.2", "eslint-plugin-vue": "^9.19.2",
"prettier": "^3.1.0", "prettier": "^3.1.0",
"sass": "^1.69.0", "sass": "^1.69.0",
"typescript": "^5.3.2", "typescript": "^5.3.2",
"vite": "^5.0.11", "vite": "^5.0.12",
"vue-eslint-parser": "^9.4.0" "vue-eslint-parser": "^9.4.0"
}, },
"browserslist": [ "browserslist": [

View File

@@ -15,7 +15,7 @@ const config = {
baseWsUrl: `${(window as any).globalConfig.BaseWsUrl || `${location.protocol == 'https:' ? 'wss:' : 'ws:'}//${getBaseApiUrl()}`}/api`, baseWsUrl: `${(window as any).globalConfig.BaseWsUrl || `${location.protocol == 'https:' ? 'wss:' : 'ws:'}//${getBaseApiUrl()}`}/api`,
// 系统版本 // 系统版本
version: 'v1.7.0', version: 'v1.7.1',
}; };
export default config; export default config;

View File

@@ -2,6 +2,7 @@ import vue from '@vitejs/plugin-vue';
import { resolve } from 'path'; import { resolve } from 'path';
import type { UserConfig } from 'vite'; import type { UserConfig } from 'vite';
import { loadEnv } from './src/common/utils/viteBuild'; import { loadEnv } from './src/common/utils/viteBuild';
import { CodeInspectorPlugin } from 'code-inspector-plugin';
const pathResolve = (dir: string): any => { const pathResolve = (dir: string): any => {
return resolve(__dirname, '.', dir); return resolve(__dirname, '.', dir);
@@ -14,7 +15,12 @@ const alias: Record<string, string> = {
}; };
const viteConfig: UserConfig = { const viteConfig: UserConfig = {
plugins: [vue()], plugins: [
vue(),
CodeInspectorPlugin({
bundler: 'vite',
}),
],
root: process.cwd(), root: process.cwd(),
resolve: { resolve: {
alias, alias,

View File

@@ -3,9 +3,14 @@ package initialize
import ( import (
dbInit "mayfly-go/internal/db/init" dbInit "mayfly-go/internal/db/init"
machineInit "mayfly-go/internal/machine/init" machineInit "mayfly-go/internal/machine/init"
"mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
) )
func InitOther() { func InitOther() {
// 为所有注册的实例注入其依赖的其他组件实例
biz.ErrIsNil(ioc.DefaultContainer.InjectComponents())
machineInit.Init() machineInit.Init()
dbInit.Init() dbInit.Init()
} }

View File

@@ -25,8 +25,8 @@ import (
) )
type AccountLogin struct { type AccountLogin struct {
AccountApp sysapp.Account AccountApp sysapp.Account `inject:""`
MsgApp msgapp.Msg MsgApp msgapp.Msg `inject:""`
} }
/** 用户账号密码登录 **/ /** 用户账号密码登录 **/

View File

@@ -28,8 +28,8 @@ import (
) )
type LdapLogin struct { type LdapLogin struct {
AccountApp sysapp.Account AccountApp sysapp.Account `inject:""`
MsgApp msgapp.Msg MsgApp msgapp.Msg `inject:""`
} }
// @router /auth/ldap/enabled [get] // @router /auth/ldap/enabled [get]

View File

@@ -28,9 +28,9 @@ import (
) )
type Oauth2Login struct { type Oauth2Login struct {
Oauth2App application.Oauth2 Oauth2App application.Oauth2 `inject:""`
AccountApp sysapp.Account AccountApp sysapp.Account `inject:""`
MsgApp msgapp.Msg MsgApp msgapp.Msg `inject:""`
} }
func (a *Oauth2Login) OAuth2Login(rc *req.Ctx) { func (a *Oauth2Login) OAuth2Login(rc *req.Ctx) {

View File

@@ -1,11 +1,16 @@
package application package application
import "mayfly-go/internal/auth/infrastructure/persistence" import (
"mayfly-go/internal/auth/infrastructure/persistence"
var ( "mayfly-go/pkg/ioc"
authApp = newAuthApp(persistence.GetOauthAccountRepo())
) )
func GetAuthApp() Oauth2 { func init() {
return authApp persistence.Init()
ioc.Register(new(oauth2AppImpl), ioc.WithComponentName("Oauth2App"))
}
func GetAuthApp() Oauth2 {
return ioc.Get[Oauth2]("Oauth2App")
} }

View File

@@ -14,27 +14,21 @@ type Oauth2 interface {
Unbind(accountId uint64) Unbind(accountId uint64)
} }
func newAuthApp(oauthAccountRepo repository.Oauth2Account) Oauth2 {
return &oauth2AppImpl{
oauthAccountRepo: oauthAccountRepo,
}
}
type oauth2AppImpl struct { type oauth2AppImpl struct {
oauthAccountRepo repository.Oauth2Account Oauth2AccountRepo repository.Oauth2Account `inject:""`
} }
func (a *oauth2AppImpl) GetOAuthAccount(condition *entity.Oauth2Account, cols ...string) error { func (a *oauth2AppImpl) GetOAuthAccount(condition *entity.Oauth2Account, cols ...string) error {
return a.oauthAccountRepo.GetBy(condition, cols...) return a.Oauth2AccountRepo.GetBy(condition, cols...)
} }
func (a *oauth2AppImpl) BindOAuthAccount(e *entity.Oauth2Account) error { func (a *oauth2AppImpl) BindOAuthAccount(e *entity.Oauth2Account) error {
if e.Id == 0 { if e.Id == 0 {
return a.oauthAccountRepo.Insert(context.Background(), e) return a.Oauth2AccountRepo.Insert(context.Background(), e)
} }
return a.oauthAccountRepo.UpdateById(context.Background(), e) return a.Oauth2AccountRepo.UpdateById(context.Background(), e)
} }
func (a *oauth2AppImpl) Unbind(accountId uint64) { func (a *oauth2AppImpl) Unbind(accountId uint64) {
a.oauthAccountRepo.DeleteByCond(context.Background(), &entity.Oauth2Account{AccountId: accountId}) a.Oauth2AccountRepo.DeleteByCond(context.Background(), &entity.Oauth2Account{AccountId: accountId})
} }

View File

@@ -1,11 +1,14 @@
package persistence package persistence
import "mayfly-go/internal/auth/domain/repository" import (
"mayfly-go/internal/auth/domain/repository"
var ( "mayfly-go/pkg/ioc"
authAccountRepo = newAuthAccountRepo()
) )
func GetOauthAccountRepo() repository.Oauth2Account { func Init() {
return authAccountRepo ioc.Register(newAuthAccountRepo(), ioc.WithComponentName("Oauth2AccountRepo"))
}
func GetOauthAccountRepo() repository.Oauth2Account {
return ioc.Get[repository.Oauth2Account]("Oauth2AccountRepo")
} }

View File

@@ -2,30 +2,22 @@ package router
import ( import (
"mayfly-go/internal/auth/api" "mayfly-go/internal/auth/api"
"mayfly-go/internal/auth/application" "mayfly-go/pkg/biz"
msgapp "mayfly-go/internal/msg/application" "mayfly-go/pkg/ioc"
sysapp "mayfly-go/internal/sys/application"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func Init(router *gin.RouterGroup) { func Init(router *gin.RouterGroup) {
accountLogin := &api.AccountLogin{ accountLogin := new(api.AccountLogin)
AccountApp: sysapp.GetAccountApp(), biz.ErrIsNil(ioc.Inject(accountLogin))
MsgApp: msgapp.GetMsgApp(),
}
ldapLogin := &api.LdapLogin{ ldapLogin := new(api.LdapLogin)
AccountApp: sysapp.GetAccountApp(), biz.ErrIsNil(ioc.Inject(ldapLogin))
MsgApp: msgapp.GetMsgApp(),
}
oauth2Login := &api.Oauth2Login{ oauth2Login := new(api.Oauth2Login)
Oauth2App: application.GetAuthApp(), biz.ErrIsNil(ioc.Inject(oauth2Login))
AccountApp: sysapp.GetAccountApp(),
MsgApp: msgapp.GetMsgApp(),
}
rg := router.Group("/auth") rg := router.Group("/auth")

View File

@@ -12,11 +12,11 @@ import (
) )
type Index struct { type Index struct {
TagApp tagapp.TagTree TagApp tagapp.TagTree `inject:"TagTreeApp"`
MachineApp machineapp.Machine MachineApp machineapp.Machine `inject:""`
DbApp dbapp.Db DbApp dbapp.Db `inject:""`
RedisApp redisapp.Redis RedisApp redisapp.Redis `inject:""`
MongoApp mongoapp.Mongo MongoApp mongoapp.Mongo `inject:""`
} }
func (i *Index) Count(rc *req.Ctx) { func (i *Index) Count(rc *req.Ctx) {

View File

@@ -2,11 +2,8 @@ package router
import ( import (
"mayfly-go/internal/common/api" "mayfly-go/internal/common/api"
dbapp "mayfly-go/internal/db/application" "mayfly-go/pkg/biz"
machineapp "mayfly-go/internal/machine/application" "mayfly-go/pkg/ioc"
mongoapp "mayfly-go/internal/mongo/application"
redisapp "mayfly-go/internal/redis/application"
tagapp "mayfly-go/internal/tag/application"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -14,13 +11,8 @@ import (
func InitIndexRouter(router *gin.RouterGroup) { func InitIndexRouter(router *gin.RouterGroup) {
index := router.Group("common/index") index := router.Group("common/index")
i := &api.Index{ i := new(api.Index)
TagApp: tagapp.GetTagTreeApp(), biz.ErrIsNil(ioc.Inject(i))
MachineApp: machineapp.GetMachineApp(),
DbApp: dbapp.GetDbApp(),
RedisApp: redisapp.GetRedisApp(),
MongoApp: mongoapp.GetMongoApp(),
}
{ {
// 首页基本信息统计 // 首页基本信息统计
req.NewGet("count", i.Count).Group(index) req.NewGet("count", i.Count).Group(index)

View File

@@ -32,11 +32,11 @@ import (
) )
type Db struct { type Db struct {
InstanceApp application.Instance InstanceApp application.Instance `inject:"DbInstanceApp"`
DbApp application.Db DbApp application.Db `inject:""`
DbSqlExecApp application.DbSqlExec DbSqlExecApp application.DbSqlExec `inject:""`
MsgApp msgapp.Msg MsgApp msgapp.Msg `inject:""`
TagApp tagapp.TagTree TagApp tagapp.TagTree `inject:"TagTreeApp"`
} }
// @router /api/dbs [get] // @router /api/dbs [get]

View File

@@ -19,7 +19,7 @@ import (
) )
type DataSyncTask struct { type DataSyncTask struct {
DataSyncTaskApp application.DataSyncTask DataSyncTaskApp application.DataSyncTask `inject:"DbDataSyncTaskApp"`
} }
func (d *DataSyncTask) Tasks(rc *req.Ctx) { func (d *DataSyncTask) Tasks(rc *req.Ctx) {

View File

@@ -10,7 +10,7 @@ import (
) )
type DbSql struct { type DbSql struct {
DbSqlApp application.DbSql DbSqlApp application.DbSql `inject:""`
} }
// @router /api/db/:dbId/sql [post] // @router /api/db/:dbId/sql [post]

View File

@@ -9,7 +9,7 @@ import (
) )
type DbSqlExec struct { type DbSqlExec struct {
DbSqlExecApp application.DbSqlExec DbSqlExecApp application.DbSqlExec `inject:""`
} }
func (d *DbSqlExec) DbSqlExecs(rc *req.Ctx) { func (d *DbSqlExec) DbSqlExecs(rc *req.Ctx) {

View File

@@ -16,8 +16,8 @@ import (
) )
type Instance struct { type Instance struct {
InstanceApp application.Instance InstanceApp application.Instance `inject:"DbInstanceApp"`
DbApp application.Db DbApp application.Db `inject:""`
} }
// Instances 获取数据库实例信息 // Instances 获取数据库实例信息

View File

@@ -4,21 +4,26 @@ import (
"fmt" "fmt"
"mayfly-go/internal/db/domain/repository" "mayfly-go/internal/db/domain/repository"
"mayfly-go/internal/db/infrastructure/persistence" "mayfly-go/internal/db/infrastructure/persistence"
tagapp "mayfly-go/internal/tag/application" "mayfly-go/pkg/ioc"
"sync" "sync"
) )
var ( var (
instanceApp Instance
dbApp Db
dbSqlExecApp DbSqlExec
dbSqlApp DbSql
dbBackupApp *DbBackupApp dbBackupApp *DbBackupApp
dbRestoreApp *DbRestoreApp dbRestoreApp *DbRestoreApp
dbBinlogApp *DbBinlogApp dbBinlogApp *DbBinlogApp
dataSyncApp DataSyncTask
) )
func init() {
persistence.Init()
ioc.Register(new(instanceAppImpl), ioc.WithComponentName("DbInstanceApp"))
ioc.Register(new(dbAppImpl), ioc.WithComponentName("DbApp"))
ioc.Register(new(dbSqlExecAppImpl), ioc.WithComponentName("DbSqlExecApp"))
ioc.Register(new(dbSqlAppImpl), ioc.WithComponentName("DbSqlApp"))
ioc.Register(new(dataSyncAppImpl), ioc.WithComponentName("DbDataSyncTaskApp"))
}
func Init() { func Init() {
sync.OnceFunc(func() { sync.OnceFunc(func() {
repositories := &repository.Repositories{ repositories := &repository.Repositories{
@@ -31,13 +36,7 @@ func Init() {
BinlogHistory: persistence.NewDbBinlogHistoryRepo(), BinlogHistory: persistence.NewDbBinlogHistoryRepo(),
} }
var err error var err error
instanceRepo := persistence.GetInstanceRepo() dbApp := GetDbApp()
instanceApp = newInstanceApp(instanceRepo)
dbApp = newDbApp(persistence.GetDbRepo(), persistence.GetDbSqlRepo(), instanceApp, tagapp.GetTagTreeApp())
dbSqlExecApp = newDbSqlExecApp(persistence.GetDbSqlExecRepo())
dbSqlApp = newDbSqlApp(persistence.GetDbSqlRepo())
dataSyncApp = newDataSyncApp(persistence.GetDataSyncTaskRepo(), persistence.GetDataSyncLogRepo())
scheduler, err := newDbScheduler(repositories) scheduler, err := newDbScheduler(repositories)
if err != nil { if err != nil {
panic(fmt.Sprintf("初始化 dbScheduler 失败: %v", err)) panic(fmt.Sprintf("初始化 dbScheduler 失败: %v", err))
@@ -55,24 +54,24 @@ func Init() {
panic(fmt.Sprintf("初始化 dbBinlogApp 失败: %v", err)) panic(fmt.Sprintf("初始化 dbBinlogApp 失败: %v", err))
} }
dataSyncApp.InitCronJob() GetDataSyncTaskApp().InitCronJob()
})() })()
} }
func GetInstanceApp() Instance { func GetInstanceApp() Instance {
return instanceApp return ioc.Get[Instance]("DbInstance")
} }
func GetDbApp() Db { func GetDbApp() Db {
return dbApp return ioc.Get[Db]("DbApp")
} }
func GetDbSqlApp() DbSql { func GetDbSqlApp() DbSql {
return dbSqlApp return ioc.Get[DbSql]("DbSqlApp")
} }
func GetDbSqlExecApp() DbSqlExec { func GetDbSqlExecApp() DbSqlExec {
return dbSqlExecApp return ioc.Get[DbSqlExec]("DbSqlExecApp")
} }
func GetDbBackupApp() *DbBackupApp { func GetDbBackupApp() *DbBackupApp {
@@ -88,5 +87,5 @@ func GetDbBinlogApp() *DbBinlogApp {
} }
func GetDataSyncTaskApp() DataSyncTask { func GetDataSyncTaskApp() DataSyncTask {
return dataSyncApp return ioc.Get[DataSyncTask]("DbDataSyncTaskApp")
} }

View File

@@ -40,22 +40,17 @@ type Db interface {
GetDbConnByInstanceId(instanceId uint64) (*dbi.DbConn, error) GetDbConnByInstanceId(instanceId uint64) (*dbi.DbConn, error)
} }
func newDbApp(dbRepo repository.Db, dbSqlRepo repository.DbSql, dbInstanceApp Instance, tagApp tagapp.TagTree) Db {
app := &dbAppImpl{
dbSqlRepo: dbSqlRepo,
dbInstanceApp: dbInstanceApp,
tagApp: tagApp,
}
app.Repo = dbRepo
return app
}
type dbAppImpl struct { type dbAppImpl struct {
base.AppImpl[*entity.Db, repository.Db] base.AppImpl[*entity.Db, repository.Db]
dbSqlRepo repository.DbSql DbSqlRepo repository.DbSql `inject:""`
dbInstanceApp Instance DbInstanceApp Instance `inject:""`
tagApp tagapp.TagTree TagApp tagapp.TagTree `inject:"TagTreeApp"`
}
// 注入DbRepo
func (d *dbAppImpl) InjectDbRepo(repo repository.Db) {
d.Repo = repo
} }
// 分页获取数据库信息列表 // 分页获取数据库信息列表
@@ -83,7 +78,7 @@ func (d *dbAppImpl) SaveDb(ctx context.Context, dbEntity *entity.Db, tagIds ...u
return d.Tx(ctx, func(ctx context.Context) error { return d.Tx(ctx, func(ctx context.Context) error {
return d.Insert(ctx, dbEntity) return d.Insert(ctx, dbEntity)
}, func(ctx context.Context) error { }, func(ctx context.Context) error {
return d.tagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeDb, tagIds) return d.TagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeDb, tagIds)
}) })
} }
@@ -107,13 +102,13 @@ func (d *dbAppImpl) SaveDb(ctx context.Context, dbEntity *entity.Db, tagIds ...u
// 关闭数据库连接 // 关闭数据库连接
dbm.CloseDb(dbEntity.Id, v) dbm.CloseDb(dbEntity.Id, v)
// 删除该库关联的所有sql记录 // 删除该库关联的所有sql记录
d.dbSqlRepo.DeleteByCond(ctx, &entity.DbSql{DbId: dbId, Db: v}) d.DbSqlRepo.DeleteByCond(ctx, &entity.DbSql{DbId: dbId, Db: v})
} }
return d.Tx(ctx, func(ctx context.Context) error { return d.Tx(ctx, func(ctx context.Context) error {
return d.UpdateById(ctx, dbEntity) return d.UpdateById(ctx, dbEntity)
}, func(ctx context.Context) error { }, func(ctx context.Context) error {
return d.tagApp.RelateResource(ctx, old.Code, consts.TagResourceTypeDb, tagIds) return d.TagApp.RelateResource(ctx, old.Code, consts.TagResourceTypeDb, tagIds)
}) })
} }
@@ -134,10 +129,10 @@ func (d *dbAppImpl) Delete(ctx context.Context, id uint64) error {
}, },
func(ctx context.Context) error { func(ctx context.Context) error {
// 删除该库下用户保存的所有sql信息 // 删除该库下用户保存的所有sql信息
return d.dbSqlRepo.DeleteByCond(ctx, &entity.DbSql{DbId: id}) return d.DbSqlRepo.DeleteByCond(ctx, &entity.DbSql{DbId: id})
}, func(ctx context.Context) error { }, func(ctx context.Context) error {
var tagIds []uint64 var tagIds []uint64
return d.tagApp.RelateResource(ctx, db.Code, consts.TagResourceTypeDb, tagIds) return d.TagApp.RelateResource(ctx, db.Code, consts.TagResourceTypeDb, tagIds)
}) })
} }
@@ -148,7 +143,7 @@ func (d *dbAppImpl) GetDbConn(dbId uint64, dbName string) (*dbi.DbConn, error) {
return nil, errorx.NewBiz("数据库信息不存在") return nil, errorx.NewBiz("数据库信息不存在")
} }
instance, err := d.dbInstanceApp.GetById(new(entity.DbInstance), db.InstanceId) instance, err := d.DbInstanceApp.GetById(new(entity.DbInstance), db.InstanceId)
if err != nil { if err != nil {
return nil, errorx.NewBiz("数据库实例不存在") return nil, errorx.NewBiz("数据库实例不存在")
} }
@@ -169,7 +164,7 @@ func (d *dbAppImpl) GetDbConn(dbId uint64, dbName string) (*dbi.DbConn, error) {
if err := instance.PwdDecrypt(); err != nil { if err := instance.PwdDecrypt(); err != nil {
return nil, errorx.NewBiz(err.Error()) return nil, errorx.NewBiz(err.Error())
} }
return toDbInfo(instance, dbId, dbName, d.tagApp.ListTagPathByResource(consts.TagResourceTypeDb, db.Code)...), nil return toDbInfo(instance, dbId, dbName, d.TagApp.ListTagPathByResource(consts.TagResourceTypeDb, db.Code)...), nil
}) })
} }

View File

@@ -38,17 +38,14 @@ type DataSyncTask interface {
GetTaskLogList(condition *entity.DataSyncLogQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) GetTaskLogList(condition *entity.DataSyncLogQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error)
} }
func newDataSyncApp(dataSyncRepo repository.DataSyncTask, dataSyncLogRepo repository.DataSyncLog) DataSyncTask {
app := new(dataSyncAppImpl)
app.Repo = dataSyncRepo
app.dataSyncLogRepo = dataSyncLogRepo
return app
}
type dataSyncAppImpl struct { type dataSyncAppImpl struct {
base.AppImpl[*entity.DataSyncTask, repository.DataSyncTask] base.AppImpl[*entity.DataSyncTask, repository.DataSyncTask]
dataSyncLogRepo repository.DataSyncLog DbDataSyncLogRepo repository.DataSyncLog `inject:""`
}
func (d *dataSyncAppImpl) InjectDbDataSyncTaskRepo(repo repository.DataSyncTask) {
d.Repo = repo
} }
func (app *dataSyncAppImpl) GetPageList(condition *entity.DataSyncTaskQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (app *dataSyncAppImpl) GetPageList(condition *entity.DataSyncTaskQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
@@ -328,7 +325,7 @@ func (app *dataSyncAppImpl) endRunning(taskEntity *entity.DataSyncTask, log *ent
} }
func (app *dataSyncAppImpl) saveLog(log *entity.DataSyncLog) { func (app *dataSyncAppImpl) saveLog(log *entity.DataSyncLog) {
app.dataSyncLogRepo.Save(context.Background(), log) app.DbDataSyncLogRepo.Save(context.Background(), log)
} }
func (app *dataSyncAppImpl) InitCronJob() { func (app *dataSyncAppImpl) InitCronJob() {
@@ -374,5 +371,5 @@ func (app *dataSyncAppImpl) InitCronJob() {
} }
func (app *dataSyncAppImpl) GetTaskLogList(condition *entity.DataSyncLogQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (app *dataSyncAppImpl) GetTaskLogList(condition *entity.DataSyncLogQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return app.dataSyncLogRepo.GetTaskLogList(condition, pageParam, toEntity, orderBy...) return app.DbDataSyncLogRepo.GetTaskLogList(condition, pageParam, toEntity, orderBy...)
} }

View File

@@ -33,7 +33,7 @@ type dbScheduler struct {
func newDbScheduler(repositories *repository.Repositories) (*dbScheduler, error) { func newDbScheduler(repositories *repository.Repositories) (*dbScheduler, error) {
scheduler := &dbScheduler{ scheduler := &dbScheduler{
dbApp: dbApp, dbApp: GetDbApp(),
backupRepo: repositories.Backup, backupRepo: repositories.Backup,
backupHistoryRepo: repositories.BackupHistory, backupHistoryRepo: repositories.BackupHistory,
restoreRepo: repositories.Restore, restoreRepo: repositories.Restore,

View File

@@ -14,8 +14,7 @@ type dbSqlAppImpl struct {
base.AppImpl[*entity.DbSql, repository.DbSql] base.AppImpl[*entity.DbSql, repository.DbSql]
} }
func newDbSqlApp(dbSqlRepo repository.DbSql) DbSql { // 注入DbSqlRepo
app := new(dbSqlAppImpl) func (d *dbSqlAppImpl) InjectDbSqlRepo(repo repository.DbSql) {
app.Repo = dbSqlRepo d.Repo = repo
return app
} }

View File

@@ -56,14 +56,8 @@ type DbSqlExec interface {
GetPageList(condition *entity.DbSqlExecQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) GetPageList(condition *entity.DbSqlExecQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error)
} }
func newDbSqlExecApp(dbExecSqlRepo repository.DbSqlExec) DbSqlExec {
return &dbSqlExecAppImpl{
dbSqlExecRepo: dbExecSqlRepo,
}
}
type dbSqlExecAppImpl struct { type dbSqlExecAppImpl struct {
dbSqlExecRepo repository.DbSqlExec DbSqlExecRepo repository.DbSqlExec `inject:""`
} }
func createSqlExecRecord(ctx context.Context, execSqlReq *DbSqlExecReq) *entity.DbSqlExec { func createSqlExecRecord(ctx context.Context, execSqlReq *DbSqlExecReq) *entity.DbSqlExec {
@@ -144,23 +138,23 @@ func (d *dbSqlExecAppImpl) Exec(ctx context.Context, execSqlReq *DbSqlExecReq) (
// 保存sql执行记录如果是查询类则根据系统配置判断是否保存 // 保存sql执行记录如果是查询类则根据系统配置判断是否保存
func (d *dbSqlExecAppImpl) saveSqlExecLog(isQuery bool, dbSqlExecRecord *entity.DbSqlExec) { func (d *dbSqlExecAppImpl) saveSqlExecLog(isQuery bool, dbSqlExecRecord *entity.DbSqlExec) {
if !isQuery { if !isQuery {
d.dbSqlExecRepo.Insert(context.TODO(), dbSqlExecRecord) d.DbSqlExecRepo.Insert(context.TODO(), dbSqlExecRecord)
return return
} }
if config.GetDbSaveQuerySql() { if config.GetDbSaveQuerySql() {
dbSqlExecRecord.Table = "-" dbSqlExecRecord.Table = "-"
dbSqlExecRecord.OldValue = "-" dbSqlExecRecord.OldValue = "-"
dbSqlExecRecord.Type = entity.DbSqlExecTypeQuery dbSqlExecRecord.Type = entity.DbSqlExecTypeQuery
d.dbSqlExecRepo.Insert(context.TODO(), dbSqlExecRecord) d.DbSqlExecRepo.Insert(context.TODO(), dbSqlExecRecord)
} }
} }
func (d *dbSqlExecAppImpl) DeleteBy(ctx context.Context, condition *entity.DbSqlExec) { func (d *dbSqlExecAppImpl) DeleteBy(ctx context.Context, condition *entity.DbSqlExec) {
d.dbSqlExecRepo.DeleteByCond(ctx, condition) d.DbSqlExecRepo.DeleteByCond(ctx, condition)
} }
func (d *dbSqlExecAppImpl) GetPageList(condition *entity.DbSqlExecQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (d *dbSqlExecAppImpl) GetPageList(condition *entity.DbSqlExecQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return d.dbSqlExecRepo.GetPageList(condition, pageParam, toEntity, orderBy...) return d.DbSqlExecRepo.GetPageList(condition, pageParam, toEntity, orderBy...)
} }
func doSelect(ctx context.Context, selectStmt *sqlparser.Select, execSqlReq *DbSqlExecReq) (*DbSqlExecRes, error) { func doSelect(ctx context.Context, selectStmt *sqlparser.Select, execSqlReq *DbSqlExecReq) (*DbSqlExecRes, error) {

View File

@@ -30,16 +30,15 @@ type Instance interface {
GetDatabases(entity *entity.DbInstance) ([]string, error) GetDatabases(entity *entity.DbInstance) ([]string, error)
} }
func newInstanceApp(instanceRepo repository.Instance) Instance {
app := new(instanceAppImpl)
app.Repo = instanceRepo
return app
}
type instanceAppImpl struct { type instanceAppImpl struct {
base.AppImpl[*entity.DbInstance, repository.Instance] base.AppImpl[*entity.DbInstance, repository.Instance]
} }
// 注入DbInstanceRepo
func (i *instanceAppImpl) InjectDbInstanceRepo(repo repository.Instance) {
i.Repo = repo
}
// GetPageList 分页获取数据库实例 // GetPageList 分页获取数据库实例
func (app *instanceAppImpl) GetPageList(condition *entity.InstanceQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (app *instanceAppImpl) GetPageList(condition *entity.InstanceQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return app.GetRepo().GetInstanceList(condition, pageParam, toEntity, orderBy...) return app.GetRepo().GetInstanceList(condition, pageParam, toEntity, orderBy...)

View File

@@ -1,46 +1,49 @@
package persistence package persistence
import "mayfly-go/internal/db/domain/repository" import (
"mayfly-go/internal/db/domain/repository"
var ( "mayfly-go/pkg/ioc"
instanceRepo repository.Instance = newInstanceRepo()
dbRepo repository.Db = newDbRepo()
dbSqlRepo repository.DbSql = newDbSqlRepo()
dbSqlExecRepo repository.DbSqlExec = newDbSqlExecRepo()
dbBackupHistoryRepo = NewDbBackupHistoryRepo()
dbRestoreHistoryRepo = NewDbRestoreHistoryRepo()
dbDataSyncTaskRepo repository.DataSyncTask = newDataSyncTaskRepo()
dbDataSyncLogRepo repository.DataSyncLog = newDataSyncLogRepo()
) )
func Init() {
ioc.Register(newInstanceRepo(), ioc.WithComponentName("DbInstanceRepo"))
ioc.Register(newDbRepo(), ioc.WithComponentName("DbRepo"))
ioc.Register(newDbSqlRepo(), ioc.WithComponentName("DbSqlRepo"))
ioc.Register(newDbSqlExecRepo(), ioc.WithComponentName("DbSqlExecRepo"))
ioc.Register(NewDbBackupHistoryRepo(), ioc.WithComponentName("DbBackupHistoryRepo"))
ioc.Register(NewDbRestoreHistoryRepo(), ioc.WithComponentName("DbRestoreHistoryRepo"))
ioc.Register(newDataSyncTaskRepo(), ioc.WithComponentName("DbDataSyncTaskRepo"))
ioc.Register(newDataSyncLogRepo(), ioc.WithComponentName("DbDataSyncLogRepo"))
}
func GetInstanceRepo() repository.Instance { func GetInstanceRepo() repository.Instance {
return instanceRepo return ioc.Get[repository.Instance]("DbInstanceRepo")
} }
func GetDbRepo() repository.Db { func GetDbRepo() repository.Db {
return dbRepo return ioc.Get[repository.Db]("DbRepo")
} }
func GetDbSqlRepo() repository.DbSql { func GetDbSqlRepo() repository.DbSql {
return dbSqlRepo return ioc.Get[repository.DbSql]("DbSqlRepo")
} }
func GetDbSqlExecRepo() repository.DbSqlExec { func GetDbSqlExecRepo() repository.DbSqlExec {
return dbSqlExecRepo return ioc.Get[repository.DbSqlExec]("DbSqlExecRepo")
} }
func GetDbBackupHistoryRepo() repository.DbBackupHistory { func GetDbBackupHistoryRepo() repository.DbBackupHistory {
return dbBackupHistoryRepo return ioc.Get[repository.DbBackupHistory]("DbBackupHistoryRepo")
} }
func GetDbRestoreHistoryRepo() repository.DbRestoreHistory { func GetDbRestoreHistoryRepo() repository.DbRestoreHistory {
return dbRestoreHistoryRepo return ioc.Get[repository.DbRestoreHistory]("DbRestoreHistoryRepo")
} }
func GetDataSyncLogRepo() repository.DataSyncLog { func GetDataSyncLogRepo() repository.DataSyncLog {
return dbDataSyncLogRepo return ioc.Get[repository.DataSyncLog]("DataSyncLogRepo")
} }
func GetDataSyncTaskRepo() repository.DataSyncTask { func GetDataSyncTaskRepo() repository.DataSyncTask {
return dbDataSyncTaskRepo return ioc.Get[repository.DataSyncTask]("DataSyncTaskRepo")
} }

View File

@@ -2,9 +2,8 @@ package router
import ( import (
"mayfly-go/internal/db/api" "mayfly-go/internal/db/api"
"mayfly-go/internal/db/application" "mayfly-go/pkg/biz"
msgapp "mayfly-go/internal/msg/application" "mayfly-go/pkg/ioc"
tagapp "mayfly-go/internal/tag/application"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -13,13 +12,8 @@ import (
func InitDbRouter(router *gin.RouterGroup) { func InitDbRouter(router *gin.RouterGroup) {
db := router.Group("dbs") db := router.Group("dbs")
d := &api.Db{ d := new(api.Db)
InstanceApp: application.GetInstanceApp(), biz.ErrIsNil(ioc.Inject(d))
DbApp: application.GetDbApp(),
DbSqlExecApp: application.GetDbSqlExecApp(),
MsgApp: msgapp.GetMsgApp(),
TagApp: tagapp.GetTagTreeApp(),
}
reqs := [...]*req.Conf{ reqs := [...]*req.Conf{
// 获取数据库列表 // 获取数据库列表

View File

@@ -2,7 +2,8 @@ package router
import ( import (
"mayfly-go/internal/db/api" "mayfly-go/internal/db/api"
"mayfly-go/internal/db/application" "mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -11,9 +12,8 @@ import (
func InitDbDataSyncRouter(router *gin.RouterGroup) { func InitDbDataSyncRouter(router *gin.RouterGroup) {
instances := router.Group("/datasync/tasks") instances := router.Group("/datasync/tasks")
d := &api.DataSyncTask{ d := new(api.DataSyncTask)
DataSyncTaskApp: application.GetDataSyncTaskApp(), biz.ErrIsNil(ioc.Inject(d))
}
reqs := [...]*req.Conf{ reqs := [...]*req.Conf{
// 获取任务列表 /datasync // 获取任务列表 /datasync

View File

@@ -2,7 +2,8 @@ package router
import ( import (
"mayfly-go/internal/db/api" "mayfly-go/internal/db/api"
"mayfly-go/internal/db/application" "mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -11,9 +12,8 @@ import (
func InitDbSqlRouter(router *gin.RouterGroup) { func InitDbSqlRouter(router *gin.RouterGroup) {
db := router.Group("dbs") db := router.Group("dbs")
dbSql := &api.DbSql{ dbSql := new(api.DbSql)
DbSqlApp: application.GetDbSqlApp(), biz.ErrIsNil(ioc.Inject(dbSql))
}
reqs := [...]*req.Conf{ reqs := [...]*req.Conf{

View File

@@ -2,7 +2,8 @@ package router
import ( import (
"mayfly-go/internal/db/api" "mayfly-go/internal/db/api"
"mayfly-go/internal/db/application" "mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -11,9 +12,8 @@ import (
func InitDbSqlExecRouter(router *gin.RouterGroup) { func InitDbSqlExecRouter(router *gin.RouterGroup) {
db := router.Group("/dbs/:dbId/sql-execs") db := router.Group("/dbs/:dbId/sql-execs")
d := &api.DbSqlExec{ d := new(api.DbSqlExec)
DbSqlExecApp: application.GetDbSqlExecApp(), biz.ErrIsNil(ioc.Inject(d))
}
// 获取所有数据库sql执行记录列表 // 获取所有数据库sql执行记录列表
req.NewGet("", d.DbSqlExecs).Group(db) req.NewGet("", d.DbSqlExecs).Group(db)

View File

@@ -2,7 +2,8 @@ package router
import ( import (
"mayfly-go/internal/db/api" "mayfly-go/internal/db/api"
"mayfly-go/internal/db/application" "mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -11,10 +12,8 @@ import (
func InitInstanceRouter(router *gin.RouterGroup) { func InitInstanceRouter(router *gin.RouterGroup) {
instances := router.Group("/instances") instances := router.Group("/instances")
d := &api.Instance{ d := new(api.Instance)
InstanceApp: application.GetInstanceApp(), biz.ErrIsNil(ioc.Inject(d))
DbApp: application.GetDbApp(),
}
reqs := [...]*req.Conf{ reqs := [...]*req.Conf{
// 获取数据库列表 // 获取数据库列表

View File

@@ -13,7 +13,7 @@ import (
) )
type AuthCert struct { type AuthCert struct {
AuthCertApp application.AuthCert AuthCertApp application.AuthCert `inject:""`
} }
func (ac *AuthCert) BaseAuthCerts(rc *req.Ctx) { func (ac *AuthCert) BaseAuthCerts(rc *req.Ctx) {

View File

@@ -29,9 +29,9 @@ import (
) )
type Machine struct { type Machine struct {
MachineApp application.Machine MachineApp application.Machine `inject:""`
MachineTermOpApp application.MachineTermOp MachineTermOpApp application.MachineTermOp `inject:""`
TagApp tagapp.TagTree TagApp tagapp.TagTree `inject:"TagTreeApp"`
} }
func (m *Machine) Machines(rc *req.Ctx) { func (m *Machine) Machines(rc *req.Ctx) {

View File

@@ -15,7 +15,7 @@ import (
) )
type MachineCronJob struct { type MachineCronJob struct {
MachineCronJobApp application.MachineCronJob MachineCronJobApp application.MachineCronJob `inject:""`
} }
func (m *MachineCronJob) MachineCronJobs(rc *req.Ctx) { func (m *MachineCronJob) MachineCronJobs(rc *req.Ctx) {

View File

@@ -31,8 +31,8 @@ import (
) )
type MachineFile struct { type MachineFile struct {
MachineFileApp application.MachineFile MachineFileApp application.MachineFile `inject:""`
MsgApp msgapp.Msg MsgApp msgapp.Msg `inject:""`
} }
const ( const (

View File

@@ -19,9 +19,9 @@ import (
) )
type MachineScript struct { type MachineScript struct {
MachineScriptApp application.MachineScript MachineScriptApp application.MachineScript `inject:""`
MachineApp application.Machine MachineApp application.Machine `inject:""`
TagApp tagapp.TagTree TagApp tagapp.TagTree `inject:"TagTreeApp"`
} }
func (m *MachineScript) MachineScripts(rc *req.Ctx) { func (m *MachineScript) MachineScripts(rc *req.Ctx) {

View File

@@ -2,58 +2,40 @@ package application
import ( import (
"mayfly-go/internal/machine/infrastructure/persistence" "mayfly-go/internal/machine/infrastructure/persistence"
tagapp "mayfly-go/internal/tag/application" "mayfly-go/pkg/ioc"
) )
var ( func init() {
machineApp Machine = newMachineApp( persistence.Init()
persistence.GetMachineRepo(),
GetAuthCertApp(),
tagapp.GetTagTreeApp(),
)
machineFileApp MachineFile = newMachineFileApp( ioc.Register(new(machineAppImpl), ioc.WithComponentName("MachineApp"))
persistence.GetMachineFileRepo(), ioc.Register(new(machineFileAppImpl), ioc.WithComponentName("MachineFileApp"))
GetMachineApp(), ioc.Register(new(machineScriptAppImpl), ioc.WithComponentName("MachineScriptApp"))
) ioc.Register(new(authCertAppImpl), ioc.WithComponentName("AuthCertApp"))
ioc.Register(new(machineCronJobAppImpl), ioc.WithComponentName("MachineCronJobApp"))
machineScriptApp MachineScript = newMachineScriptApp( ioc.Register(new(machineTermOpAppImpl), ioc.WithComponentName("MachineTermOpApp"))
persistence.GetMachineScriptRepo(), }
GetMachineApp(),
)
authCertApp AuthCert = newAuthCertApp(persistence.GetAuthCertRepo())
machineCropJobApp MachineCronJob = newMachineCronJobApp(
persistence.GetMachineCronJobRepo(),
persistence.GetMachineCronJobRelateRepo(),
persistence.GetMachineCronJobExecRepo(),
GetMachineApp(),
)
machineTermOpApp MachineTermOp = newMachineTermOpApp(persistence.GetMachineTermOpRepo())
)
func GetMachineApp() Machine { func GetMachineApp() Machine {
return machineApp return ioc.Get[Machine]("MachineApp")
} }
func GetMachineFileApp() MachineFile { func GetMachineFileApp() MachineFile {
return machineFileApp return ioc.Get[MachineFile]("MachineFileApp")
} }
func GetMachineScriptApp() MachineScript { func GetMachineScriptApp() MachineScript {
return machineScriptApp return ioc.Get[MachineScript]("MachineScriptApp")
} }
func GetAuthCertApp() AuthCert { func GetAuthCertApp() AuthCert {
return authCertApp return ioc.Get[AuthCert]("AuthCertApp")
} }
func GetMachineCronJobApp() MachineCronJob { func GetMachineCronJobApp() MachineCronJob {
return machineCropJobApp return ioc.Get[MachineCronJob]("MachineCronJobApp")
} }
func GetMachineTermOpApp() MachineTermOp { func GetMachineTermOpApp() MachineTermOp {
return machineTermOpApp return ioc.Get[MachineTermOp]("MachineTermOpApp")
} }

View File

@@ -19,16 +19,15 @@ type AuthCert interface {
GetByIds(ids ...uint64) []*entity.AuthCert GetByIds(ids ...uint64) []*entity.AuthCert
} }
func newAuthCertApp(authCertRepo repository.AuthCert) AuthCert {
return &authCertAppImpl{
base.AppImpl[*entity.AuthCert, repository.AuthCert]{Repo: authCertRepo},
}
}
type authCertAppImpl struct { type authCertAppImpl struct {
base.AppImpl[*entity.AuthCert, repository.AuthCert] base.AppImpl[*entity.AuthCert, repository.AuthCert]
} }
// 注入AuthCertRepo
func (a *authCertAppImpl) InjectAuthCertRepo(repo repository.AuthCert) {
a.Repo = repo
}
func (a *authCertAppImpl) GetPageList(condition *entity.AuthCertQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (a *authCertAppImpl) GetPageList(condition *entity.AuthCertQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return a.GetRepo().GetPageList(condition, pageParam, toEntity) return a.GetRepo().GetPageList(condition, pageParam, toEntity)
} }

View File

@@ -49,24 +49,16 @@ type Machine interface {
GetMachineStats(machineId uint64) (*mcm.Stats, error) GetMachineStats(machineId uint64) (*mcm.Stats, error)
} }
func newMachineApp(machineRepo repository.Machine,
authCertApp AuthCert,
tagApp tagapp.TagTree) Machine {
app := &machineAppImpl{
authCertApp: authCertApp,
tagApp: tagApp,
}
app.Repo = machineRepo
return app
}
type machineAppImpl struct { type machineAppImpl struct {
base.AppImpl[*entity.Machine, repository.Machine] base.AppImpl[*entity.Machine, repository.Machine]
authCertApp AuthCert AuthCertApp AuthCert `inject:""`
TagApp tagapp.TagTree `inject:"TagTreeApp"`
}
tagApp tagapp.TagTree // 注入MachineRepo
func (m *machineAppImpl) InjectMachineRepo(repo repository.Machine) {
m.Repo = repo
} }
// 分页获取机器信息列表 // 分页获取机器信息列表
@@ -99,7 +91,7 @@ func (m *machineAppImpl) SaveMachine(ctx context.Context, me *entity.Machine, ta
return m.Tx(ctx, func(ctx context.Context) error { return m.Tx(ctx, func(ctx context.Context) error {
return m.Insert(ctx, me) return m.Insert(ctx, me)
}, func(ctx context.Context) error { }, func(ctx context.Context) error {
return m.tagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeMachine, tagIds) return m.TagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeMachine, tagIds)
}) })
} }
@@ -117,7 +109,7 @@ func (m *machineAppImpl) SaveMachine(ctx context.Context, me *entity.Machine, ta
return m.Tx(ctx, func(ctx context.Context) error { return m.Tx(ctx, func(ctx context.Context) error {
return m.UpdateById(ctx, me) return m.UpdateById(ctx, me)
}, func(ctx context.Context) error { }, func(ctx context.Context) error {
return m.tagApp.RelateResource(ctx, oldMachine.Code, consts.TagResourceTypeMachine, tagIds) return m.TagApp.RelateResource(ctx, oldMachine.Code, consts.TagResourceTypeMachine, tagIds)
}) })
} }
@@ -162,7 +154,7 @@ func (m *machineAppImpl) Delete(ctx context.Context, id uint64) error {
return m.DeleteById(ctx, id) return m.DeleteById(ctx, id)
}, func(ctx context.Context) error { }, func(ctx context.Context) error {
var tagIds []uint64 var tagIds []uint64
return m.tagApp.RelateResource(ctx, machine.Code, consts.TagResourceTypeMachine, tagIds) return m.TagApp.RelateResource(ctx, machine.Code, consts.TagResourceTypeMachine, tagIds)
}) })
} }
@@ -235,11 +227,11 @@ func (m *machineAppImpl) toMachineInfo(me *entity.Machine) (*mcm.MachineInfo, er
mi.Ip = me.Ip mi.Ip = me.Ip
mi.Port = me.Port mi.Port = me.Port
mi.Username = me.Username mi.Username = me.Username
mi.TagPath = m.tagApp.ListTagPathByResource(consts.TagResourceTypeMachine, me.Code) mi.TagPath = m.TagApp.ListTagPathByResource(consts.TagResourceTypeMachine, me.Code)
mi.EnableRecorder = me.EnableRecorder mi.EnableRecorder = me.EnableRecorder
if me.UseAuthCert() { if me.UseAuthCert() {
ac, err := m.authCertApp.GetById(new(entity.AuthCert), uint64(me.AuthCertId)) ac, err := m.AuthCertApp.GetById(new(entity.AuthCert), uint64(me.AuthCertId))
if err != nil { if err != nil {
return nil, errorx.NewBiz("授权凭证信息已不存在,请重新关联") return nil, errorx.NewBiz("授权凭证信息已不存在,请重新关联")
} }

View File

@@ -50,41 +50,31 @@ type MachineCronJob interface {
RunCronJob(key string) RunCronJob(key string)
} }
type machineCropJobAppImpl struct { type machineCronJobAppImpl struct {
base.AppImpl[*entity.MachineCronJob, repository.MachineCronJob] base.AppImpl[*entity.MachineCronJob, repository.MachineCronJob]
machineCropJobRelateRepo repository.MachineCronJobRelate MachineCronJobRelateRepo repository.MachineCronJobRelate `inject:""`
machineCropJobExecRepo repository.MachineCronJobExec MachineCronJobExecRepo repository.MachineCronJobExec `inject:""`
machineApp Machine MachineApp Machine `inject:""`
} }
func newMachineCronJobApp( // 注入MachineCronJobRepo
machineCropJobRepo repository.MachineCronJob, func (m *machineCronJobAppImpl) InjectMachineCronJobRepo(repo repository.MachineCronJob) {
machineCropJobRelateRepo repository.MachineCronJobRelate, m.Repo = repo
machineCropJobExecRepo repository.MachineCronJobExec,
machineApp Machine,
) MachineCronJob {
app := &machineCropJobAppImpl{
machineCropJobRelateRepo: machineCropJobRelateRepo,
machineCropJobExecRepo: machineCropJobExecRepo,
machineApp: machineApp,
}
app.Repo = machineCropJobRepo
return app
} }
// 分页获取机器脚本任务列表 // 分页获取机器脚本任务列表
func (m *machineCropJobAppImpl) GetPageList(condition *entity.MachineCronJob, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (m *machineCronJobAppImpl) GetPageList(condition *entity.MachineCronJob, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return m.GetRepo().GetPageList(condition, pageParam, toEntity, orderBy...) return m.GetRepo().GetPageList(condition, pageParam, toEntity, orderBy...)
} }
// 获取分页执行结果列表 // 获取分页执行结果列表
func (m *machineCropJobAppImpl) GetExecPageList(condition *entity.MachineCronJobExec, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (m *machineCronJobAppImpl) GetExecPageList(condition *entity.MachineCronJobExec, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return m.machineCropJobExecRepo.GetPageList(condition, pageParam, toEntity, orderBy...) return m.MachineCronJobExecRepo.GetPageList(condition, pageParam, toEntity, orderBy...)
} }
// 保存机器任务信息 // 保存机器任务信息
func (m *machineCropJobAppImpl) SaveMachineCronJob(ctx context.Context, mcj *entity.MachineCronJob) (uint64, error) { func (m *machineCronJobAppImpl) SaveMachineCronJob(ctx context.Context, mcj *entity.MachineCronJob) (uint64, error) {
// 更新操作 // 更新操作
if mcj.Id != 0 { if mcj.Id != 0 {
m.UpdateById(ctx, mcj) m.UpdateById(ctx, mcj)
@@ -104,22 +94,22 @@ func (m *machineCropJobAppImpl) SaveMachineCronJob(ctx context.Context, mcj *ent
return mcj.Id, nil return mcj.Id, nil
} }
func (m *machineCropJobAppImpl) Delete(ctx context.Context, id uint64) { func (m *machineCronJobAppImpl) Delete(ctx context.Context, id uint64) {
m.DeleteById(ctx, id) m.DeleteById(ctx, id)
m.machineCropJobExecRepo.DeleteByCond(ctx, &entity.MachineCronJobExec{CronJobId: id}) m.MachineCronJobExecRepo.DeleteByCond(ctx, &entity.MachineCronJobExec{CronJobId: id})
m.machineCropJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{CronJobId: id}) m.MachineCronJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{CronJobId: id})
} }
func (m *machineCropJobAppImpl) GetRelateMachineIds(cronJobId uint64) []uint64 { func (m *machineCronJobAppImpl) GetRelateMachineIds(cronJobId uint64) []uint64 {
return m.machineCropJobRelateRepo.GetMachineIds(cronJobId) return m.MachineCronJobRelateRepo.GetMachineIds(cronJobId)
} }
func (m *machineCropJobAppImpl) GetRelateCronJobIds(machineId uint64) []uint64 { func (m *machineCronJobAppImpl) GetRelateCronJobIds(machineId uint64) []uint64 {
return m.machineCropJobRelateRepo.GetCronJobIds(machineId) return m.MachineCronJobRelateRepo.GetCronJobIds(machineId)
} }
func (m *machineCropJobAppImpl) CronJobRelateMachines(ctx context.Context, cronJobId uint64, machineIds []uint64) { func (m *machineCronJobAppImpl) CronJobRelateMachines(ctx context.Context, cronJobId uint64, machineIds []uint64) {
oldMachineIds := m.machineCropJobRelateRepo.GetMachineIds(cronJobId) oldMachineIds := m.MachineCronJobRelateRepo.GetMachineIds(cronJobId)
addIds, delIds, _ := collx.ArrayCompare[uint64](machineIds, oldMachineIds) addIds, delIds, _ := collx.ArrayCompare[uint64](machineIds, oldMachineIds)
addVals := make([]*entity.MachineCronJobRelate, 0) addVals := make([]*entity.MachineCronJobRelate, 0)
@@ -129,20 +119,20 @@ func (m *machineCropJobAppImpl) CronJobRelateMachines(ctx context.Context, cronJ
CronJobId: cronJobId, CronJobId: cronJobId,
}) })
} }
m.machineCropJobRelateRepo.BatchInsert(ctx, addVals) m.MachineCronJobRelateRepo.BatchInsert(ctx, addVals)
for _, delId := range delIds { for _, delId := range delIds {
m.machineCropJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{CronJobId: cronJobId, MachineId: delId}) m.MachineCronJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{CronJobId: cronJobId, MachineId: delId})
} }
} }
func (m *machineCropJobAppImpl) MachineRelateCronJobs(ctx context.Context, machineId uint64, cronJobs []uint64) { func (m *machineCronJobAppImpl) MachineRelateCronJobs(ctx context.Context, machineId uint64, cronJobs []uint64) {
if len(cronJobs) == 0 { if len(cronJobs) == 0 {
m.machineCropJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{MachineId: machineId}) m.MachineCronJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{MachineId: machineId})
return return
} }
oldCronIds := m.machineCropJobRelateRepo.GetCronJobIds(machineId) oldCronIds := m.MachineCronJobRelateRepo.GetCronJobIds(machineId)
addIds, delIds, _ := collx.ArrayCompare[uint64](cronJobs, oldCronIds) addIds, delIds, _ := collx.ArrayCompare[uint64](cronJobs, oldCronIds)
addVals := make([]*entity.MachineCronJobRelate, 0) addVals := make([]*entity.MachineCronJobRelate, 0)
@@ -152,14 +142,14 @@ func (m *machineCropJobAppImpl) MachineRelateCronJobs(ctx context.Context, machi
CronJobId: addId, CronJobId: addId,
}) })
} }
m.machineCropJobRelateRepo.BatchInsert(ctx, addVals) m.MachineCronJobRelateRepo.BatchInsert(ctx, addVals)
for _, delId := range delIds { for _, delId := range delIds {
m.machineCropJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{CronJobId: delId, MachineId: machineId}) m.MachineCronJobRelateRepo.DeleteByCond(ctx, &entity.MachineCronJobRelate{CronJobId: delId, MachineId: machineId})
} }
} }
func (m *machineCropJobAppImpl) InitCronJob() { func (m *machineCronJobAppImpl) InitCronJob() {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
logx.ErrorTrace("机器计划任务初始化失败: %s", err.(error)) logx.ErrorTrace("机器计划任务初始化失败: %s", err.(error))
@@ -192,7 +182,7 @@ func (m *machineCropJobAppImpl) InitCronJob() {
} }
} }
func (m *machineCropJobAppImpl) RunCronJob(key string) { func (m *machineCronJobAppImpl) RunCronJob(key string) {
// 简单使用redis分布式锁防止多实例同一时刻重复执行 // 简单使用redis分布式锁防止多实例同一时刻重复执行
if lock := rediscli.NewLock(key, 30*time.Second); lock != nil { if lock := rediscli.NewLock(key, 30*time.Second); lock != nil {
if !lock.Lock() { if !lock.Lock() {
@@ -209,13 +199,13 @@ func (m *machineCropJobAppImpl) RunCronJob(key string) {
scheduler.RemoveByKey(key) scheduler.RemoveByKey(key)
} }
machienIds := m.machineCropJobRelateRepo.GetMachineIds(cronJob.Id) machienIds := m.MachineCronJobRelateRepo.GetMachineIds(cronJob.Id)
for _, machineId := range machienIds { for _, machineId := range machienIds {
go m.runCronJob0(machineId, cronJob) go m.runCronJob0(machineId, cronJob)
} }
} }
func (m *machineCropJobAppImpl) addCronJob(mcj *entity.MachineCronJob) { func (m *machineCronJobAppImpl) addCronJob(mcj *entity.MachineCronJob) {
var key string var key string
isDisable := mcj.Status == entity.MachineCronJobStatusDisable isDisable := mcj.Status == entity.MachineCronJobStatusDisable
if mcj.Id == 0 { if mcj.Id == 0 {
@@ -237,11 +227,11 @@ func (m *machineCropJobAppImpl) addCronJob(mcj *entity.MachineCronJob) {
go m.RunCronJob(key) go m.RunCronJob(key)
}) })
} }
func (m *machineCropJobAppImpl) runCronJob0(mid uint64, cronJob *entity.MachineCronJob) { func (m *machineCronJobAppImpl) runCronJob0(mid uint64, cronJob *entity.MachineCronJob) {
defer func() { defer func() {
if err := recover(); err != nil { if err := recover(); err != nil {
res := anyx.ToString(err) res := anyx.ToString(err)
m.machineCropJobExecRepo.Insert(context.TODO(), &entity.MachineCronJobExec{ m.MachineCronJobExecRepo.Insert(context.TODO(), &entity.MachineCronJobExec{
MachineId: mid, MachineId: mid,
CronJobId: cronJob.Id, CronJobId: cronJob.Id,
ExecTime: time.Now(), ExecTime: time.Now(),
@@ -252,7 +242,7 @@ func (m *machineCropJobAppImpl) runCronJob0(mid uint64, cronJob *entity.MachineC
} }
}() }()
machineCli, err := m.machineApp.GetCli(uint64(mid)) machineCli, err := m.MachineApp.GetCli(uint64(mid))
biz.ErrIsNilAppendErr(err, "获取客户端连接失败: %s") biz.ErrIsNilAppendErr(err, "获取客户端连接失败: %s")
res, err := machineCli.Run(cronJob.Script) res, err := machineCli.Run(cronJob.Script)
if err != nil { if err != nil {
@@ -281,5 +271,5 @@ func (m *machineCropJobAppImpl) runCronJob0(mid uint64, cronJob *entity.MachineC
execRes.Status = entity.MachineCronJobExecStatusError execRes.Status = entity.MachineCronJobExecStatusError
} }
// 保存执行记录 // 保存执行记录
m.machineCropJobExecRepo.Insert(context.TODO(), execRes) m.MachineCronJobExecRepo.Insert(context.TODO(), execRes)
} }

View File

@@ -72,42 +72,40 @@ type MachineFile interface {
Rename(fileId uint64, oldname string, newname string) (*mcm.MachineInfo, error) Rename(fileId uint64, oldname string, newname string) (*mcm.MachineInfo, error)
} }
func newMachineFileApp(machineFileRepo repository.MachineFile, machineApp Machine) MachineFile {
app := &machineFileAppImpl{machineApp: machineApp, machineFileRepo: machineFileRepo}
app.Repo = machineFileRepo
return app
}
type machineFileAppImpl struct { type machineFileAppImpl struct {
base.AppImpl[*entity.MachineFile, repository.MachineFile] base.AppImpl[*entity.MachineFile, repository.MachineFile]
machineFileRepo repository.MachineFile MachineFileRepo repository.MachineFile `inject:""`
MachineApp Machine `inject:""`
}
machineApp Machine // 注入MachineFileRepo
func (m *machineFileAppImpl) InjectMachineFileRepo(repo repository.MachineFile) {
m.Repo = repo
} }
// 分页获取机器脚本信息列表 // 分页获取机器脚本信息列表
func (m *machineFileAppImpl) GetPageList(condition *entity.MachineFile, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (m *machineFileAppImpl) GetPageList(condition *entity.MachineFile, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return m.machineFileRepo.GetPageList(condition, pageParam, toEntity, orderBy...) return m.MachineFileRepo.GetPageList(condition, pageParam, toEntity, orderBy...)
} }
// 根据条件获取 // 根据条件获取
func (m *machineFileAppImpl) GetMachineFile(condition *entity.MachineFile, cols ...string) error { func (m *machineFileAppImpl) GetMachineFile(condition *entity.MachineFile, cols ...string) error {
return m.machineFileRepo.GetBy(condition, cols...) return m.MachineFileRepo.GetBy(condition, cols...)
} }
// 保存机器文件配置 // 保存机器文件配置
func (m *machineFileAppImpl) Save(ctx context.Context, mf *entity.MachineFile) error { func (m *machineFileAppImpl) Save(ctx context.Context, mf *entity.MachineFile) error {
_, err := m.machineApp.GetById(new(entity.Machine), mf.MachineId, "Name") _, err := m.MachineApp.GetById(new(entity.Machine), mf.MachineId, "Name")
if err != nil { if err != nil {
return errorx.NewBiz("该机器不存在") return errorx.NewBiz("该机器不存在")
} }
if mf.Id != 0 { if mf.Id != 0 {
return m.machineFileRepo.UpdateById(ctx, mf) return m.MachineFileRepo.UpdateById(ctx, mf)
} }
return m.machineFileRepo.Insert(ctx, mf) return m.MachineFileRepo.Insert(ctx, mf)
} }
func (m *machineFileAppImpl) ReadDir(fid uint64, path string) ([]fs.FileInfo, error) { func (m *machineFileAppImpl) ReadDir(fid uint64, path string) ([]fs.FileInfo, error) {
@@ -308,7 +306,7 @@ func (m *machineFileAppImpl) GetMachineCli(fid uint64, inputPath ...string) (*mc
return nil, errorx.NewBiz("无权访问该目录或文件: %s", path) return nil, errorx.NewBiz("无权访问该目录或文件: %s", path)
} }
} }
return m.machineApp.GetCli(mf.MachineId) return m.MachineApp.GetCli(mf.MachineId)
} }
// 获取文件机器 sftp cli // 获取文件机器 sftp cli

View File

@@ -20,16 +20,15 @@ type MachineScript interface {
Delete(ctx context.Context, id uint64) Delete(ctx context.Context, id uint64)
} }
func newMachineScriptApp(machineScriptRepo repository.MachineScript, machineApp Machine) MachineScript {
app := &machineScriptAppImpl{machineApp: machineApp}
app.Repo = machineScriptRepo
return app
}
type machineScriptAppImpl struct { type machineScriptAppImpl struct {
base.AppImpl[*entity.MachineScript, repository.MachineScript] base.AppImpl[*entity.MachineScript, repository.MachineScript]
machineApp Machine MachineApp Machine `inject:""`
}
// 注入MachineScriptRepo
func (m *machineScriptAppImpl) InjectMachineScriptRepo(repo repository.MachineScript) {
m.Repo = repo
} }
const Common_Script_Machine_Id = 9999999 const Common_Script_Machine_Id = 9999999
@@ -43,7 +42,7 @@ func (m *machineScriptAppImpl) GetPageList(condition *entity.MachineScript, page
func (m *machineScriptAppImpl) Save(ctx context.Context, ms *entity.MachineScript) error { func (m *machineScriptAppImpl) Save(ctx context.Context, ms *entity.MachineScript) error {
// 如果机器id不为公共脚本id则校验机器是否存在 // 如果机器id不为公共脚本id则校验机器是否存在
if machineId := ms.MachineId; machineId != Common_Script_Machine_Id { if machineId := ms.MachineId; machineId != Common_Script_Machine_Id {
_, err := m.machineApp.GetById(new(entity.Machine), machineId, "Name") _, err := m.MachineApp.GetById(new(entity.Machine), machineId, "Name")
if err != nil { if err != nil {
return errorx.NewBiz("该机器不存在") return errorx.NewBiz("该机器不存在")
} }

View File

@@ -33,16 +33,15 @@ type MachineTermOp interface {
TimerDeleteTermOp() TimerDeleteTermOp()
} }
func newMachineTermOpApp(machineTermOpRepo repository.MachineTermOp) MachineTermOp {
return &machineTermOpAppImpl{
base.AppImpl[*entity.MachineTermOp, repository.MachineTermOp]{Repo: machineTermOpRepo},
}
}
type machineTermOpAppImpl struct { type machineTermOpAppImpl struct {
base.AppImpl[*entity.MachineTermOp, repository.MachineTermOp] base.AppImpl[*entity.MachineTermOp, repository.MachineTermOp]
} }
// 注入MachineTermOpRepo
func (m *machineTermOpAppImpl) InjectMachineTermOpRepo(repo repository.MachineTermOp) {
m.Repo = repo
}
func (m *machineTermOpAppImpl) TermConn(ctx context.Context, cli *mcm.Cli, wsConn *websocket.Conn, rows, cols int) error { func (m *machineTermOpAppImpl) TermConn(ctx context.Context, cli *mcm.Cli, wsConn *websocket.Conn, rows, cols int) error {
var recorder *mcm.Recorder var recorder *mcm.Recorder
var termOpRecord *entity.MachineTermOp var termOpRecord *entity.MachineTermOp

View File

@@ -8,16 +8,16 @@ import (
"mayfly-go/pkg/model" "mayfly-go/pkg/model"
) )
type machineCropJobRepoImpl struct { type machineCronJobRepoImpl struct {
base.RepoImpl[*entity.MachineCronJob] base.RepoImpl[*entity.MachineCronJob]
} }
func newMachineCronJobRepo() repository.MachineCronJob { func newMachineCronJobRepo() repository.MachineCronJob {
return &machineCropJobRepoImpl{base.RepoImpl[*entity.MachineCronJob]{M: new(entity.MachineCronJob)}} return &machineCronJobRepoImpl{base.RepoImpl[*entity.MachineCronJob]{M: new(entity.MachineCronJob)}}
} }
// 分页获取机器信息列表 // 分页获取机器信息列表
func (m *machineCropJobRepoImpl) GetPageList(condition *entity.MachineCronJob, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (m *machineCronJobRepoImpl) GetPageList(condition *entity.MachineCronJob, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(condition).Like("name", condition.Name).Eq("status", condition.Status).WithOrderBy(orderBy...) qd := gormx.NewQuery(condition).Like("name", condition.Name).Eq("status", condition.Status).WithOrderBy(orderBy...)
return gormx.PageQuery(qd, pageParam, toEntity) return gormx.PageQuery(qd, pageParam, toEntity)
} }

View File

@@ -7,27 +7,27 @@ import (
"mayfly-go/pkg/gormx" "mayfly-go/pkg/gormx"
) )
type machineCropJobRelateRepoImpl struct { type machineCronJobRelateRepoImpl struct {
base.RepoImpl[*entity.MachineCronJobRelate] base.RepoImpl[*entity.MachineCronJobRelate]
} }
func newMachineCropJobRelateRepo() repository.MachineCronJobRelate { func newMachineCronJobRelateRepo() repository.MachineCronJobRelate {
return &machineCropJobRelateRepoImpl{base.RepoImpl[*entity.MachineCronJobRelate]{M: new(entity.MachineCronJobRelate)}} return &machineCronJobRelateRepoImpl{base.RepoImpl[*entity.MachineCronJobRelate]{M: new(entity.MachineCronJobRelate)}}
} }
func (m *machineCropJobRelateRepoImpl) GetList(condition *entity.MachineCronJobRelate) []entity.MachineCronJobRelate { func (m *machineCronJobRelateRepoImpl) GetList(condition *entity.MachineCronJobRelate) []entity.MachineCronJobRelate {
list := new([]entity.MachineCronJobRelate) list := new([]entity.MachineCronJobRelate)
m.ListByCond(condition, list) m.ListByCond(condition, list)
return *list return *list
} }
func (m *machineCropJobRelateRepoImpl) GetMachineIds(cronJobId uint64) []uint64 { func (m *machineCronJobRelateRepoImpl) GetMachineIds(cronJobId uint64) []uint64 {
var machineIds []uint64 var machineIds []uint64
m.ListByCond(&entity.MachineCronJobRelate{CronJobId: cronJobId}, &machineIds, "machine_id") m.ListByCond(&entity.MachineCronJobRelate{CronJobId: cronJobId}, &machineIds, "machine_id")
return machineIds return machineIds
} }
func (m *machineCropJobRelateRepoImpl) GetCronJobIds(machineId uint64) []uint64 { func (m *machineCronJobRelateRepoImpl) GetCronJobIds(machineId uint64) []uint64 {
var cronJobIds []uint64 var cronJobIds []uint64
gormx.ListBy(&entity.MachineCronJobRelate{MachineId: machineId}, &cronJobIds, "cron_job_id") gormx.ListBy(&entity.MachineCronJobRelate{MachineId: machineId}, &cronJobIds, "cron_job_id")
return cronJobIds return cronJobIds

View File

@@ -1,46 +1,49 @@
package persistence package persistence
import "mayfly-go/internal/machine/domain/repository" import (
"mayfly-go/internal/machine/domain/repository"
var ( "mayfly-go/pkg/ioc"
machineRepo repository.Machine = newMachineRepo()
machineFileRepo repository.MachineFile = newMachineFileRepo()
machineScriptRepo repository.MachineScript = newMachineScriptRepo()
authCertRepo repository.AuthCert = newAuthCertRepo()
machineCropJobRepo repository.MachineCronJob = newMachineCronJobRepo()
machineCropJobExecRepo repository.MachineCronJobExec = newMachineCronJobExecRepo()
machineCronJobRelateRepo repository.MachineCronJobRelate = newMachineCropJobRelateRepo()
machineTermOpRepo repository.MachineTermOp = newMachineTermOpRepoImpl()
) )
func Init() {
ioc.Register(newMachineRepo(), ioc.WithComponentName("MachineRepo"))
ioc.Register(newMachineFileRepo(), ioc.WithComponentName("MachineFileRepo"))
ioc.Register(newMachineScriptRepo(), ioc.WithComponentName("MachineScriptRepo"))
ioc.Register(newAuthCertRepo(), ioc.WithComponentName("AuthCertRepo"))
ioc.Register(newMachineCronJobRepo(), ioc.WithComponentName("MachineCronJobRepo"))
ioc.Register(newMachineCronJobExecRepo(), ioc.WithComponentName("MachineCronJobExecRepo"))
ioc.Register(newMachineCronJobRelateRepo(), ioc.WithComponentName("MachineCronJobRelateRepo"))
ioc.Register(newMachineTermOpRepoImpl(), ioc.WithComponentName("MachineTermOpRepo"))
}
func GetMachineRepo() repository.Machine { func GetMachineRepo() repository.Machine {
return machineRepo return ioc.Get[repository.Machine]("MachineRepo")
} }
func GetMachineFileRepo() repository.MachineFile { func GetMachineFileRepo() repository.MachineFile {
return machineFileRepo return ioc.Get[repository.MachineFile]("MachineFileRepo")
} }
func GetMachineScriptRepo() repository.MachineScript { func GetMachineScriptRepo() repository.MachineScript {
return machineScriptRepo return ioc.Get[repository.MachineScript]("MachineScriptRepo")
} }
func GetAuthCertRepo() repository.AuthCert { func GetAuthCertRepo() repository.AuthCert {
return authCertRepo return ioc.Get[repository.AuthCert]("AuthCertRepo")
} }
func GetMachineCronJobRepo() repository.MachineCronJob { func GetMachineCronJobRepo() repository.MachineCronJob {
return machineCropJobRepo return ioc.Get[repository.MachineCronJob]("MachineCronJobRepo")
} }
func GetMachineCronJobExecRepo() repository.MachineCronJobExec { func GetMachineCronJobExecRepo() repository.MachineCronJobExec {
return machineCropJobExecRepo return ioc.Get[repository.MachineCronJobExec]("MachineCronJobExecRepo")
} }
func GetMachineCronJobRelateRepo() repository.MachineCronJobRelate { func GetMachineCronJobRelateRepo() repository.MachineCronJobRelate {
return machineCronJobRelateRepo return ioc.Get[repository.MachineCronJobRelate]("MachineCropJobRelateRepo")
} }
func GetMachineTermOpRepo() repository.MachineTermOp { func GetMachineTermOpRepo() repository.MachineTermOp {
return machineTermOpRepo return ioc.Get[repository.MachineTermOp]("MachineTermOpRepo")
} }

View File

@@ -2,17 +2,19 @@ package router
import ( import (
"mayfly-go/internal/machine/api" "mayfly-go/internal/machine/api"
"mayfly-go/internal/machine/application" "mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func InitAuthCertRouter(router *gin.RouterGroup) { func InitAuthCertRouter(router *gin.RouterGroup) {
r := &api.AuthCert{AuthCertApp: application.GetAuthCertApp()}
ag := router.Group("sys/authcerts") ag := router.Group("sys/authcerts")
r := new(api.AuthCert)
biz.ErrIsNil(ioc.Inject(r))
reqs := [...]*req.Conf{ reqs := [...]*req.Conf{
req.NewGet("", r.AuthCerts).RequiredPermissionCode("authcert"), req.NewGet("", r.AuthCerts).RequiredPermissionCode("authcert"),

View File

@@ -2,19 +2,16 @@ package router
import ( import (
"mayfly-go/internal/machine/api" "mayfly-go/internal/machine/api"
"mayfly-go/internal/machine/application" "mayfly-go/pkg/biz"
tagapp "mayfly-go/internal/tag/application" "mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func InitMachineRouter(router *gin.RouterGroup) { func InitMachineRouter(router *gin.RouterGroup) {
m := &api.Machine{ m := new(api.Machine)
MachineApp: application.GetMachineApp(), biz.ErrIsNil(ioc.Inject(m))
MachineTermOpApp: application.GetMachineTermOpApp(),
TagApp: tagapp.GetTagTreeApp(),
}
machines := router.Group("machines") machines := router.Group("machines")
{ {

View File

@@ -2,7 +2,8 @@ package router
import ( import (
"mayfly-go/internal/machine/api" "mayfly-go/internal/machine/api"
"mayfly-go/internal/machine/application" "mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -10,9 +11,9 @@ import (
func InitMachineCronJobRouter(router *gin.RouterGroup) { func InitMachineCronJobRouter(router *gin.RouterGroup) {
cronjobs := router.Group("machine-cronjobs") cronjobs := router.Group("machine-cronjobs")
cj := &api.MachineCronJob{
MachineCronJobApp: application.GetMachineCronJobApp(), cj := new(api.MachineCronJob)
} biz.ErrIsNil(ioc.Inject(cj))
reqs := [...]*req.Conf{ reqs := [...]*req.Conf{
// 获取机器任务列表 // 获取机器任务列表

View File

@@ -2,8 +2,8 @@ package router
import ( import (
"mayfly-go/internal/machine/api" "mayfly-go/internal/machine/api"
"mayfly-go/internal/machine/application" "mayfly-go/pkg/biz"
msgapp "mayfly-go/internal/msg/application" "mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -12,10 +12,8 @@ import (
func InitMachineFileRouter(router *gin.RouterGroup) { func InitMachineFileRouter(router *gin.RouterGroup) {
machineFile := router.Group("machines") machineFile := router.Group("machines")
mf := &api.MachineFile{ mf := new(api.MachineFile)
MachineFileApp: application.GetMachineFileApp(), biz.ErrIsNil(ioc.Inject(mf))
MsgApp: msgapp.GetMsgApp(),
}
reqs := [...]*req.Conf{ reqs := [...]*req.Conf{
// 获取指定机器文件列表 // 获取指定机器文件列表

View File

@@ -2,8 +2,8 @@ package router
import ( import (
"mayfly-go/internal/machine/api" "mayfly-go/internal/machine/api"
"mayfly-go/internal/machine/application" "mayfly-go/pkg/biz"
tagapp "mayfly-go/internal/tag/application" "mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -11,11 +11,9 @@ import (
func InitMachineScriptRouter(router *gin.RouterGroup) { func InitMachineScriptRouter(router *gin.RouterGroup) {
machines := router.Group("machines") machines := router.Group("machines")
ms := &api.MachineScript{
MachineScriptApp: application.GetMachineScriptApp(), ms := new(api.MachineScript)
MachineApp: application.GetMachineApp(), biz.ErrIsNil(ioc.Inject(ms))
TagApp: tagapp.GetTagTreeApp(),
}
reqs := [...]*req.Conf{ reqs := [...]*req.Conf{
// 获取指定机器脚本列表 // 获取指定机器脚本列表

View File

@@ -23,8 +23,8 @@ import (
) )
type Mongo struct { type Mongo struct {
MongoApp application.Mongo MongoApp application.Mongo `inject:""`
TagApp tagapp.TagTree TagApp tagapp.TagTree `inject:"TagTreeApp"`
} }
func (m *Mongo) Mongos(rc *req.Ctx) { func (m *Mongo) Mongos(rc *req.Ctx) {

View File

@@ -2,13 +2,15 @@ package application
import ( import (
"mayfly-go/internal/mongo/infrastructure/persistence" "mayfly-go/internal/mongo/infrastructure/persistence"
tagapp "mayfly-go/internal/tag/application" "mayfly-go/pkg/ioc"
) )
var ( func init() {
mongoApp Mongo = newMongoAppImpl(persistence.GetMongoRepo(), tagapp.GetTagTreeApp()) persistence.Init()
)
ioc.Register(new(mongoAppImpl), ioc.WithComponentName("MongoApp"))
}
func GetMongoApp() Mongo { func GetMongoApp() Mongo {
return mongoApp return ioc.Get[Mongo]("MongoApp")
} }

View File

@@ -31,18 +31,15 @@ type Mongo interface {
GetMongoConn(id uint64) (*mgm.MongoConn, error) GetMongoConn(id uint64) (*mgm.MongoConn, error)
} }
func newMongoAppImpl(mongoRepo repository.Mongo, tagApp tagapp.TagTree) Mongo {
app := &mongoAppImpl{
tagApp: tagApp,
}
app.Repo = mongoRepo
return app
}
type mongoAppImpl struct { type mongoAppImpl struct {
base.AppImpl[*entity.Mongo, repository.Mongo] base.AppImpl[*entity.Mongo, repository.Mongo]
tagApp tagapp.TagTree TagApp tagapp.TagTree `inject:"TagTreeApp"`
}
// 注入MongoRepo
func (d *mongoAppImpl) InjectMongoRepo(repo repository.Mongo) {
d.Repo = repo
} }
// 分页获取数据库信息列表 // 分页获取数据库信息列表
@@ -63,7 +60,7 @@ func (d *mongoAppImpl) Delete(ctx context.Context, id uint64) error {
}, },
func(ctx context.Context) error { func(ctx context.Context) error {
var tagIds []uint64 var tagIds []uint64
return d.tagApp.RelateResource(ctx, mongoEntity.Code, consts.TagResourceTypeMongo, tagIds) return d.TagApp.RelateResource(ctx, mongoEntity.Code, consts.TagResourceTypeMongo, tagIds)
}) })
} }
@@ -91,7 +88,7 @@ func (d *mongoAppImpl) SaveMongo(ctx context.Context, m *entity.Mongo, tagIds ..
return d.Tx(ctx, func(ctx context.Context) error { return d.Tx(ctx, func(ctx context.Context) error {
return d.Insert(ctx, m) return d.Insert(ctx, m)
}, func(ctx context.Context) error { }, func(ctx context.Context) error {
return d.tagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeMongo, tagIds) return d.TagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeMongo, tagIds)
}) })
} }
@@ -109,7 +106,7 @@ func (d *mongoAppImpl) SaveMongo(ctx context.Context, m *entity.Mongo, tagIds ..
return d.Tx(ctx, func(ctx context.Context) error { return d.Tx(ctx, func(ctx context.Context) error {
return d.UpdateById(ctx, m) return d.UpdateById(ctx, m)
}, func(ctx context.Context) error { }, func(ctx context.Context) error {
return d.tagApp.RelateResource(ctx, oldMongo.Code, consts.TagResourceTypeMongo, tagIds) return d.TagApp.RelateResource(ctx, oldMongo.Code, consts.TagResourceTypeMongo, tagIds)
}) })
} }
@@ -119,6 +116,6 @@ func (d *mongoAppImpl) GetMongoConn(id uint64) (*mgm.MongoConn, error) {
if err != nil { if err != nil {
return nil, errorx.NewBiz("mongo信息不存在") return nil, errorx.NewBiz("mongo信息不存在")
} }
return me.ToMongoInfo(d.tagApp.ListTagPathByResource(consts.TagResourceTypeMongo, me.Code)...), nil return me.ToMongoInfo(d.TagApp.ListTagPathByResource(consts.TagResourceTypeMongo, me.Code)...), nil
}) })
} }

View File

@@ -2,12 +2,13 @@ package persistence
import ( import (
"mayfly-go/internal/mongo/domain/repository" "mayfly-go/internal/mongo/domain/repository"
"mayfly-go/pkg/ioc"
) )
var ( func Init() {
mongoRepo repository.Mongo = newMongoRepo() ioc.Register(newMongoRepo(), ioc.WithComponentName("MongoRepo"))
) }
func GetMongoRepo() repository.Mongo { func GetMongoRepo() repository.Mongo {
return mongoRepo return ioc.Get[repository.Mongo]("MongoRepo")
} }

View File

@@ -2,8 +2,8 @@ package router
import ( import (
"mayfly-go/internal/mongo/api" "mayfly-go/internal/mongo/api"
"mayfly-go/internal/mongo/application" "mayfly-go/pkg/biz"
tagapp "mayfly-go/internal/tag/application" "mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -12,10 +12,8 @@ import (
func InitMongoRouter(router *gin.RouterGroup) { func InitMongoRouter(router *gin.RouterGroup) {
m := router.Group("mongos") m := router.Group("mongos")
ma := &api.Mongo{ ma := new(api.Mongo)
MongoApp: application.GetMongoApp(), biz.ErrIsNil(ioc.Inject(ma))
TagApp: tagapp.GetTagTreeApp(),
}
saveDataPerm := req.NewPermission("mongo:data:save") saveDataPerm := req.NewPermission("mongo:data:save")

View File

@@ -9,7 +9,7 @@ import (
) )
type Msg struct { type Msg struct {
MsgApp application.Msg MsgApp application.Msg `inject:""`
} }
// 获取账号接收的消息列表 // 获取账号接收的消息列表

View File

@@ -2,12 +2,15 @@ package application
import ( import (
"mayfly-go/internal/msg/infrastructure/persistence" "mayfly-go/internal/msg/infrastructure/persistence"
"mayfly-go/pkg/ioc"
) )
var ( func init() {
msgApp = newMsgApp(persistence.GetMsgRepo()) persistence.Init()
)
ioc.Register(new(msgAppImpl), ioc.WithComponentName("MsgApp"))
}
func GetMsgApp() Msg { func GetMsgApp() Msg {
return msgApp return ioc.Get[Msg]("MsgApp")
} }

View File

@@ -19,27 +19,21 @@ type Msg interface {
CreateAndSend(la *model.LoginAccount, msg *dto.SysMsg) CreateAndSend(la *model.LoginAccount, msg *dto.SysMsg)
} }
func newMsgApp(msgRepo repository.Msg) Msg {
return &msgAppImpl{
msgRepo: msgRepo,
}
}
type msgAppImpl struct { type msgAppImpl struct {
msgRepo repository.Msg MsgRepo repository.Msg `inject:""`
} }
func (a *msgAppImpl) GetPageList(condition *entity.Msg, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (a *msgAppImpl) GetPageList(condition *entity.Msg, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return a.msgRepo.GetPageList(condition, pageParam, toEntity) return a.MsgRepo.GetPageList(condition, pageParam, toEntity)
} }
func (a *msgAppImpl) Create(ctx context.Context, msg *entity.Msg) { func (a *msgAppImpl) Create(ctx context.Context, msg *entity.Msg) {
a.msgRepo.Insert(ctx, msg) a.MsgRepo.Insert(ctx, msg)
} }
func (a *msgAppImpl) CreateAndSend(la *model.LoginAccount, wmsg *dto.SysMsg) { func (a *msgAppImpl) CreateAndSend(la *model.LoginAccount, wmsg *dto.SysMsg) {
now := time.Now() now := time.Now()
msg := &entity.Msg{Type: 2, Msg: wmsg.Msg, RecipientId: int64(la.Id), CreateTime: &now, CreatorId: la.Id, Creator: la.Username} msg := &entity.Msg{Type: 2, Msg: wmsg.Msg, RecipientId: int64(la.Id), CreateTime: &now, CreatorId: la.Id, Creator: la.Username}
a.msgRepo.Insert(context.TODO(), msg) a.MsgRepo.Insert(context.TODO(), msg)
ws.SendJsonMsg(ws.UserId(la.Id), wmsg.ClientId, wmsg) ws.SendJsonMsg(ws.UserId(la.Id), wmsg.ClientId, wmsg)
} }

View File

@@ -1,11 +1,14 @@
package persistence package persistence
import "mayfly-go/internal/msg/domain/repository" import (
"mayfly-go/internal/msg/domain/repository"
var ( "mayfly-go/pkg/ioc"
msgRepo = newMsgRepo()
) )
func GetMsgRepo() repository.Msg { func Init() {
return msgRepo ioc.Register(newMsgRepo(), ioc.WithComponentName("MsgRepo"))
}
func GetMsgRepo() repository.Msg {
return ioc.Get[repository.Msg]("msgRepo")
} }

View File

@@ -2,7 +2,7 @@ package router
import ( import (
"mayfly-go/internal/msg/api" "mayfly-go/internal/msg/api"
"mayfly-go/internal/msg/application" "mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -10,9 +10,9 @@ import (
func InitMsgRouter(router *gin.RouterGroup) { func InitMsgRouter(router *gin.RouterGroup) {
msg := router.Group("msgs") msg := router.Group("msgs")
a := &api.Msg{
MsgApp: application.GetMsgApp(), a := new(api.Msg)
} ioc.Inject(a)
req.NewGet("/self", a.GetMsgs).Group(msg) req.NewGet("/self", a.GetMsgs).Group(msg)
} }

View File

@@ -1,6 +1,8 @@
package router package router
import "github.com/gin-gonic/gin" import (
"github.com/gin-gonic/gin"
)
func Init(router *gin.RouterGroup) { func Init(router *gin.RouterGroup) {
InitMsgRouter(router) InitMsgRouter(router)

View File

@@ -64,7 +64,7 @@ func (r *Redis) Hset(rc *req.Ctx) {
rc.ResData = res rc.ResData = res
} }
func (r *Redis) SetHashValue(rc *req.Ctx) { func (r *Redis) SaveHashValue(rc *req.Ctx) {
g := rc.GinCtx g := rc.GinCtx
hashValue := new(form.HashValue) hashValue := new(form.HashValue)
ginx.BindJsonAndValid(g, hashValue) ginx.BindJsonAndValid(g, hashValue)

View File

@@ -54,7 +54,7 @@ func (r *Redis) SaveListValue(rc *req.Ctx) {
} }
} }
func (r *Redis) SetListValue(rc *req.Ctx) { func (r *Redis) Lset(rc *req.Ctx) {
g := rc.GinCtx g := rc.GinCtx
listSetValue := new(form.ListSetValue) listSetValue := new(form.ListSetValue)
ginx.BindJsonAndValid(g, listSetValue) ginx.BindJsonAndValid(g, listSetValue)

View File

@@ -24,8 +24,8 @@ import (
) )
type Redis struct { type Redis struct {
RedisApp application.Redis RedisApp application.Redis `inject:""`
TagApp tagapp.TagTree TagApp tagapp.TagTree `inject:"TagTreeApp"`
} }
func (r *Redis) RedisList(rc *req.Ctx) { func (r *Redis) RedisList(rc *req.Ctx) {

View File

@@ -17,7 +17,7 @@ func (r *Redis) GetSetValue(rc *req.Ctx) {
rc.ResData = res rc.ResData = res
} }
func (r *Redis) SetSetValue(rc *req.Ctx) { func (r *Redis) SaveSetValue(rc *req.Ctx) {
g := rc.GinCtx g := rc.GinCtx
keyvalue := new(form.SetValue) keyvalue := new(form.SetValue)
ginx.BindJsonAndValid(g, keyvalue) ginx.BindJsonAndValid(g, keyvalue)

View File

@@ -17,7 +17,7 @@ func (r *Redis) GetStringValue(rc *req.Ctx) {
rc.ResData = str rc.ResData = str
} }
func (r *Redis) SetStringValue(rc *req.Ctx) { func (r *Redis) SaveStringValue(rc *req.Ctx) {
g := rc.GinCtx g := rc.GinCtx
keyValue := new(form.StringValue) keyValue := new(form.StringValue)
ginx.BindJsonAndValid(g, keyValue) ginx.BindJsonAndValid(g, keyValue)

View File

@@ -2,13 +2,15 @@ package application
import ( import (
"mayfly-go/internal/redis/infrastructure/persistence" "mayfly-go/internal/redis/infrastructure/persistence"
tagapp "mayfly-go/internal/tag/application" "mayfly-go/pkg/ioc"
) )
var ( func init() {
redisApp Redis = newRedisApp(persistence.GetRedisRepo(), tagapp.GetTagTreeApp()) persistence.Init()
)
ioc.Register(new(redisAppImpl), ioc.WithComponentName("RedisApp"))
}
func GetRedisApp() Redis { func GetRedisApp() Redis {
return redisApp return ioc.Get[Redis]("RedisApp")
} }

View File

@@ -35,18 +35,15 @@ type Redis interface {
GetRedisConn(id uint64, db int) (*rdm.RedisConn, error) GetRedisConn(id uint64, db int) (*rdm.RedisConn, error)
} }
func newRedisApp(redisRepo repository.Redis, tagApp tagapp.TagTree) Redis {
app := &redisAppImpl{
tagApp: tagApp,
}
app.Repo = redisRepo
return app
}
type redisAppImpl struct { type redisAppImpl struct {
base.AppImpl[*entity.Redis, repository.Redis] base.AppImpl[*entity.Redis, repository.Redis]
tagApp tagapp.TagTree TagApp tagapp.TagTree `inject:"TagTreeApp"`
}
// 注入RedisRepo
func (r *redisAppImpl) InjectRedisRepo(repo repository.Redis) {
r.Repo = repo
} }
// 分页获取redis列表 // 分页获取redis列表
@@ -90,7 +87,7 @@ func (r *redisAppImpl) SaveRedis(ctx context.Context, re *entity.Redis, tagIds .
return r.Tx(ctx, func(ctx context.Context) error { return r.Tx(ctx, func(ctx context.Context) error {
return r.Insert(ctx, re) return r.Insert(ctx, re)
}, func(ctx context.Context) error { }, func(ctx context.Context) error {
return r.tagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeRedis, tagIds) return r.TagApp.RelateResource(ctx, resouceCode, consts.TagResourceTypeRedis, tagIds)
}) })
} }
@@ -116,7 +113,7 @@ func (r *redisAppImpl) SaveRedis(ctx context.Context, re *entity.Redis, tagIds .
return r.Tx(ctx, func(ctx context.Context) error { return r.Tx(ctx, func(ctx context.Context) error {
return r.UpdateById(ctx, re) return r.UpdateById(ctx, re)
}, func(ctx context.Context) error { }, func(ctx context.Context) error {
return r.tagApp.RelateResource(ctx, oldRedis.Code, consts.TagResourceTypeRedis, tagIds) return r.TagApp.RelateResource(ctx, oldRedis.Code, consts.TagResourceTypeRedis, tagIds)
}) })
} }
@@ -136,7 +133,7 @@ func (r *redisAppImpl) Delete(ctx context.Context, id uint64) error {
return r.DeleteById(ctx, id) return r.DeleteById(ctx, id)
}, func(ctx context.Context) error { }, func(ctx context.Context) error {
var tagIds []uint64 var tagIds []uint64
return r.tagApp.RelateResource(ctx, re.Code, consts.TagResourceTypeRedis, tagIds) return r.TagApp.RelateResource(ctx, re.Code, consts.TagResourceTypeRedis, tagIds)
}) })
} }
@@ -151,6 +148,6 @@ func (r *redisAppImpl) GetRedisConn(id uint64, db int) (*rdm.RedisConn, error) {
if err := re.PwdDecrypt(); err != nil { if err := re.PwdDecrypt(); err != nil {
return nil, errorx.NewBiz(err.Error()) return nil, errorx.NewBiz(err.Error())
} }
return re.ToRedisInfo(db, r.tagApp.ListTagPathByResource(consts.TagResourceTypeRedis, re.Code)...), nil return re.ToRedisInfo(db, r.TagApp.ListTagPathByResource(consts.TagResourceTypeRedis, re.Code)...), nil
}) })
} }

View File

@@ -1,11 +1,14 @@
package persistence package persistence
import "mayfly-go/internal/redis/domain/repository" import (
"mayfly-go/internal/redis/domain/repository"
var ( "mayfly-go/pkg/ioc"
redisRepo repository.Redis = newRedisRepo()
) )
func GetRedisRepo() repository.Redis { func Init() {
return redisRepo ioc.Register(newRedisRepo(), ioc.WithComponentName("RedisRepo"))
}
func GetRedisRepo() repository.Redis {
return ioc.Get[repository.Redis]("RedisRepo")
} }

View File

@@ -2,8 +2,8 @@ package router
import ( import (
"mayfly-go/internal/redis/api" "mayfly-go/internal/redis/api"
"mayfly-go/internal/redis/application" "mayfly-go/pkg/biz"
tagapp "mayfly-go/internal/tag/application" "mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -12,10 +12,8 @@ import (
func InitRedisRouter(router *gin.RouterGroup) { func InitRedisRouter(router *gin.RouterGroup) {
redis := router.Group("redis") redis := router.Group("redis")
rs := &api.Redis{ rs := new(api.Redis)
RedisApp: application.GetRedisApp(), biz.ErrIsNil(ioc.Inject(rs))
TagApp: tagapp.GetTagTreeApp(),
}
// 保存数据权限 // 保存数据权限
saveDataP := req.NewPermission("redis:data:save") saveDataP := req.NewPermission("redis:data:save")
@@ -61,7 +59,7 @@ func InitRedisRouter(router *gin.RouterGroup) {
req.NewGet(":id/:db/string-value", rs.GetStringValue), req.NewGet(":id/:db/string-value", rs.GetStringValue),
// 设置string类型值 // 设置string类型值
req.NewPost(":id/:db/string-value", rs.SetStringValue).Log(req.NewLogSave("redis-setString")).RequiredPermission(saveDataP), req.NewPost(":id/:db/string-value", rs.SaveStringValue).Log(req.NewLogSave("redis-setString")).RequiredPermission(saveDataP),
// ———————————————— hash操作 ———————————————— // ———————————————— hash操作 ————————————————
req.NewGet(":id/:db/hscan", rs.Hscan), req.NewGet(":id/:db/hscan", rs.Hscan),
@@ -73,12 +71,12 @@ func InitRedisRouter(router *gin.RouterGroup) {
req.NewDelete(":id/:db/hdel", rs.Hdel).Log(req.NewLogSave("redis-hdel")).RequiredPermission(deleteDataP), req.NewDelete(":id/:db/hdel", rs.Hdel).Log(req.NewLogSave("redis-hdel")).RequiredPermission(deleteDataP),
// 设置hash类型值 // 设置hash类型值
req.NewPost(":id/:db/hash-value", rs.SetHashValue).Log(req.NewLogSave("redis-setHashValue")).RequiredPermission(saveDataP), req.NewPost(":id/:db/hash-value", rs.SaveHashValue).Log(req.NewLogSave("redis-setHashValue")).RequiredPermission(saveDataP),
// --------------- set操作 ---------------- // --------------- set操作 ----------------
req.NewGet(":id/:db/set-value", rs.GetSetValue), req.NewGet(":id/:db/set-value", rs.GetSetValue),
req.NewPost(":id/:db/set-value", rs.SetSetValue).RequiredPermission(saveDataP), req.NewPost(":id/:db/set-value", rs.SaveSetValue).RequiredPermission(saveDataP),
req.NewGet(":id/:db/scard", rs.Scard), req.NewGet(":id/:db/scard", rs.Scard),
@@ -93,7 +91,7 @@ func InitRedisRouter(router *gin.RouterGroup) {
req.NewPost(":id/:db/list-value", rs.SaveListValue).RequiredPermission(saveDataP), req.NewPost(":id/:db/list-value", rs.SaveListValue).RequiredPermission(saveDataP),
req.NewPost(":id/:db/list-value/lset", rs.SetListValue).RequiredPermission(saveDataP), req.NewPost(":id/:db/list-value/lset", rs.Lset).RequiredPermission(saveDataP),
req.NewPost(":id/:db/lrem", rs.Lrem).RequiredPermission(deleteDataP), req.NewPost(":id/:db/lrem", rs.Lrem).RequiredPermission(deleteDataP),

View File

@@ -27,11 +27,11 @@ const (
) )
type Account struct { type Account struct {
AccountApp application.Account AccountApp application.Account `inject:""`
ResourceApp application.Resource ResourceApp application.Resource `inject:""`
RoleApp application.Role RoleApp application.Role `inject:""`
MsgApp msgapp.Msg MsgApp msgapp.Msg `inject:""`
ConfigApp application.Config ConfigApp application.Config `inject:""`
} }
// 获取当前登录用户的菜单与权限码 // 获取当前登录用户的菜单与权限码

View File

@@ -10,7 +10,7 @@ import (
) )
type Config struct { type Config struct {
ConfigApp application.Config ConfigApp application.Config `inject:""`
} }
func (c *Config) Configs(rc *req.Ctx) { func (c *Config) Configs(rc *req.Ctx) {

View File

@@ -13,7 +13,7 @@ import (
) )
type Resource struct { type Resource struct {
ResourceApp application.Resource ResourceApp application.Resource `inject:""`
} }
func (r *Resource) GetAllResourceTree(rc *req.Ctx) { func (r *Resource) GetAllResourceTree(rc *req.Ctx) {

View File

@@ -15,8 +15,8 @@ import (
) )
type Role struct { type Role struct {
RoleApp application.Role RoleApp application.Role `inject:""`
ResourceApp application.Resource ResourceApp application.Resource `inject:""`
} }
func (r *Role) Roles(rc *req.Ctx) { func (r *Role) Roles(rc *req.Ctx) {

View File

@@ -9,7 +9,7 @@ import (
) )
type Syslog struct { type Syslog struct {
SyslogApp application.Syslog SyslogApp application.Syslog `inject:""`
} }
func (r *Syslog) Syslogs(rc *req.Ctx) { func (r *Syslog) Syslogs(rc *req.Ctx) {

View File

@@ -25,14 +25,15 @@ type Account interface {
Delete(ctx context.Context, id uint64) error Delete(ctx context.Context, id uint64) error
} }
func newAccountApp(accountRepo repository.Account) Account {
return &accountAppImpl{base.AppImpl[*entity.Account, repository.Account]{Repo: accountRepo}}
}
type accountAppImpl struct { type accountAppImpl struct {
base.AppImpl[*entity.Account, repository.Account] base.AppImpl[*entity.Account, repository.Account]
} }
// 注入AccountRepo
func (a *accountAppImpl) InjectAccountRepo(repo repository.Account) {
a.Repo = repo
}
func (a *accountAppImpl) GetPageList(condition *entity.Account, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (a *accountAppImpl) GetPageList(condition *entity.Account, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return a.GetRepo().GetPageList(condition, pageParam, toEntity) return a.GetRepo().GetPageList(condition, pageParam, toEntity)
} }

View File

@@ -2,32 +2,35 @@ package application
import ( import (
"mayfly-go/internal/sys/infrastructure/persistence" "mayfly-go/internal/sys/infrastructure/persistence"
"mayfly-go/pkg/ioc"
) )
var ( func init() {
accountApp = newAccountApp(persistence.GetAccountRepo()) persistence.Init()
configApp = newConfigApp(persistence.GetConfigRepo())
resourceApp = newResourceApp(persistence.GetResourceRepo()) ioc.Register(new(accountAppImpl), ioc.WithComponentName("AccountApp"))
roleApp = newRoleApp(persistence.GetRoleRepo(), persistence.GetAccountRoleRepo()) ioc.Register(new(roleAppImpl), ioc.WithComponentName("RoleApp"))
syslogApp = newSyslogApp(persistence.GetSyslogRepo()) ioc.Register(new(configAppImpl), ioc.WithComponentName("ConfigApp"))
) ioc.Register(new(resourceAppImpl), ioc.WithComponentName("ResourceApp"))
ioc.Register(new(syslogAppImpl), ioc.WithComponentName("SyslogApp"))
}
func GetAccountApp() Account { func GetAccountApp() Account {
return accountApp return ioc.Get[Account]("AccountApp")
} }
func GetConfigApp() Config { func GetConfigApp() Config {
return configApp return ioc.Get[Config]("ConfigApp")
} }
func GetResourceApp() Resource { func GetResourceApp() Resource {
return resourceApp return ioc.Get[Resource]("ResourceApp")
} }
func GetRoleApp() Role { func GetRoleApp() Role {
return roleApp return ioc.Get[Role]("RoleApp")
} }
func GetSyslogApp() Syslog { func GetSyslogApp() Syslog {
return syslogApp return ioc.Get[Syslog]("SyslogApp")
} }

View File

@@ -27,17 +27,14 @@ type Config interface {
GetConfig(key string) *entity.Config GetConfig(key string) *entity.Config
} }
func newConfigApp(configRepo repository.Config) Config {
configApp := new(configAppImpl)
configApp.Repo = configRepo
return configApp
// return &configAppImpl{base.AppImpl[*entity.Config, repository.Config]{Repo: configRepo}}
}
type configAppImpl struct { type configAppImpl struct {
base.AppImpl[*entity.Config, repository.Config] base.AppImpl[*entity.Config, repository.Config]
} }
func (a *configAppImpl) InjectConfigRepo(repo repository.Config) {
a.Repo = repo
}
func (a *configAppImpl) GetPageList(condition *entity.Config, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (a *configAppImpl) GetPageList(condition *entity.Config, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return a.GetRepo().GetPageList(condition, pageParam, toEntity) return a.GetRepo().GetPageList(condition, pageParam, toEntity)
} }

View File

@@ -27,16 +27,15 @@ type Resource interface {
GetAccountResources(accountId uint64, toEntity any) error GetAccountResources(accountId uint64, toEntity any) error
} }
func newResourceApp(resourceRepo repository.Resource) Resource {
return &resourceAppImpl{
base.AppImpl[*entity.Resource, repository.Resource]{Repo: resourceRepo},
}
}
type resourceAppImpl struct { type resourceAppImpl struct {
base.AppImpl[*entity.Resource, repository.Resource] base.AppImpl[*entity.Resource, repository.Resource]
} }
// 注入ResourceRepo
func (r *resourceAppImpl) InjectResourceRepo(repo repository.Resource) {
r.Repo = repo
}
func (r *resourceAppImpl) Save(ctx context.Context, resource *entity.Resource) error { func (r *resourceAppImpl) Save(ctx context.Context, resource *entity.Resource) error {
// 更新操作 // 更新操作
if resource.Id != 0 { if resource.Id != 0 {

View File

@@ -41,24 +41,17 @@ type Role interface {
GetRoleAccountPage(condition *entity.RoleAccountQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) GetRoleAccountPage(condition *entity.RoleAccountQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error)
} }
func newRoleApp(roleRepo repository.Role, accountRoleRepo repository.AccountRole) Role {
return &roleAppImpl{
roleRepo: roleRepo,
accountRoleRepo: accountRoleRepo,
}
}
type roleAppImpl struct { type roleAppImpl struct {
roleRepo repository.Role RoleRepo repository.Role `inject:""`
accountRoleRepo repository.AccountRole AccountRoleRepo repository.AccountRole `inject:""`
} }
func (m *roleAppImpl) GetPageList(condition *entity.RoleQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (m *roleAppImpl) GetPageList(condition *entity.RoleQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return m.roleRepo.GetPageList(condition, pageParam, toEntity, orderBy...) return m.RoleRepo.GetPageList(condition, pageParam, toEntity, orderBy...)
} }
func (m *roleAppImpl) ListByQuery(condition *entity.RoleQuery) ([]*entity.Role, error) { func (m *roleAppImpl) ListByQuery(condition *entity.RoleQuery) ([]*entity.Role, error) {
return m.roleRepo.ListByQuery(condition) return m.RoleRepo.ListByQuery(condition)
} }
func (m *roleAppImpl) SaveRole(ctx context.Context, role *entity.Role) error { func (m *roleAppImpl) SaveRole(ctx context.Context, role *entity.Role) error {
@@ -69,14 +62,14 @@ func (m *roleAppImpl) SaveRole(ctx context.Context, role *entity.Role) error {
} }
role.Status = 1 role.Status = 1
return m.roleRepo.Insert(ctx, role) return m.RoleRepo.Insert(ctx, role)
} }
func (m *roleAppImpl) DeleteRole(ctx context.Context, id uint64) error { func (m *roleAppImpl) DeleteRole(ctx context.Context, id uint64) error {
// 删除角色与资源账号的关联关系 // 删除角色与资源账号的关联关系
return gormx.Tx( return gormx.Tx(
func(db *gorm.DB) error { func(db *gorm.DB) error {
return m.roleRepo.DeleteByIdWithDb(ctx, db, id) return m.RoleRepo.DeleteByIdWithDb(ctx, db, id)
}, },
func(db *gorm.DB) error { func(db *gorm.DB) error {
return gormx.DeleteByWithDb(db, &entity.RoleResource{RoleId: id}) return gormx.DeleteByWithDb(db, &entity.RoleResource{RoleId: id})
@@ -88,11 +81,11 @@ func (m *roleAppImpl) DeleteRole(ctx context.Context, id uint64) error {
} }
func (m *roleAppImpl) GetRoleResourceIds(roleId uint64) []uint64 { func (m *roleAppImpl) GetRoleResourceIds(roleId uint64) []uint64 {
return m.roleRepo.GetRoleResourceIds(roleId) return m.RoleRepo.GetRoleResourceIds(roleId)
} }
func (m *roleAppImpl) GetRoleResources(roleId uint64, toEntity any) { func (m *roleAppImpl) GetRoleResources(roleId uint64, toEntity any) {
m.roleRepo.GetRoleResources(roleId, toEntity) m.RoleRepo.GetRoleResources(roleId, toEntity)
} }
func (m *roleAppImpl) SaveRoleResource(ctx context.Context, roleId uint64, resourceIds []uint64) { func (m *roleAppImpl) SaveRoleResource(ctx context.Context, roleId uint64, resourceIds []uint64) {
@@ -112,20 +105,20 @@ func (m *roleAppImpl) SaveRoleResource(ctx context.Context, roleId uint64, resou
rr.IsDeleted = undeleted rr.IsDeleted = undeleted
addVals = append(addVals, rr) addVals = append(addVals, rr)
} }
m.roleRepo.SaveRoleResource(addVals) m.RoleRepo.SaveRoleResource(addVals)
for _, v := range delIds { for _, v := range delIds {
m.roleRepo.DeleteRoleResource(roleId, v) m.RoleRepo.DeleteRoleResource(roleId, v)
} }
} }
func (m *roleAppImpl) RelateAccountRole(ctx context.Context, accountId, roleId uint64, relateType consts.AccountRoleRelateType) error { func (m *roleAppImpl) RelateAccountRole(ctx context.Context, accountId, roleId uint64, relateType consts.AccountRoleRelateType) error {
accountRole := &entity.AccountRole{AccountId: accountId, RoleId: roleId} accountRole := &entity.AccountRole{AccountId: accountId, RoleId: roleId}
if relateType == consts.AccountRoleUnbind { if relateType == consts.AccountRoleUnbind {
return m.accountRoleRepo.DeleteByCond(ctx, accountRole) return m.AccountRoleRepo.DeleteByCond(ctx, accountRole)
} }
err := m.accountRoleRepo.GetBy(accountRole) err := m.AccountRoleRepo.GetBy(accountRole)
if err == nil { if err == nil {
return errorx.NewBiz("该用户已拥有该权限") return errorx.NewBiz("该用户已拥有该权限")
} }
@@ -135,15 +128,15 @@ func (m *roleAppImpl) RelateAccountRole(ctx context.Context, accountId, roleId u
accountRole.Creator = la.Username accountRole.Creator = la.Username
accountRole.CreatorId = la.Id accountRole.CreatorId = la.Id
accountRole.CreateTime = &createTime accountRole.CreateTime = &createTime
return m.accountRoleRepo.Insert(ctx, accountRole) return m.AccountRoleRepo.Insert(ctx, accountRole)
} }
func (m *roleAppImpl) GetAccountRoles(accountId uint64) ([]*entity.AccountRole, error) { func (m *roleAppImpl) GetAccountRoles(accountId uint64) ([]*entity.AccountRole, error) {
var res []*entity.AccountRole var res []*entity.AccountRole
err := m.accountRoleRepo.ListByCond(&entity.AccountRole{AccountId: accountId}, &res) err := m.AccountRoleRepo.ListByCond(&entity.AccountRole{AccountId: accountId}, &res)
return res, err return res, err
} }
func (m *roleAppImpl) GetRoleAccountPage(condition *entity.RoleAccountQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (m *roleAppImpl) GetRoleAccountPage(condition *entity.RoleAccountQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return m.accountRoleRepo.GetPageList(condition, pageParam, toEntity, orderBy...) return m.AccountRoleRepo.GetPageList(condition, pageParam, toEntity, orderBy...)
} }

View File

@@ -20,18 +20,12 @@ type Syslog interface {
SaveFromReq(req *req.Ctx) SaveFromReq(req *req.Ctx)
} }
func newSyslogApp(syslogRepo repository.Syslog) Syslog {
return &syslogAppImpl{
syslogRepo: syslogRepo,
}
}
type syslogAppImpl struct { type syslogAppImpl struct {
syslogRepo repository.Syslog SyslogRepo repository.Syslog `inject:""`
} }
func (m *syslogAppImpl) GetPageList(condition *entity.SysLogQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (m *syslogAppImpl) GetPageList(condition *entity.SysLogQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return m.syslogRepo.GetPageList(condition, pageParam, toEntity, orderBy...) return m.SyslogRepo.GetPageList(condition, pageParam, toEntity, orderBy...)
} }
func (m *syslogAppImpl) SaveFromReq(req *req.Ctx) { func (m *syslogAppImpl) SaveFromReq(req *req.Ctx) {
@@ -76,5 +70,5 @@ func (m *syslogAppImpl) SaveFromReq(req *req.Ctx) {
syslog.Type = entity.SyslogTypeNorman syslog.Type = entity.SyslogTypeNorman
} }
m.syslogRepo.Insert(req.MetaCtx, syslog) m.SyslogRepo.Insert(req.MetaCtx, syslog)
} }

View File

@@ -8,15 +8,15 @@ import (
"mayfly-go/pkg/model" "mayfly-go/pkg/model"
) )
type accountRepoImpl struct { type AccountRepoImpl struct {
base.RepoImpl[*entity.Account] base.RepoImpl[*entity.Account]
} }
func newAccountRepo() repository.Account { func newAccountRepo() repository.Account {
return &accountRepoImpl{base.RepoImpl[*entity.Account]{M: new(entity.Account)}} return &AccountRepoImpl{base.RepoImpl[*entity.Account]{M: new(entity.Account)}}
} }
func (m *accountRepoImpl) GetPageList(condition *entity.Account, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (m *AccountRepoImpl) GetPageList(condition *entity.Account, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
qd := gormx.NewQuery(new(entity.Account)). qd := gormx.NewQuery(new(entity.Account)).
Like("name", condition.Name). Like("name", condition.Name).
Like("username", condition.Username) Like("username", condition.Username)

View File

@@ -1,36 +1,39 @@
package persistence package persistence
import "mayfly-go/internal/sys/domain/repository" import (
"mayfly-go/internal/sys/domain/repository"
var ( "mayfly-go/pkg/ioc"
accountRepo = newAccountRepo()
configRepo = newConfigRepo()
resourceRepo = newResourceRepo()
roleRepo = newRoleRepo()
accountRoleRepo = newAccountRoleRepo()
syslogRepo = newSyslogRepo()
) )
func Init() {
ioc.Register(newAccountRepo(), ioc.WithComponentName("AccountRepo"))
ioc.Register(newRoleRepo(), ioc.WithComponentName("RoleRepo"))
ioc.Register(newAccountRoleRepo(), ioc.WithComponentName("AccountRoleRepo"))
ioc.Register(newResourceRepo(), ioc.WithComponentName("ResourceRepo"))
ioc.Register(newConfigRepo(), ioc.WithComponentName("ConfigRepo"))
ioc.Register(newSyslogRepo(), ioc.WithComponentName("SyslogRepo"))
}
func GetAccountRepo() repository.Account { func GetAccountRepo() repository.Account {
return accountRepo return ioc.Get[repository.Account]("AccountRepo")
} }
func GetConfigRepo() repository.Config { func GetConfigRepo() repository.Config {
return configRepo return ioc.Get[repository.Config]("ConfigRepo")
} }
func GetResourceRepo() repository.Resource { func GetResourceRepo() repository.Resource {
return resourceRepo return ioc.Get[repository.Resource]("ResourceRepo")
} }
func GetRoleRepo() repository.Role { func GetRoleRepo() repository.Role {
return roleRepo return ioc.Get[repository.Role]("RoleRepo")
} }
func GetAccountRoleRepo() repository.AccountRole { func GetAccountRoleRepo() repository.AccountRole {
return accountRoleRepo return ioc.Get[repository.AccountRole]("AccountRoleRepo")
} }
func GetSyslogRepo() repository.Syslog { func GetSyslogRepo() repository.Syslog {
return syslogRepo return ioc.Get[repository.Syslog]("SyslogRepo")
} }

View File

@@ -1,9 +1,9 @@
package router package router
import ( import (
msgapp "mayfly-go/internal/msg/application"
"mayfly-go/internal/sys/api" "mayfly-go/internal/sys/api"
"mayfly-go/internal/sys/application" "mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
@@ -11,13 +11,8 @@ import (
func InitAccountRouter(router *gin.RouterGroup) { func InitAccountRouter(router *gin.RouterGroup) {
account := router.Group("sys/accounts") account := router.Group("sys/accounts")
a := &api.Account{ a := new(api.Account)
AccountApp: application.GetAccountApp(), biz.ErrIsNil(ioc.Inject(a))
ResourceApp: application.GetResourceApp(),
RoleApp: application.GetRoleApp(),
MsgApp: msgapp.GetMsgApp(),
ConfigApp: application.GetConfigApp(),
}
addAccountPermission := req.NewPermission("account:add") addAccountPermission := req.NewPermission("account:add")

View File

@@ -2,15 +2,17 @@ package router
import ( import (
"mayfly-go/internal/sys/api" "mayfly-go/internal/sys/api"
"mayfly-go/internal/sys/application" "mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func InitSysConfigRouter(router *gin.RouterGroup) { func InitSysConfigRouter(router *gin.RouterGroup) {
r := &api.Config{ConfigApp: application.GetConfigApp()}
configG := router.Group("sys/configs") configG := router.Group("sys/configs")
r := new(api.Config)
biz.ErrIsNil(ioc.Inject(r))
baseP := req.NewPermission("config:base") baseP := req.NewPermission("config:base")

View File

@@ -2,15 +2,17 @@ package router
import ( import (
"mayfly-go/internal/sys/api" "mayfly-go/internal/sys/api"
"mayfly-go/internal/sys/application" "mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func InitResourceRouter(router *gin.RouterGroup) { func InitResourceRouter(router *gin.RouterGroup) {
r := &api.Resource{ResourceApp: application.GetResourceApp()}
rg := router.Group("sys/resources") rg := router.Group("sys/resources")
r := new(api.Resource)
biz.ErrIsNil(ioc.Inject(r))
reqs := [...]*req.Conf{ reqs := [...]*req.Conf{
req.NewGet("", r.GetAllResourceTree), req.NewGet("", r.GetAllResourceTree),

View File

@@ -2,18 +2,17 @@ package router
import ( import (
"mayfly-go/internal/sys/api" "mayfly-go/internal/sys/api"
"mayfly-go/internal/sys/application" "mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func InitRoleRouter(router *gin.RouterGroup) { func InitRoleRouter(router *gin.RouterGroup) {
r := &api.Role{
RoleApp: application.GetRoleApp(),
ResourceApp: application.GetResourceApp(),
}
rg := router.Group("sys/roles") rg := router.Group("sys/roles")
r := new(api.Role)
biz.ErrIsNil(ioc.Inject(r))
reqs := [...]*req.Conf{ reqs := [...]*req.Conf{
req.NewGet("", r.Roles), req.NewGet("", r.Roles),

View File

@@ -1,6 +1,8 @@
package router package router
import "github.com/gin-gonic/gin" import (
"github.com/gin-gonic/gin"
)
func Init(router *gin.RouterGroup) { func Init(router *gin.RouterGroup) {
InitCaptchaRouter(router) InitCaptchaRouter(router)

View File

@@ -2,17 +2,17 @@ package router
import ( import (
"mayfly-go/internal/sys/api" "mayfly-go/internal/sys/api"
"mayfly-go/internal/sys/application" "mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func InitSyslogRouter(router *gin.RouterGroup) { func InitSyslogRouter(router *gin.RouterGroup) {
s := &api.Syslog{
SyslogApp: application.GetSyslogApp(),
}
sysG := router.Group("syslogs") sysG := router.Group("syslogs")
s := new(api.Syslog)
biz.ErrIsNil(ioc.Inject(s))
req.NewGet("", s.Syslogs).Group(sysG) req.NewGet("", s.Syslogs).Group(sysG)
} }

View File

@@ -2,13 +2,16 @@ package router
import ( import (
"mayfly-go/internal/sys/api" "mayfly-go/internal/sys/api"
"mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func InitSystemRouter(router *gin.RouterGroup) { func InitSystemRouter(router *gin.RouterGroup) {
s := &api.System{}
sys := router.Group("sysmsg") sys := router.Group("sysmsg")
s := new(api.System)
biz.ErrIsNil(ioc.Inject(s))
{ {
sys.GET("", s.ConnectWs) sys.GET("", s.ConnectWs)

View File

@@ -17,8 +17,8 @@ import (
) )
type TagTree struct { type TagTree struct {
TagTreeApp application.TagTree TagTreeApp application.TagTree `inject:""`
TagResourceApp application.TagResource TagResourceApp application.TagResource `inject:""`
} }
func (p *TagTree) GetTagTree(rc *req.Ctx) { func (p *TagTree) GetTagTree(rc *req.Ctx) {

View File

@@ -17,9 +17,9 @@ import (
) )
type Team struct { type Team struct {
TeamApp application.Team TeamApp application.Team `inject:""`
TagApp application.TagTree TagTreeApp application.TagTree `inject:""`
AccountApp sys_applicaiton.Account AccountApp sys_applicaiton.Account `inject:""`
} }
func (p *Team) GetTeams(rc *req.Ctx) { func (p *Team) GetTeams(rc *req.Ctx) {
@@ -131,7 +131,7 @@ func (p *Team) SaveTags(rc *req.Ctx) {
for _, v := range addIds { for _, v := range addIds {
tagId := v tagId := v
tag, err := p.TagApp.GetById(new(entity.TagTree), tagId) tag, err := p.TagTreeApp.GetById(new(entity.TagTree), tagId)
biz.ErrIsNil(err, "存在非法标签id") biz.ErrIsNil(err, "存在非法标签id")
ptt := &entity.TagTreeTeam{TeamId: teamId, TagId: tagId, TagPath: tag.CodePath} ptt := &entity.TagTreeTeam{TeamId: teamId, TagId: tagId, TagPath: tag.CodePath}

View File

@@ -2,32 +2,25 @@ package application
import ( import (
"mayfly-go/internal/tag/infrastructure/persistence" "mayfly-go/internal/tag/infrastructure/persistence"
"mayfly-go/pkg/ioc"
) )
var ( func init() {
tagTreeApp TagTree = newTagTreeApp( persistence.Init()
persistence.GetTagTreeRepo(),
GetTagResourceApp(),
persistence.GetTagTreeTeamRepo(),
)
teamApp Team = newTeamApp( ioc.Register(new(tagTreeAppImpl), ioc.WithComponentName("TagTreeApp"))
persistence.GetTeamRepo(), ioc.Register(new(teamAppImpl), ioc.WithComponentName("TeamApp"))
persistence.GetTeamMemberRepo(), ioc.Register(new(tagResourceAppImpl), ioc.WithComponentName("TagResourceApp"))
persistence.GetTagTreeTeamRepo(), }
)
tagResourceApp TagResource = newTagResourceApp(persistence.GetTagResourceRepo())
)
func GetTagTreeApp() TagTree { func GetTagTreeApp() TagTree {
return tagTreeApp return ioc.Get[TagTree]("TagTreeApp")
} }
func GetTeamApp() Team { func GetTeamApp() Team {
return teamApp return ioc.Get[Team]("TeamApp")
} }
func GetTagResourceApp() TagResource { func GetTagResourceApp() TagResource {
return tagResourceApp return ioc.Get[TagResource]("TagResourceApp")
} }

View File

@@ -12,16 +12,15 @@ type TagResource interface {
ListByQuery(condition *entity.TagResourceQuery, toEntity any) ListByQuery(condition *entity.TagResourceQuery, toEntity any)
} }
func newTagResourceApp(tagResourceRepo repository.TagResource) TagResource {
tagResourceApp := &tagResourceAppImpl{}
tagResourceApp.Repo = tagResourceRepo
return tagResourceApp
}
type tagResourceAppImpl struct { type tagResourceAppImpl struct {
base.AppImpl[*entity.TagResource, repository.TagResource] base.AppImpl[*entity.TagResource, repository.TagResource]
} }
// 注入TagResourceRepo
func (tr *tagResourceAppImpl) InjectTagResourceRepo(repo repository.TagResource) {
tr.Repo = repo
}
func (tr *tagResourceAppImpl) ListByQuery(condition *entity.TagResourceQuery, toEntity any) { func (tr *tagResourceAppImpl) ListByQuery(condition *entity.TagResourceQuery, toEntity any) {
tr.Repo.SelectByCondition(condition, toEntity) tr.Repo.SelectByCondition(condition, toEntity)
} }

View File

@@ -51,23 +51,16 @@ type TagTree interface {
CanAccess(accountId uint64, tagPath ...string) error CanAccess(accountId uint64, tagPath ...string) error
} }
func newTagTreeApp(tagTreeRepo repository.TagTree,
tagResourceApp TagResource,
tagTreeTeamRepo repository.TagTreeTeam,
) TagTree {
tagTreeApp := &tagTreeAppImpl{
tagTreeTeamRepo: tagTreeTeamRepo,
tagResourceApp: tagResourceApp,
}
tagTreeApp.Repo = tagTreeRepo
return tagTreeApp
}
type tagTreeAppImpl struct { type tagTreeAppImpl struct {
base.AppImpl[*entity.TagTree, repository.TagTree] base.AppImpl[*entity.TagTree, repository.TagTree]
tagTreeTeamRepo repository.TagTreeTeam TagTreeTeamRepo repository.TagTreeTeam `inject:""`
tagResourceApp TagResource TagResourceApp TagResource `inject:""`
}
// 注入TagTreeRepo
func (p *tagTreeAppImpl) InjectTagTreeRepo(tagTreeRepo repository.TagTree) {
p.Repo = tagTreeRepo
} }
func (p *tagTreeAppImpl) Save(ctx context.Context, tag *entity.TagTree) error { func (p *tagTreeAppImpl) Save(ctx context.Context, tag *entity.TagTree) error {
@@ -82,7 +75,7 @@ func (p *tagTreeAppImpl) Save(ctx context.Context, tag *entity.TagTree) error {
if err != nil { if err != nil {
return errorx.NewBiz("父节点不存在") return errorx.NewBiz("父节点不存在")
} }
if p.tagResourceApp.CountByCond(&entity.TagResource{TagId: tag.Pid}) > 0 { if p.TagResourceApp.CountByCond(&entity.TagResource{TagId: tag.Pid}) > 0 {
return errorx.NewBiz("该父标签已关联资源, 无法添加子标签") return errorx.NewBiz("该父标签已关联资源, 无法添加子标签")
} }
@@ -135,7 +128,7 @@ func (p *tagTreeAppImpl) GetAccountTagResources(accountId uint64, resourceType i
tagResourceQuery.TagPath = tagPath tagResourceQuery.TagPath = tagPath
tagResourceQuery.TagPathLikes = accountTagPaths tagResourceQuery.TagPathLikes = accountTagPaths
p.tagResourceApp.ListByQuery(tagResourceQuery, &tagResources) p.TagResourceApp.ListByQuery(tagResourceQuery, &tagResources)
return tagResources return tagResources
} }
@@ -155,14 +148,14 @@ func (p *tagTreeAppImpl) RelateResource(ctx context.Context, resourceCode string
} }
// 如果tagIds为空数组则为解绑该标签资源关联关系 // 如果tagIds为空数组则为解绑该标签资源关联关系
if len(tagIds) == 0 { if len(tagIds) == 0 {
return p.tagResourceApp.DeleteByCond(ctx, &entity.TagResource{ return p.TagResourceApp.DeleteByCond(ctx, &entity.TagResource{
ResourceCode: resourceCode, ResourceCode: resourceCode,
ResourceType: resourceType, ResourceType: resourceType,
}) })
} }
var oldTagResources []*entity.TagResource var oldTagResources []*entity.TagResource
p.tagResourceApp.ListByQuery(&entity.TagResourceQuery{ResourceType: resourceType, ResourceCode: resourceCode}, &oldTagResources) p.TagResourceApp.ListByQuery(&entity.TagResourceQuery{ResourceType: resourceType, ResourceCode: resourceCode}, &oldTagResources)
var addTagIds, delTagIds []uint64 var addTagIds, delTagIds []uint64
if len(oldTagResources) == 0 { if len(oldTagResources) == 0 {
@@ -188,7 +181,7 @@ func (p *tagTreeAppImpl) RelateResource(ctx context.Context, resourceCode string
TagPath: tag.CodePath, TagPath: tag.CodePath,
}) })
} }
if err := p.tagResourceApp.BatchInsert(ctx, addTagResource); err != nil { if err := p.TagResourceApp.BatchInsert(ctx, addTagResource); err != nil {
return err return err
} }
} }
@@ -196,7 +189,7 @@ func (p *tagTreeAppImpl) RelateResource(ctx context.Context, resourceCode string
if len(delTagIds) > 0 { if len(delTagIds) > 0 {
for _, tagId := range delTagIds { for _, tagId := range delTagIds {
cond := &entity.TagResource{ResourceCode: resourceCode, ResourceType: resourceType, TagId: tagId} cond := &entity.TagResource{ResourceCode: resourceCode, ResourceType: resourceType, TagId: tagId}
if err := p.tagResourceApp.DeleteByCond(ctx, cond); err != nil { if err := p.TagResourceApp.DeleteByCond(ctx, cond); err != nil {
return err return err
} }
} }
@@ -207,7 +200,7 @@ func (p *tagTreeAppImpl) RelateResource(ctx context.Context, resourceCode string
func (p *tagTreeAppImpl) ListTagPathByResource(resourceType int8, resourceCode string) []string { func (p *tagTreeAppImpl) ListTagPathByResource(resourceType int8, resourceCode string) []string {
var trs []*entity.TagResource var trs []*entity.TagResource
p.tagResourceApp.ListByQuery(&entity.TagResourceQuery{ResourceType: resourceType, ResourceCode: resourceCode}, &trs) p.TagResourceApp.ListByQuery(&entity.TagResourceQuery{ResourceType: resourceType, ResourceCode: resourceCode}, &trs)
return collx.ArrayMap(trs, func(tr *entity.TagResource) string { return collx.ArrayMap(trs, func(tr *entity.TagResource) string {
return tr.TagPath return tr.TagPath
}) })
@@ -220,7 +213,7 @@ func (p *tagTreeAppImpl) ListTagByPath(tagPaths ...string) []*entity.TagTree {
} }
func (p *tagTreeAppImpl) ListTagByAccountId(accountId uint64) []string { func (p *tagTreeAppImpl) ListTagByAccountId(accountId uint64) []string {
return p.tagTreeTeamRepo.SelectTagPathsByAccountId(accountId) return p.TagTreeTeamRepo.SelectTagPathsByAccountId(accountId)
} }
func (p *tagTreeAppImpl) CanAccess(accountId uint64, tagPath ...string) error { func (p *tagTreeAppImpl) CanAccess(accountId uint64, tagPath ...string) error {
@@ -250,7 +243,7 @@ func (p *tagTreeAppImpl) Delete(ctx context.Context, id uint64) error {
return errorx.NewBiz("您无权删除该标签") return errorx.NewBiz("您无权删除该标签")
} }
if p.tagResourceApp.CountByCond(&entity.TagResource{TagId: id}) > 0 { if p.TagResourceApp.CountByCond(&entity.TagResource{TagId: id}) > 0 {
return errorx.NewBiz("请先移除该标签关联的资源") return errorx.NewBiz("请先移除该标签关联的资源")
} }
@@ -258,6 +251,6 @@ func (p *tagTreeAppImpl) Delete(ctx context.Context, id uint64) error {
return p.DeleteById(ctx, id) return p.DeleteById(ctx, id)
}, func(ctx context.Context) error { }, func(ctx context.Context) error {
// 删除该标签关联的团队信息 // 删除该标签关联的团队信息
return p.tagTreeTeamRepo.DeleteByCond(ctx, &entity.TagTreeTeam{TagId: id}) return p.TagTreeTeamRepo.DeleteByCond(ctx, &entity.TagTreeTeam{TagId: id})
}) })
} }

View File

@@ -38,44 +38,33 @@ type Team interface {
DeleteTag(tx context.Context, teamId, tagId uint64) error DeleteTag(tx context.Context, teamId, tagId uint64) error
} }
func newTeamApp(teamRepo repository.Team,
teamMemberRepo repository.TeamMember,
tagTreeTeamRepo repository.TagTreeTeam,
) Team {
return &teamAppImpl{
teamRepo: teamRepo,
teamMemberRepo: teamMemberRepo,
tagTreeTeamRepo: tagTreeTeamRepo,
}
}
type teamAppImpl struct { type teamAppImpl struct {
teamRepo repository.Team TeamRepo repository.Team `inject:""`
teamMemberRepo repository.TeamMember TeamMemberRepo repository.TeamMember `inject:""`
tagTreeTeamRepo repository.TagTreeTeam TagTreeTeamRepo repository.TagTreeTeam `inject:""`
} }
func (p *teamAppImpl) GetPageList(condition *entity.TeamQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) { func (p *teamAppImpl) GetPageList(condition *entity.TeamQuery, pageParam *model.PageParam, toEntity any, orderBy ...string) (*model.PageResult[any], error) {
return p.teamRepo.GetPageList(condition, pageParam, toEntity, orderBy...) return p.TeamRepo.GetPageList(condition, pageParam, toEntity, orderBy...)
} }
func (p *teamAppImpl) Save(ctx context.Context, team *entity.Team) error { func (p *teamAppImpl) Save(ctx context.Context, team *entity.Team) error {
if team.Id == 0 { if team.Id == 0 {
return p.teamRepo.Insert(ctx, team) return p.TeamRepo.Insert(ctx, team)
} }
return p.teamRepo.UpdateById(ctx, team) return p.TeamRepo.UpdateById(ctx, team)
} }
func (p *teamAppImpl) Delete(ctx context.Context, id uint64) error { func (p *teamAppImpl) Delete(ctx context.Context, id uint64) error {
return gormx.Tx( return gormx.Tx(
func(db *gorm.DB) error { func(db *gorm.DB) error {
return p.teamRepo.DeleteByIdWithDb(ctx, db, id) return p.TeamRepo.DeleteByIdWithDb(ctx, db, id)
}, },
func(db *gorm.DB) error { func(db *gorm.DB) error {
return p.teamMemberRepo.DeleteByCondWithDb(ctx, db, &entity.TeamMember{TeamId: id}) return p.TeamMemberRepo.DeleteByCondWithDb(ctx, db, &entity.TeamMember{TeamId: id})
}, },
func(db *gorm.DB) error { func(db *gorm.DB) error {
return p.tagTreeTeamRepo.DeleteByCondWithDb(ctx, db, &entity.TagTreeTeam{TeamId: id}) return p.TagTreeTeamRepo.DeleteByCondWithDb(ctx, db, &entity.TagTreeTeam{TeamId: id})
}, },
) )
} }
@@ -83,30 +72,30 @@ func (p *teamAppImpl) Delete(ctx context.Context, id uint64) error {
// --------------- 团队成员相关接口 --------------- // --------------- 团队成员相关接口 ---------------
func (p *teamAppImpl) GetMemberPage(condition *entity.TeamMember, pageParam *model.PageParam, toEntity any) (*model.PageResult[any], error) { func (p *teamAppImpl) GetMemberPage(condition *entity.TeamMember, pageParam *model.PageParam, toEntity any) (*model.PageResult[any], error) {
return p.teamMemberRepo.GetPageList(condition, pageParam, toEntity) return p.TeamMemberRepo.GetPageList(condition, pageParam, toEntity)
} }
// 保存团队成员信息 // 保存团队成员信息
func (p *teamAppImpl) SaveMember(ctx context.Context, teamMember *entity.TeamMember) { func (p *teamAppImpl) SaveMember(ctx context.Context, teamMember *entity.TeamMember) {
teamMember.Id = 0 teamMember.Id = 0
biz.IsTrue(!p.teamMemberRepo.IsExist(teamMember.TeamId, teamMember.AccountId), "该成员已存在") biz.IsTrue(!p.TeamMemberRepo.IsExist(teamMember.TeamId, teamMember.AccountId), "该成员已存在")
p.teamMemberRepo.Insert(ctx, teamMember) p.TeamMemberRepo.Insert(ctx, teamMember)
} }
// 删除团队成员信息 // 删除团队成员信息
func (p *teamAppImpl) DeleteMember(ctx context.Context, teamId, accountId uint64) { func (p *teamAppImpl) DeleteMember(ctx context.Context, teamId, accountId uint64) {
p.teamMemberRepo.DeleteByCond(ctx, &entity.TeamMember{TeamId: teamId, AccountId: accountId}) p.TeamMemberRepo.DeleteByCond(ctx, &entity.TeamMember{TeamId: teamId, AccountId: accountId})
} }
func (p *teamAppImpl) IsExistMember(teamId, accounId uint64) bool { func (p *teamAppImpl) IsExistMember(teamId, accounId uint64) bool {
return p.teamMemberRepo.IsExist(teamId, accounId) return p.TeamMemberRepo.IsExist(teamId, accounId)
} }
//--------------- 关联项目相关接口 --------------- //--------------- 关联标签相关接口 ---------------
func (p *teamAppImpl) ListTagIds(teamId uint64) []uint64 { func (p *teamAppImpl) ListTagIds(teamId uint64) []uint64 {
tags := &[]entity.TagTreeTeam{} tags := &[]entity.TagTreeTeam{}
p.tagTreeTeamRepo.ListByCondOrder(&entity.TagTreeTeam{TeamId: teamId}, tags) p.TagTreeTeamRepo.ListByCondOrder(&entity.TagTreeTeam{TeamId: teamId}, tags)
ids := make([]uint64, 0) ids := make([]uint64, 0)
for _, v := range *tags { for _, v := range *tags {
ids = append(ids, v.TagId) ids = append(ids, v.TagId)
@@ -117,10 +106,10 @@ func (p *teamAppImpl) ListTagIds(teamId uint64) []uint64 {
// 保存关联项目信息 // 保存关联项目信息
func (p *teamAppImpl) SaveTag(ctx context.Context, tagTreeTeam *entity.TagTreeTeam) error { func (p *teamAppImpl) SaveTag(ctx context.Context, tagTreeTeam *entity.TagTreeTeam) error {
tagTreeTeam.Id = 0 tagTreeTeam.Id = 0
return p.tagTreeTeamRepo.Insert(ctx, tagTreeTeam) return p.TagTreeTeamRepo.Insert(ctx, tagTreeTeam)
} }
// 删除关联项目信息 // 删除关联项目信息
func (p *teamAppImpl) DeleteTag(ctx context.Context, teamId, tagId uint64) error { func (p *teamAppImpl) DeleteTag(ctx context.Context, teamId, tagId uint64) error {
return p.tagTreeTeamRepo.DeleteByCond(ctx, &entity.TagTreeTeam{TeamId: teamId, TagId: tagId}) return p.TagTreeTeamRepo.DeleteByCond(ctx, &entity.TagTreeTeam{TeamId: teamId, TagId: tagId})
} }

View File

@@ -1,31 +1,34 @@
package persistence package persistence
import "mayfly-go/internal/tag/domain/repository" import (
"mayfly-go/internal/tag/domain/repository"
var ( "mayfly-go/pkg/ioc"
tagTreeRepo repository.TagTree = newTagTreeRepo()
tagTreeTeamRepo repository.TagTreeTeam = newTagTreeTeamRepo()
tagResourceRepo repository.TagResource = newTagResourceRepo()
teamRepo repository.Team = newTeamRepo()
teamMemberRepo repository.TeamMember = newTeamMemberRepo()
) )
func Init() {
ioc.Register(newTagTreeRepo(), ioc.WithComponentName("TagTreeRepo"))
ioc.Register(newTagTreeTeamRepo(), ioc.WithComponentName("TagTreeTeamRepo"))
ioc.Register(newTagResourceRepo(), ioc.WithComponentName("TagResourceRepo"))
ioc.Register(newTeamRepo(), ioc.WithComponentName("TeamRepo"))
ioc.Register(newTeamMemberRepo(), ioc.WithComponentName("TeamMemberRepo"))
}
func GetTagTreeRepo() repository.TagTree { func GetTagTreeRepo() repository.TagTree {
return tagTreeRepo return ioc.Get[repository.TagTree]("TagTreeRepo")
} }
func GetTagTreeTeamRepo() repository.TagTreeTeam { func GetTagTreeTeamRepo() repository.TagTreeTeam {
return tagTreeTeamRepo return ioc.Get[repository.TagTreeTeam]("TagTreeTeamRepo")
} }
func GetTagResourceRepo() repository.TagResource { func GetTagResourceRepo() repository.TagResource {
return tagResourceRepo return ioc.Get[repository.TagResource]("TagResourceRepo")
} }
func GetTeamRepo() repository.Team { func GetTeamRepo() repository.Team {
return teamRepo return ioc.Get[repository.Team]("TeamRepo")
} }
func GetTeamMemberRepo() repository.TeamMember { func GetTeamMemberRepo() repository.TeamMember {
return teamMemberRepo return ioc.Get[repository.TeamMember]("TeamMemberRepo")
} }

View File

@@ -2,17 +2,16 @@ package router
import ( import (
"mayfly-go/internal/tag/api" "mayfly-go/internal/tag/api"
"mayfly-go/internal/tag/application" "mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func InitTagTreeRouter(router *gin.RouterGroup) { func InitTagTreeRouter(router *gin.RouterGroup) {
m := &api.TagTree{ m := new(api.TagTree)
TagTreeApp: application.GetTagTreeApp(), biz.ErrIsNil(ioc.Inject(m))
TagResourceApp: application.GetTagResourceApp(),
}
tagTree := router.Group("/tag-trees") tagTree := router.Group("/tag-trees")
{ {

View File

@@ -1,20 +1,17 @@
package router package router
import ( import (
sysapp "mayfly-go/internal/sys/application"
"mayfly-go/internal/tag/api" "mayfly-go/internal/tag/api"
"mayfly-go/internal/tag/application" "mayfly-go/pkg/biz"
"mayfly-go/pkg/ioc"
"mayfly-go/pkg/req" "mayfly-go/pkg/req"
"github.com/gin-gonic/gin" "github.com/gin-gonic/gin"
) )
func InitTeamRouter(router *gin.RouterGroup) { func InitTeamRouter(router *gin.RouterGroup) {
m := &api.Team{ m := new(api.Team)
TeamApp: application.GetTeamApp(), biz.ErrIsNil(ioc.Inject(m))
TagApp: application.GetTagTreeApp(),
AccountApp: sysapp.GetAccountApp(),
}
team := router.Group("/teams") team := router.Group("/teams")
{ {

Some files were not shown because too many files have changed in this diff Show More