2022-01-24 14:57:04 +08:00
|
|
|
import { SyncOptions, Transactionable } from 'sequelize';
|
2022-01-19 10:02:52 +08:00
|
|
|
import Database, { MagicAttributeModel } from '@nocobase/database';
|
|
|
|
|
2022-01-24 14:57:04 +08:00
|
|
|
interface LoadOptions extends Transactionable {
|
2022-01-19 10:02:52 +08:00
|
|
|
// TODO
|
|
|
|
skipExist?: boolean;
|
|
|
|
}
|
|
|
|
|
|
|
|
export class FieldModel extends MagicAttributeModel {
|
|
|
|
get db(): Database {
|
|
|
|
return (<any>this.constructor).database;
|
|
|
|
}
|
|
|
|
|
|
|
|
async load(loadOptions?: LoadOptions) {
|
2022-01-24 14:10:35 +08:00
|
|
|
const { skipExist = false } = loadOptions || {};
|
2022-01-19 10:02:52 +08:00
|
|
|
const collectionName = this.get('collectionName');
|
|
|
|
if (!this.db.hasCollection(collectionName)) {
|
|
|
|
throw new Error(`${collectionName} collection does not exist.`);
|
|
|
|
}
|
|
|
|
const collection = this.db.getCollection(collectionName);
|
|
|
|
const name = this.get('name');
|
|
|
|
if (skipExist && collection.hasField(name)) {
|
|
|
|
return collection.getField(name);
|
|
|
|
}
|
|
|
|
return collection.setField(name, this.get());
|
|
|
|
}
|
|
|
|
|
2022-01-24 14:57:04 +08:00
|
|
|
async migrate(options?: SyncOptions & Transactionable) {
|
|
|
|
const field = await this.load({
|
|
|
|
transaction: options.transaction,
|
|
|
|
});
|
2022-01-19 10:02:52 +08:00
|
|
|
await field.sync(options);
|
|
|
|
}
|
|
|
|
}
|