tachybase_todo/packages/plugin-collections/src/models/collection.ts

94 lines
2.4 KiB
TypeScript
Raw Normal View History

import _ from 'lodash';
import BaseModel from './base';
import { TableOptions } from '@nocobase/database';
import { SaveOptions, Utils } from 'sequelize';
2020-10-24 15:34:43 +08:00
export class CollectionModel extends BaseModel {
/**
* name collection
*
* @param name
*/
static async findByName(name: string) {
return this.findOne({ where: { name } });
}
/**
*
*
* 使 3+2
* 1. id
* 2.
* 3.
* 4.
* 5.
*
* @param title
*/
static generateName(title?: string): string {
return `t_${Date.now().toString(36)}_${Math.random().toString(36).replace('0.', '').slice(-4).padStart(4, '0')}`;
}
/**
*
*/
async migrate() {
const options = await this.getOptions();
const prevTable = this.database.getTable(this.get('name'));
const prevOptions = prevTable ? prevTable.getOptions() : {};
// table 是初始化和重新初始化
const table = this.database.table({...prevOptions, ...options});
return await table.sync({
force: false,
alter: {
drop: false,
}
});
}
async getFieldsOptions() {
const fieldsOptions = [];
const fields = await this.getFields();
for (const field of fields) {
fieldsOptions.push(await field.getOptions());
2020-10-24 15:34:43 +08:00
}
return fieldsOptions;
}
async getOptions(): Promise<TableOptions> {
return {
...this.get('options'),
2020-10-24 15:34:43 +08:00
name: this.get('name'),
title: this.get('title'),
fields: await this.getFieldsOptions(),
};
}
static async import(data: TableOptions, options: SaveOptions = {}): Promise<CollectionModel> {
data = _.cloneDeep(data);
const collection = await this.create({
...data,
}, options);
const items: any = {};
const associations = ['fields', 'tabs', 'actions', 'views'];
for (const key of associations) {
if (!Array.isArray(data[key])) {
continue;
}
items[key] = data[key].map((item, sort) => ({
...item,
sort,
}));
for (const item of items[key]) {
await collection[`create${_.upperFirst(Utils.singularize(key))}`](item);
}
}
// updateAssociations 有 BUG
// await collection.updateAssociations(items, options);
return collection;
2020-10-24 15:34:43 +08:00
}
}
export default CollectionModel;