create_file.go 1.4 KB
package command

import (
	"fmt"
	"gitlab.fjmaimaimai.com/allied-creation/character-library-metadata-bastion/pkg/domain"
	"path/filepath"
	"reflect"
	"strings"

	"github.com/beego/beego/v2/core/validation"
)

type CreateFileCommand struct {
	// 名称
	Name string `cname:"名称" json:"name" valid:"Required"`
	// 文件地址
	Url string `cname:"文件地址" json:"url" valid:"Required"`
	// 文件大小 单位KB
	FileSize int `cname:"文件大小" json:"fileSize" valid:"Required"`
}

var MaxFileSize = 50 * 1024 * 1024

func (createFileCommand *CreateFileCommand) Valid(validation *validation.Validation) {
	ext := filepath.Ext(createFileCommand.Name)
	if !(ext == domain.XLS || ext == domain.XLSX) {
		validation.Error("仅支持文件格式 xls 、 xlsx")
		return
	}
	if createFileCommand.FileSize > 0 && createFileCommand.FileSize > MaxFileSize {
		validation.Error("文件大小超过50M")
		return
	}
}

func (createFileCommand *CreateFileCommand) ValidateCommand() error {
	valid := validation.Validation{}
	b, err := valid.Valid(createFileCommand)
	if err != nil {
		return err
	}
	if !b {
		elem := reflect.TypeOf(createFileCommand).Elem()
		for _, validErr := range valid.Errors {
			field, isExist := elem.FieldByName(validErr.Field)
			if isExist {
				return fmt.Errorf(strings.Replace(validErr.Message, validErr.Field, field.Tag.Get("cname"), -1))
			} else {
				return fmt.Errorf(validErr.Message)
			}
		}
	}
	return nil
}