From 416f5e09867b71082d8ceef798cc39ca8c0c5b9c Mon Sep 17 00:00:00 2001 From: Fu Diwei Date: Sat, 28 Dec 2024 16:26:01 +0800 Subject: [PATCH] refactor: clean code --- internal/applicant/applicant.go | 8 ++--- internal/certificate/service.go | 8 ++--- internal/domain/{setting.go => settings.go} | 34 +++++++++---------- internal/notify/service.go | 8 ++--- internal/repository/access.go | 2 +- internal/repository/certificate.go | 2 +- .../repository/{setting.go => settings.go} | 8 ++--- internal/repository/statistics.go | 24 ++++++++----- internal/routes/routes.go | 2 +- .../workflow/node-processor/notify_node.go | 4 +-- .../certificate/CertificateDetailDrawer.tsx | 2 +- .../workflow/run/WorkflowRunDetailDrawer.tsx | 2 +- 12 files changed, 55 insertions(+), 49 deletions(-) rename internal/domain/{setting.go => settings.go} (73%) rename internal/repository/{setting.go => settings.go} (73%) diff --git a/internal/applicant/applicant.go b/internal/applicant/applicant.go index 909622a6..f9fd7eb3 100644 --- a/internal/applicant/applicant.go +++ b/internal/applicant/applicant.go @@ -58,7 +58,7 @@ type Certificate struct { type ApplyOption struct { Email string `json:"email"` - Domain string `json:"subjectAltNames"` + SubjectAltNames string `json:"subjectAltNames"` AccessConfig string `json:"accessConfig"` KeyAlgorithm string `json:"keyAlgorithm"` Nameservers string `json:"nameservers"` @@ -144,7 +144,7 @@ func Get(record *models.Record) (Applicant, error) { option := &ApplyOption{ Email: applyConfig.Email, - Domain: record.GetString("domain"), + SubjectAltNames: record.GetString("domain"), AccessConfig: access.GetString("config"), KeyAlgorithm: applyConfig.KeyAlgorithm, Nameservers: applyConfig.Nameservers, @@ -166,7 +166,7 @@ func GetWithApplyNode(node *domain.WorkflowNode) (Applicant, error) { applyConfig := &ApplyOption{ Email: node.GetConfigString("email"), - Domain: node.GetConfigString("domain"), + SubjectAltNames: node.GetConfigString("domain"), AccessConfig: access.Config, KeyAlgorithm: node.GetConfigString("keyAlgorithm"), Nameservers: node.GetConfigString("nameservers"), @@ -276,7 +276,7 @@ func apply(option *ApplyOption, provider challenge.Provider) (*Certificate, erro myUser.Registration = reg } - domains := strings.Split(option.Domain, ";") + domains := strings.Split(option.SubjectAltNames, ";") request := certificate.ObtainRequest{ Domains: domains, Bundle: true, diff --git a/internal/certificate/service.go b/internal/certificate/service.go index 08f485b2..d59fccc4 100644 --- a/internal/certificate/service.go +++ b/internal/certificate/service.go @@ -18,7 +18,7 @@ const ( ) type CertificateRepository interface { - GetExpireSoon(ctx context.Context) ([]domain.Certificate, error) + ListExpireSoon(ctx context.Context) ([]domain.Certificate, error) } type certificateService struct { @@ -35,7 +35,7 @@ func (s *certificateService) InitSchedule(ctx context.Context) error { scheduler := app.GetScheduler() err := scheduler.Add("certificate", "0 0 * * *", func() { - certs, err := s.repo.GetExpireSoon(context.Background()) + certs, err := s.repo.ListExpireSoon(context.Background()) if err != nil { app.GetApp().Logger().Error("failed to get expire soon certificate", "err", err) return @@ -61,14 +61,14 @@ func buildMsg(records []domain.Certificate) *domain.NotifyMessage { } // 查询模板信息 - settingRepo := repository.NewSettingRepository() + settingRepo := repository.NewSettingsRepository() setting, err := settingRepo.GetByName(context.Background(), "notifyTemplates") subject := defaultExpireSubject message := defaultExpireMessage if err == nil { - var templates *domain.NotifyTemplates + var templates *domain.NotifyTemplatesSettingsContent json.Unmarshal([]byte(setting.Content), &templates) diff --git a/internal/domain/setting.go b/internal/domain/settings.go similarity index 73% rename from internal/domain/setting.go rename to internal/domain/settings.go index 697972ed..7c8f374c 100644 --- a/internal/domain/setting.go +++ b/internal/domain/settings.go @@ -11,10 +11,24 @@ type Settings struct { Content string `json:"content" db:"content"` } -type NotifyChannelsConfig map[string]map[string]any +type NotifyTemplatesSettingsContent struct { + NotifyTemplates []NotifyTemplate `json:"notifyTemplates"` +} -func (s *Settings) GetChannelContent(channel string) (map[string]any, error) { - conf := &NotifyChannelsConfig{} +type NotifyTemplate struct { + Subject string `json:"subject"` + Message string `json:"message"` +} + +type NotifyChannelsSettingsContent map[string]map[string]any + +type NotifyMessage struct { + Subject string `json:"subject"` + Message string `json:"message"` +} + +func (s *Settings) GetNotifyChannelConfig(channel string) (map[string]any, error) { + conf := &NotifyChannelsSettingsContent{} if err := json.Unmarshal([]byte(s.Content), conf); err != nil { return nil, err } @@ -26,17 +40,3 @@ func (s *Settings) GetChannelContent(channel string) (map[string]any, error) { return v, nil } - -type NotifyTemplates struct { - NotifyTemplates []NotifyTemplate `json:"notifyTemplates"` -} - -type NotifyTemplate struct { - Subject string `json:"subject"` - Message string `json:"message"` -} - -type NotifyMessage struct { - Subject string `json:"subject"` - Message string `json:"message"` -} diff --git a/internal/notify/service.go b/internal/notify/service.go index d5a49e4c..8c99d824 100644 --- a/internal/notify/service.go +++ b/internal/notify/service.go @@ -12,15 +12,15 @@ const ( notifyTestBody = "欢迎使用 Certimate ,这是一条测试通知。" ) -type SettingRepository interface { +type SettingsRepository interface { GetByName(ctx context.Context, name string) (*domain.Settings, error) } type NotifyService struct { - settingRepo SettingRepository + settingRepo SettingsRepository } -func NewNotifyService(settingRepo SettingRepository) *NotifyService { +func NewNotifyService(settingRepo SettingsRepository) *NotifyService { return &NotifyService{ settingRepo: settingRepo, } @@ -32,7 +32,7 @@ func (n *NotifyService) Test(ctx context.Context, req *domain.NotifyTestPushReq) return fmt.Errorf("failed to get notify channels settings: %w", err) } - channelConfig, err := setting.GetChannelContent(req.Channel) + channelConfig, err := setting.GetNotifyChannelConfig(req.Channel) if err != nil { return fmt.Errorf("failed to get notify channel \"%s\" config: %w", req.Channel, err) } diff --git a/internal/repository/access.go b/internal/repository/access.go index a0cca405..1053799e 100644 --- a/internal/repository/access.go +++ b/internal/repository/access.go @@ -31,8 +31,8 @@ func (a *AccessRepository) GetById(ctx context.Context, id string) (*domain.Acce UpdatedAt: record.GetTime("updated"), }, Name: record.GetString("name"), - Config: record.GetString("config"), ConfigType: record.GetString("configType"), + Config: record.GetString("config"), Usage: record.GetString("usage"), } return rs, nil diff --git a/internal/repository/certificate.go b/internal/repository/certificate.go index 36765790..6b540f80 100644 --- a/internal/repository/certificate.go +++ b/internal/repository/certificate.go @@ -13,7 +13,7 @@ func NewCertificateRepository() *CertificateRepository { return &CertificateRepository{} } -func (c *CertificateRepository) GetExpireSoon(ctx context.Context) ([]domain.Certificate, error) { +func (c *CertificateRepository) ListExpireSoon(ctx context.Context) ([]domain.Certificate, error) { rs := []domain.Certificate{} if err := app.GetApp().Dao().DB(). NewQuery("select * from certificate where expireAt > datetime('now') and expireAt < datetime('now', '+20 days')"). diff --git a/internal/repository/setting.go b/internal/repository/settings.go similarity index 73% rename from internal/repository/setting.go rename to internal/repository/settings.go index 84ee0263..fb59b125 100644 --- a/internal/repository/setting.go +++ b/internal/repository/settings.go @@ -8,13 +8,13 @@ import ( "github.com/usual2970/certimate/internal/domain" ) -type SettingRepository struct{} +type SettingsRepository struct{} -func NewSettingRepository() *SettingRepository { - return &SettingRepository{} +func NewSettingsRepository() *SettingsRepository { + return &SettingsRepository{} } -func (s *SettingRepository) GetByName(ctx context.Context, name string) (*domain.Settings, error) { +func (s *SettingsRepository) GetByName(ctx context.Context, name string) (*domain.Settings, error) { resp, err := app.GetApp().Dao().FindFirstRecordByFilter("settings", "name={:name}", dbx.Params{"name": name}) if err != nil { return nil, err diff --git a/internal/repository/statistics.go b/internal/repository/statistics.go index aa843a12..5ee01cb1 100644 --- a/internal/repository/statistics.go +++ b/internal/repository/statistics.go @@ -13,21 +13,21 @@ func NewStatisticsRepository() *StatisticsRepository { return &StatisticsRepository{} } -type totalResp struct { - Total int `json:"total" db:"total"` -} - func (r *StatisticsRepository) Get(ctx context.Context) (*domain.Statistics, error) { rs := &domain.Statistics{} // 所有证书 - certTotal := totalResp{} + certTotal := struct { + Total int `db:"total"` + }{} if err := app.GetApp().Dao().DB().NewQuery("select count(*) as total from certificate").One(&certTotal); err != nil { return nil, err } rs.CertificateTotal = certTotal.Total // 即将过期证书 - certExpireSoonTotal := totalResp{} + certExpireSoonTotal := struct { + Total int `db:"total"` + }{} if err := app.GetApp().Dao().DB(). NewQuery("select count(*) as total from certificate where expireAt > datetime('now') and expireAt < datetime('now', '+20 days')"). One(&certExpireSoonTotal); err != nil { @@ -36,7 +36,9 @@ func (r *StatisticsRepository) Get(ctx context.Context) (*domain.Statistics, err rs.CertificateExpireSoon = certExpireSoonTotal.Total // 已过期证书 - certExpiredTotal := totalResp{} + certExpiredTotal := struct { + Total int `db:"total"` + }{} if err := app.GetApp().Dao().DB(). NewQuery("select count(*) as total from certificate where expireAt < datetime('now')"). One(&certExpiredTotal); err != nil { @@ -45,14 +47,18 @@ func (r *StatisticsRepository) Get(ctx context.Context) (*domain.Statistics, err rs.CertificateExpired = certExpiredTotal.Total // 所有工作流 - workflowTotal := totalResp{} + workflowTotal := struct { + Total int `db:"total"` + }{} if err := app.GetApp().Dao().DB().NewQuery("select count(*) as total from workflow").One(&workflowTotal); err != nil { return nil, err } rs.WorkflowTotal = workflowTotal.Total // 已启用工作流 - workflowEnabledTotal := totalResp{} + workflowEnabledTotal := struct { + Total int `db:"total"` + }{} if err := app.GetApp().Dao().DB().NewQuery("select count(*) as total from workflow where enabled is TRUE").One(&workflowEnabledTotal); err != nil { return nil, err } diff --git a/internal/routes/routes.go b/internal/routes/routes.go index 4e0e51b7..058f1815 100644 --- a/internal/routes/routes.go +++ b/internal/routes/routes.go @@ -14,7 +14,7 @@ import ( func Register(e *echo.Echo) { group := e.Group("/api", apis.RequireAdminAuth()) - notifyRepo := repository.NewSettingRepository() + notifyRepo := repository.NewSettingsRepository() notifySvc := notify.NewNotifyService(notifyRepo) workflowRepo := repository.NewWorkflowRepository() diff --git a/internal/workflow/node-processor/notify_node.go b/internal/workflow/node-processor/notify_node.go index 17f8d2f3..42d071b0 100644 --- a/internal/workflow/node-processor/notify_node.go +++ b/internal/workflow/node-processor/notify_node.go @@ -21,7 +21,7 @@ func NewNotifyNode(node *domain.WorkflowNode) *notifyNode { return ¬ifyNode{ node: node, Logger: NewLogger(node), - settingRepo: repository.NewSettingRepository(), + settingRepo: repository.NewSettingsRepository(), } } @@ -35,7 +35,7 @@ func (n *notifyNode) Run(ctx context.Context) error { return err } - channelConfig, err := setting.GetChannelContent(n.node.GetConfigString("channel")) + channelConfig, err := setting.GetNotifyChannelConfig(n.node.GetConfigString("channel")) if err != nil { n.AddOutput(ctx, n.node.Name, "获取通知渠道配置失败", err.Error()) return err diff --git a/ui/src/components/certificate/CertificateDetailDrawer.tsx b/ui/src/components/certificate/CertificateDetailDrawer.tsx index e65cec51..b8ff8972 100644 --- a/ui/src/components/certificate/CertificateDetailDrawer.tsx +++ b/ui/src/components/certificate/CertificateDetailDrawer.tsx @@ -34,7 +34,7 @@ const CertificateDetailDrawer = ({ data, loading, trigger, ...props }: Certifica open={open} loading={loading} placement="right" - title={data?.id} + title={`certimate-${data?.id}`} width={640} onClose={() => setOpen(false)} > diff --git a/ui/src/components/workflow/run/WorkflowRunDetailDrawer.tsx b/ui/src/components/workflow/run/WorkflowRunDetailDrawer.tsx index 09716384..4013f09a 100644 --- a/ui/src/components/workflow/run/WorkflowRunDetailDrawer.tsx +++ b/ui/src/components/workflow/run/WorkflowRunDetailDrawer.tsx @@ -30,7 +30,7 @@ const WorkflowRunDetailDrawer = ({ data, loading, trigger, ...props }: WorkflowR <> {triggerDom} - setOpen(false)}> + setOpen(false)}>