using FluentValidation; using MessageService.Domain.Enums; using MessageService.WebApi.Application.Message; namespace MessageService.WebApi.Controllers.Message { public class MessageSendRequest { // 基础元数据 public Guid ClientMsgId { get; init; } public Guid TargetId { get; init; } public ChatType ChatType { get; init; } public MessageType MsgType { get; init; } // 业务属性 public Guid? QuoteMessageId { get; init; } public Dictionary? Ext { get; init; } // 载荷数据(根据 MsgType 选择性填充) public string? Text { get; init; } public string? Url { get; init; } public int? Width { get; init; } public int? Height { get; init; } public string? Thumb { get; init; } public int? Duration { get; init; } public Guid? FileId { get; init; } public string? FileName { get; init; } public long? FileSize { get; init; } public string? FileFormat { get; init; } public SendMsgCommand ToCommand(Guid senderId) { return new SendMsgCommand( senderId, TargetId, ChatType, MsgType, ClientMsgId, QuoteMessageId, Ext, Text, Url, Width, Height, Thumb, Duration, FileId, FileName, FileSize, FileFormat ); } } public class MessageSendRequestValidator : AbstractValidator { public MessageSendRequestValidator() { RuleFor(r => r.ClientMsgId) .NotNull() .NotEmpty(); RuleFor(r => r.TargetId) .NotEmpty() .NotNull(); // 文本消息:text 必填 When(r => r.MsgType == MessageType.Text, () => { RuleFor(r => r.Text).NotEmpty().WithMessage("文本消息的 text 字段不能为空"); }); // 图片/视频/语音消息:url 必填 When(r => r.MsgType == MessageType.Image || r.MsgType == MessageType.Video || r.MsgType == MessageType.Voice, () => { RuleFor(r => r) .Must(request => !string.IsNullOrWhiteSpace(request.Url) || request.FileId.HasValue) .WithMessage("媒体消息必须提供 url 或 fileId"); }); When(r => r.MsgType == MessageType.File, () => { RuleFor(r => r.FileId).NotNull().NotEmpty().WithMessage("文件消息的 fileId 字段不能为空"); RuleFor(r => r.FileName).NotEmpty().WithMessage("文件消息的 fileName 字段不能为空"); RuleFor(r => r.FileSize).NotNull().GreaterThanOrEqualTo(0).WithMessage("文件消息的 fileSize 字段不合法"); RuleFor(r => r.FileFormat).NotEmpty().WithMessage("文件消息的 fileFormat 字段不能为空"); }); } } }