import { Seeder, SeederFactoryManager } from 'typeorm-extension'; import { DataSource } from 'typeorm'; import { Template } from '../../entity/template.entity'; /** * @class TemplateSeeder * @description 模板数据填充器,用于在数据库初始化时插入默认的模板数据. */ export default class TemplateSeeder implements Seeder { /** * @method run * @description 执行数据填充操作.如果模板不存在,则创建它;如果存在,则更新它. * @param {DataSource} dataSource - 数据源实例,用于获取 repository. * @param {SeederFactoryManager} factoryManager - Seeder 工厂管理器. */ public async run( dataSource: DataSource, factoryManager: SeederFactoryManager ): Promise { // 获取 Template 实体的 repository const templateRepository = dataSource.getRepository(Template); const templates = [ { name: 'product.sku', value: `<% // 按分类判断属性排序逻辑 if (it.category.name === 'nicotine-pouches') { // 1. 定义 nicotine-pouches 专属的属性固定顺序 const fixedOrder = ['brand','category', 'flavor', 'strength', 'humidity']; sortedAttrShortNames = fixedOrder.map(attrKey => { if(attrKey === 'category') return it.category.shortName // 排序 const matchedAttr = it.attributes.find(a => a?.dict?.name === attrKey); return matchedAttr ? matchedAttr.shortName : ''; }).filter(Boolean); // 移除空值,避免多余的 "-" } else { // 非目标分类,保留 attributes 原有顺序 sortedAttrShortNames = it.attributes.map(a => a.shortName); } // 4. 拼接分类名 + 排序后的属性名 %><%= sortedAttrShortNames.join('-') %><% %>`, description: '产品SKU模板', testData: JSON.stringify({ "category": { "name": "nicotine-pouches", "shortName": "NP" }, "attributes": [ { "dict": {"name": "brand"},"shortName": "YOONE" }, { "dict": {"name": "flavor"},"shortName": "FL" }, { "dict": {"name": "strength"},"shortName": "10MG" }, { "dict": {"name": "humidity"},"shortName": "DRY" } ] }), }, { name: 'product.title', value: "<%= it.attributes.map(a => a.title).join(' ') %>", description: '产品标题模板', testData: JSON.stringify({ attributes: [ { title: 'Brand' }, { title: 'Flavor' }, { title: '10mg' }, { title: 'Dry' }, ], }), }, { name: 'site.product.sku', value: '<%= it.site.skuPrefix %><%= it.product.sku %>', description: '站点产品SKU模板', testData: JSON.stringify({ site: { skuPrefix: 'SITE-', }, product: { sku: 'PRODUCT-SKU-001', }, }), }, ]; for (const t of templates) { // 检查模板是否已存在 const existingTemplate = await templateRepository.findOne({ where: { name: t.name }, }); if (existingTemplate) { // 如果存在,则更新 existingTemplate.value = t.value; existingTemplate.description = t.description; existingTemplate.testData = t.testData; await templateRepository.save(existingTemplate); } else { // 如果不存在,则创建并保存 const template = new Template(); template.name = t.name; template.value = t.value; template.description = t.description; template.testData = t.testData; await templateRepository.save(template); } } } }