85 lines
2.0 KiB
Go
85 lines
2.0 KiB
Go
package service
|
|
|
|
import (
|
|
"fmt"
|
|
"github.com/badoux/goscraper"
|
|
"github.com/spf13/cast"
|
|
"gorm.io/gorm"
|
|
"website-nav/global/client"
|
|
"website-nav/http/param"
|
|
"website-nav/http/vo"
|
|
"website-nav/model"
|
|
)
|
|
|
|
type navigation struct {
|
|
*gorm.DB
|
|
}
|
|
|
|
func Navigation() navigation { return navigation{DB: client.DB} }
|
|
|
|
// List
|
|
// @description: 导航分页列表
|
|
// @receiver navigation
|
|
// @param p
|
|
// @return data
|
|
// @return total
|
|
// @return err
|
|
func (s navigation) List(p param.NavigationList) (data []vo.NavigationItem, total int64, err error) {
|
|
sql := s.Table("t_navigation as tn").
|
|
Scopes(Paginate(p.Current, p.Size)).
|
|
Joins("LEFT JOIN t_navigation_type as tnt ON tnt.id = tn.type_id").
|
|
Select("tn.id,tn.title,tn.url,tn.description,tn.icon,tn.enabled,tn.created_at,tn.updated_at,tnt.id as type_id,tnt.name as type")
|
|
|
|
if p.Type != "" {
|
|
sql.Where("tn.type_id = ?", p.Type)
|
|
}
|
|
if p.Title != "" {
|
|
sql.Where("tn.title LIKE ?", "%"+p.Title+"%")
|
|
}
|
|
if p.Link != "" {
|
|
sql.Where("tn.url LIKE ?", "%"+p.Link+"%")
|
|
}
|
|
|
|
err = sql.Find(&data).Offset(-1).Limit(-1).Count(&total).Error
|
|
return
|
|
}
|
|
|
|
// SaveNavigation
|
|
// @description: 新增/编辑导航
|
|
// @receiver s
|
|
// @param p
|
|
// @return error
|
|
func (s navigation) SaveNavigation(p param.SaveNavigation) error {
|
|
if p.Id != "" {
|
|
return s.Model(&model.Navigation{}).Where("id = ?", p.Id).Updates(map[string]any{
|
|
"title": p.Title,
|
|
"url": p.Url,
|
|
"icon": p.Icon,
|
|
"enabled": p.Enabled,
|
|
"description": p.Description,
|
|
}).Error
|
|
}
|
|
|
|
websiteInfo, err := goscraper.Scrape(p.Url, 5)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
return s.Create(&model.Navigation{
|
|
Title: p.Title,
|
|
Url: p.Url,
|
|
Icon: fmt.Sprintf("%s%s", p.Url, websiteInfo.Preview.Icon),
|
|
Enabled: cast.ToBool(p.Enabled),
|
|
Description: p.Description,
|
|
}).Error
|
|
}
|
|
|
|
// DeleteNavigation
|
|
// @description: 删除导航
|
|
// @receiver s
|
|
// @param id
|
|
// @return error
|
|
func (s navigation) DeleteNavigation(id string) error {
|
|
return s.Where("id = ?", id).Delete(&model.Navigation{}).Error
|
|
}
|