package model import ( "context" "net/url" "octopus/internal/dal" "octopus/internal/schema" "strings" "time" "github.com/rs/xid" "gorm.io/gorm" ) const TableNameDocFolder = "doc_folders" const TableNameDoc = "docs" type DocFolder struct { Base Name string `gorm:"column:name;type:varchar;not null"` // 文件夹名称 IsDefault bool `gorm:"column:is_default;type:boolean;not null;default:false"` // 是否默认分组 ParentPath string `gorm:"column:parent_path;type:varchar;index:idx_path"` // 路径索引 CreatedBy string `gorm:"column:created_by;type:varchar;not null"` // 创建人 } func (*DocFolder) TableName() string { return TableNameDocFolder } func (f *DocFolder) ParentID() string { if f.ParentPath == "" { return "" } parts := strings.Split(f.ParentPath, "/") return parts[len(parts)-1] } func (df DocFolder) ToSchema() *schema.DocFolder { return &schema.DocFolder{ ID: df.ID, Name: df.Name, IsDefault: df.IsDefault, CreatedAt: df.CreatedAt, UpdatedAt: df.UpdatedAt, } } func (d *DocFolder) BeforeCreate(*gorm.DB) error { d.ID = xid.New().String() return nil } // 在返回树结构的时候有用 type DocFolderWithChildren struct { *DocFolder Children []*DocFolderWithChildren // 子文件夹 } func (df *DocFolderWithChildren) ToTreeSchema() *schema.DocFolderWithChildren { var traverse func(folder *DocFolderWithChildren) *schema.DocFolderWithChildren traverse = func(folder *DocFolderWithChildren) *schema.DocFolderWithChildren { children := make([]*schema.DocFolderWithChildren, 0, len(folder.Children)) for _, child := range folder.Children { children = append(children, traverse(child)) } return &schema.DocFolderWithChildren{ DocFolder: folder.ToSchema(), Children: children, } } return traverse(df) } type Doc struct { Base Name string `gorm:"column:name;type:varchar;not null"` // 文件夹名称 IsDeletable bool `gorm:"column:is_deletable;type:boolean;not null;default:true"` // 是否允许被删除 IsEditable bool `gorm:"column:is_editable;type:boolean;not null;default:true"` // 是否允许编辑名称 FolderID string `gorm:"column:folder_id;type:varchar;index:idx_folder_id"` // 文件夹ID ObjectName string `gorm:"column:object_name;type:varchar"` // 对象存储中对应的object_name UploadedAt time.Time `gorm:"column:uploaded_at"` // 上传时间 CreatedBy string `gorm:"column:created_by;type:varchar;not null"` // 创建人 Folder *DocFolder `gorm:"foreignKey:FolderID;references:ID"` } func (d *Doc) ToSchema(ctx context.Context) *schema.Doc { url, _ := d.PresignedURL(ctx) return &schema.Doc{ ID: d.ID, Folder: d.Folder.ToSchema(), PresignedURL: url.String(), UploadedAt: d.UploadedAt, CreatedAt: d.CreatedAt, UpdatedAt: d.UpdatedAt, } } func (d *Doc) PresignedURL(ctx context.Context) (*url.URL, error) { return dal.GetStorage().PresignedGetObject(ctx, d.ObjectName, time.Hour) } func (*Doc) TableName() string { return TableNameDoc } func (d *Doc) BeforeCreate(*gorm.DB) error { d.ID = xid.New().String() return nil }