feat: add field import function

This commit is contained in:
chenos 2020-12-21 10:42:44 +08:00
parent 4bc2df296d
commit c5e0f65ff5
2 changed files with 73 additions and 1 deletions

View File

@ -1,5 +1,6 @@
import _ from 'lodash';
import BaseModel from './base';
import Field from './field';
import { TableOptions } from '@nocobase/database';
import { SaveOptions, Op } from 'sequelize';
@ -159,8 +160,15 @@ export class CollectionModel extends BaseModel {
continue;
}
const Model = this.database.getModel(key);
const ids = [];
let ids = [];
for (const index in data[key]) {
if (key === 'fields') {
ids = await Field.import(data[key], {
...options,
collectionName: collection.name,
});
continue;
}
let model;
const item = data[key][index];
if (item.name) {

View File

@ -7,6 +7,11 @@ import { BuildOptions } from 'sequelize';
import { SaveOptions, Utils } from 'sequelize';
import { generateCollectionName } from './collection';
interface FieldImportOptions extends SaveOptions {
parentId?: number;
collectionName?: string;
}
export function generateFieldName(title?: string): string {
return `f_${Math.random().toString(36).replace('0.', '').slice(-4).padStart(4, '0')}`;
}
@ -85,6 +90,65 @@ export class FieldModel extends BaseModel {
}
});
}
static async import(items: any, options: FieldImportOptions = {}): Promise<any> {
const { parentId, collectionName } = options;
if (!Array.isArray(items)) {
items = [items];
}
const ids = [];
for (const index in items) {
const item = items[index];
let model;
const where: any = {};
if (parentId) {
where.parent_id = parentId
} else {
where.collection_name = collectionName;
}
if (item.name) {
model = await this.findOne({
...options,
where: {
...where,
name: item.name,
},
});
}
if (!model && item.title) {
model = await this.findOne({
...options,
where: {
...where,
title: item.title,
},
});
}
if (!model) {
const tmp: any = {};
if (parentId) {
tmp.parent_id = parentId
} else {
tmp.collection_name = collectionName;
}
model = await this.create({
...item,
...tmp,
}, options);
}
if (Array.isArray(item.children)) {
const childrenIds = await this.import(item.children, {
...options,
parentId: model.id,
collectionName,
});
await model.updateAssociations({
children: childrenIds,
}, options);
}
}
return ids;
}
}
export default FieldModel;