forked from yoone/API
63 lines
2.4 KiB
TypeScript
63 lines
2.4 KiB
TypeScript
import { Seeder } from 'typeorm-extension';
|
|
import { DataSource } from 'typeorm';
|
|
import { Dict } from '../../entity/dict.entity';
|
|
import { Category } from '../../entity/category.entity';
|
|
import { CategoryAttribute } from '../../entity/category_attribute.entity';
|
|
|
|
export default class CategoryAttributeSeeder implements Seeder {
|
|
public async run(
|
|
dataSource: DataSource,
|
|
): Promise<any> {
|
|
const dictRepository = dataSource.getRepository(Dict);
|
|
const categoryRepository = dataSource.getRepository(Category);
|
|
const categoryAttributeRepository = dataSource.getRepository(CategoryAttribute);
|
|
|
|
// 1. 确保属性字典存在
|
|
const attributeNames = ['brand', 'strength', 'flavor', 'size', 'humidity'];
|
|
const attributeDicts: Dict[] = [];
|
|
|
|
for (const name of attributeNames) {
|
|
let dict = await dictRepository.findOne({ where: { name } });
|
|
if (!dict) {
|
|
dict = new Dict();
|
|
dict.name = name;
|
|
dict.title = name.charAt(0).toUpperCase() + name.slice(1);
|
|
dict.deletable = false;
|
|
dict = await dictRepository.save(dict);
|
|
console.log(`Created Dict: ${name}`);
|
|
}
|
|
attributeDicts.push(dict);
|
|
}
|
|
|
|
// 2. 获取 'nicotine-pouches' 分类 (由 CategorySeeder 创建)
|
|
const nicotinePouchesCategory = await categoryRepository.findOne({
|
|
where: {
|
|
name: 'nicotine-pouches'
|
|
}
|
|
});
|
|
|
|
if (!nicotinePouchesCategory) {
|
|
console.warn('Category "nicotine-pouches" not found. Skipping attribute linking. Please ensure CategorySeeder runs first.');
|
|
return;
|
|
}
|
|
|
|
// 3. 绑定属性到 'nicotine-pouches' 分类
|
|
for (const attrDict of attributeDicts) {
|
|
const existing = await categoryAttributeRepository.findOne({
|
|
where: {
|
|
category: { id: nicotinePouchesCategory.id },
|
|
attributeDict: { id: attrDict.id }
|
|
}
|
|
});
|
|
|
|
if (!existing) {
|
|
const link = new CategoryAttribute();
|
|
link.category = nicotinePouchesCategory;
|
|
link.attributeDict = attrDict;
|
|
await categoryAttributeRepository.save(link);
|
|
console.log(`Linked ${attrDict.name} to ${nicotinePouchesCategory.name}`);
|
|
}
|
|
}
|
|
}
|
|
}
|