feat: load the saved collection options

This commit is contained in:
chenos 2020-12-07 17:21:14 +08:00
parent e6f9973531
commit fb7706094b
3 changed files with 25 additions and 8 deletions

View File

@ -15,6 +15,7 @@ import {
} from './fields';
import Database from './database';
import { Model, ModelCtor } from './model';
import _ from 'lodash';
const registeredModels = new Map<string, any>();
@ -219,6 +220,7 @@ export class Table {
updatedAt: Utils.underscoredIf('updatedAt', underscored),
indexes: Array.from(this.indexes.values()),
// freezeTableName: true,
hooks: _.get(this.Model.options, 'hooks') || {},
...this.modelOptions,
};
}

View File

@ -40,15 +40,19 @@ export class CollectionModel extends BaseModel {
return this.findOne({ where: { name } });
}
/**
*
*/
async migrate() {
async loadTableOptions() {
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 this.database.table({...prevOptions, ...options});
}
/**
*
*/
async migrate() {
const table = await this.loadTableOptions();
return await table.sync({
force: false,
alter: {
@ -75,6 +79,13 @@ export class CollectionModel extends BaseModel {
};
}
static async load() {
const collections = await this.findAll();
for (const collection of collections) {
await collection.loadTableOptions();
}
}
static async import(data: TableOptions, options: SaveOptions = {}): Promise<CollectionModel> {
data = _.cloneDeep(data);
const collection = await this.create({

View File

@ -22,7 +22,11 @@ export default async function (this: Application, options = {}) {
Model.addHook(hookKey, hooks[modelName][hookKey]);
});
});
// 加载数据库表 collections 中已经保存的表配置
// await Collection.findAll();
try {
// 加载数据库表 collections 中已经保存的表配置
// 如果未 sync 可能报错
// TODO collections sync
await database.getModel('collections').load();
} catch (error) {
}
}