Files
StoreWeb/Plugins/CloudProduct/ImportConverters/GoodsConverter.cs
T

108 lines
2.3 KiB
C#

using Store.Modules.CloudProduct.Entities;
using Store.Modules.CloudProduct.Enums;
using System.Text.Json.Nodes;
namespace Store.Modules.CloudProduct.ImportConverters
{
/// <summary>
/// 导入商品数据转换器
/// </summary>
public interface IGoodsConverter
{
/// <summary>
/// 原始数据(JSON 原文)
/// </summary>
string RawData { get; }
/// <summary>
/// 获取转换器名称
/// </summary>
string ConverterName { get; }
/// <summary>
/// 支持的平台类型
/// </summary>
PlatformType Platform { get; }
/// <summary>
/// 读取内容
/// </summary>
/// <param name="content">JSON 原文内容</param>
void ReadContent(string content);
/// <summary>
/// 判断是否匹配当前转换器
/// </summary>
/// <returns>是否匹配</returns>
bool IsMatch();
/// <summary>
/// 转换为标准商品模型
/// </summary>
GoodsEntity Convert();
}
/// <summary>
/// 转换器基类:统一实现读取、校验与转换骨架,子类只需实现匹配判定与字段映射。
/// </summary>
public abstract class GoodsConverter : IGoodsConverter
{
private bool _isMatch = false;
public string RawData { get; private set; } = null!;
public abstract string ConverterName { get; }
public abstract PlatformType Platform { get; }
void IGoodsConverter.ReadContent(string content)
{
ReadContent(content);
}
protected virtual void ReadContent(string content)
{
RawData = content;
}
public virtual bool IsMatch()
{
_isMatch = true;
return IsMatchCore();
}
/// <summary>
/// 由子类实现的具体匹配判定
/// </summary>
protected abstract bool IsMatchCore();
/// <summary>
/// 带校验的转换(基类统一实现)
/// </summary>
public virtual GoodsEntity Convert()
{
if (_isMatch == false) throw new Exception("未校验数据");
try
{
JsonNode.Parse(RawData);
}
catch { throw new Exception("数据解析失败,不是有效的JSON格式"); }
var goods = ConvertCore();
if (goods == null)
throw new Exception("转换失败");
// 基础校验
if (goods.GoodsId == 0)
throw new Exception("商品ID不能为空");
return goods;
}
/// <summary>
/// 由子类实现的具体字段映射
/// </summary>
protected abstract GoodsEntity ConvertCore();
}
}