API/src/db/seeds/template.seeder.ts

92 lines
2.8 KiB
TypeScript

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<any> {
// 获取 Template 实体的 repository
const templateRepository = dataSource.getRepository(Template);
const templates = [
{
name: 'product.sku',
value: "<%= [it.category.shortName].concat(it.attributes.map(a => a.shortName)).join('-') %>",
description: '产品SKU模板',
testData: JSON.stringify({
category: {
shortName: 'CAT',
},
attributes: [
{ shortName: 'BR' },
{ shortName: 'FL' },
{ shortName: '10MG' },
{ 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);
}
}
}
}