nocobase/packages/plugin-pages/src/server.ts

80 lines
2.2 KiB
TypeScript
Raw Normal View History

import path from 'path';
import Database from '@nocobase/database';
import Resourcer from '@nocobase/resourcer';
2020-11-11 12:57:18 +00:00
import getCollection from './actions/getCollection';
import getView from './actions/getView';
import getRoutes from './actions/getRoutes';
import getPageInfo from './actions/getPageInfo';
export default async function (options = {}) {
const database: Database = this.database;
const resourcer: Resourcer = this.resourcer;
2020-11-11 12:57:18 +00:00
database.import({
directory: path.resolve(__dirname, 'collections'),
});
resourcer.registerActionHandler('getCollection', getCollection);
resourcer.registerActionHandler('getView', getView);
resourcer.registerActionHandler('getPageInfo', getPageInfo);
resourcer.registerActionHandler('pages:getRoutes', getRoutes);
2020-12-07 09:25:36 +00:00
const [Collection, Page] = database.getModels(['collections', 'pages']);
2020-12-12 08:36:02 +00:00
async function createCollectionPage(model, options) {
// const {
// transaction = await database.sequelize.transaction(),
// } = options;
if (model.get('internal')) {
return;
}
2020-12-12 08:36:02 +00:00
const transaction = await database.sequelize.transaction();
2020-12-07 09:25:36 +00:00
const parent = await Page.findOne({
2020-12-12 08:36:02 +00:00
transaction,
2020-12-07 09:25:36 +00:00
where: {
path: '/collections',
}
});
let page = await Page.findOne({
2020-12-12 08:36:02 +00:00
transaction,
2020-12-07 09:25:36 +00:00
where: {
collection: model.get('name'),
path: `/collections/${model.get('name')}`,
},
});
if (!page) {
page = await Page.create({
type: 'collection',
collection: model.get('name'),
path: `/collections/${model.get('name')}`,
sort: 100,
parent_id: parent.id,
2020-12-12 08:36:02 +00:00
}, {
transaction,
2020-12-07 09:25:36 +00:00
});
}
page.set({
title: model.get('title'),
icon: model.get('icon'),
2020-12-10 12:32:44 +00:00
showInMenu: !!model.get('showInDataMenu'),
2020-12-07 09:25:36 +00:00
});
2020-12-12 08:36:02 +00:00
await page.save({
transaction,
});
await transaction.commit();
2020-12-07 09:25:36 +00:00
}
Collection.addHook('afterCreate', createCollectionPage);
Collection.addHook('afterUpdate', createCollectionPage);
2020-12-12 08:36:02 +00:00
Collection.addHook('afterDestroy', async (model, options) => {
const { transaction } = options;
console.log('afterDestroy', model);
await Page.destroy({
transaction,
where: {
path: `/collections/${model.get('name')}`,
},
});
});
}