From fb7706094b8a667324dcbca8ed34423d16c24eb5 Mon Sep 17 00:00:00 2001 From: chenos Date: Mon, 7 Dec 2020 17:21:14 +0800 Subject: [PATCH] feat: load the saved collection options --- packages/database/src/table.ts | 2 ++ .../src/models/collection.ts | 21 ++++++++++++++----- packages/plugin-collections/src/server.ts | 10 ++++++--- 3 files changed, 25 insertions(+), 8 deletions(-) diff --git a/packages/database/src/table.ts b/packages/database/src/table.ts index 9983b0243c..92167e7364 100644 --- a/packages/database/src/table.ts +++ b/packages/database/src/table.ts @@ -15,6 +15,7 @@ import { } from './fields'; import Database from './database'; import { Model, ModelCtor } from './model'; +import _ from 'lodash'; const registeredModels = new Map(); @@ -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, }; } diff --git a/packages/plugin-collections/src/models/collection.ts b/packages/plugin-collections/src/models/collection.ts index 2c7e011057..fe58f45593 100644 --- a/packages/plugin-collections/src/models/collection.ts +++ b/packages/plugin-collections/src/models/collection.ts @@ -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 { data = _.cloneDeep(data); const collection = await this.create({ diff --git a/packages/plugin-collections/src/server.ts b/packages/plugin-collections/src/server.ts index 5e9f9b4b5d..90383299ef 100644 --- a/packages/plugin-collections/src/server.ts +++ b/packages/plugin-collections/src/server.ts @@ -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) { + } }