feat: improve code

This commit is contained in:
chenos 2021-09-29 07:38:05 +08:00
parent 3120147586
commit 55f6564ea8
14 changed files with 103 additions and 31 deletions

View File

@ -35,9 +35,9 @@ const api = new Server({
}); });
const plugins = [ const plugins = [
'@nocobase/plugin-collections',
'@nocobase/plugin-ui-router', '@nocobase/plugin-ui-router',
'@nocobase/plugin-ui-schema', '@nocobase/plugin-ui-schema',
'@nocobase/plugin-collections',
'@nocobase/plugin-users', '@nocobase/plugin-users',
'@nocobase/plugin-action-logs', '@nocobase/plugin-action-logs',
'@nocobase/plugin-file-manager', '@nocobase/plugin-file-manager',

View File

@ -36,7 +36,7 @@
"@nocobase/plugin-ui-router": "^0.4.0-alpha.7", "@nocobase/plugin-ui-router": "^0.4.0-alpha.7",
"@nocobase/plugin-ui-schema": "^0.4.0-alpha.7", "@nocobase/plugin-ui-schema": "^0.4.0-alpha.7",
"@nocobase/plugin-users": "^0.4.0-alpha.7", "@nocobase/plugin-users": "^0.4.0-alpha.7",
"@nocobase/plugin-saas": "^0.4.0-alpha.7", "@nocobase/plugin-multi-apps": "^0.4.0-alpha.7",
"@nocobase/server": "^0.4.0-alpha.7", "@nocobase/server": "^0.4.0-alpha.7",
"@umijs/preset-react": "1.x", "@umijs/preset-react": "1.x",
"koa-mount": "^4.0.0", "koa-mount": "^4.0.0",

View File

@ -41,9 +41,9 @@ const api = new Server({
}); });
const plugins = [ const plugins = [
'@nocobase/plugin-saas', '@nocobase/plugin-multi-apps',
'@nocobase/plugin-ui-schema',
'@nocobase/plugin-ui-router', '@nocobase/plugin-ui-router',
'@nocobase/plugin-ui-schema',
'@nocobase/plugin-collections', '@nocobase/plugin-collections',
'@nocobase/plugin-users', '@nocobase/plugin-users',
'@nocobase/plugin-action-logs', '@nocobase/plugin-action-logs',

View File

@ -8,8 +8,9 @@ import {
AdminLayout, AdminLayout,
AuthLayout, AuthLayout,
RouteSchemaRenderer, RouteSchemaRenderer,
ConfigProvider,
ClientSDK,
} from '@nocobase/client'; } from '@nocobase/client';
import { UseRequestProvider } from 'ahooks';
import { extend } from 'umi-request'; import { extend } from 'umi-request';
const request = extend({ const request = extend({
@ -26,6 +27,8 @@ request.use(async (ctx, next) => {
await next(); await next();
}); });
const client = new ClientSDK({ request });
const RouteSwitch = createRouteSwitch({ const RouteSwitch = createRouteSwitch({
components: { components: {
AdminLayout, AdminLayout,
@ -52,12 +55,8 @@ const App = () => {
export default function IndexPage() { export default function IndexPage() {
return ( return (
<UseRequestProvider <ConfigProvider client={client}>
value={{
requestMethod: (service) => request(service),
}}
>
<App /> <App />
</UseRequestProvider> </ConfigProvider>
); );
} }

View File

@ -133,7 +133,15 @@ export class Database extends EventEmitter {
} }
async sync(options?: SyncOptions) { async sync(options?: SyncOptions) {
return this.sequelize.sync(options); const isMySQL = this.sequelize.getDialect() === 'mysql';
if (isMySQL) {
await this.sequelize.query('SET FOREIGN_KEY_CHECKS = 0', null);
}
const result = await this.sequelize.sync(options);
if (isMySQL) {
await this.sequelize.query('SET FOREIGN_KEY_CHECKS = 1', null);
}
return result;
} }
async close() { async close() {

View File

@ -465,6 +465,33 @@ type HookType =
return this.sequelize.close(); return this.sequelize.close();
} }
/**
* hook
*
* @param hookType
* @param fn
*/
public addHook(hookType: HookType | string, fn: Function) {
const hooks = this.hooks[hookType] || [];
hooks.push(fn);
this.hooks[hookType] = hooks;
}
/**
* hook
*
* @param hookType
* @param args
*/
public async runHooks(hookType: HookType | string, ...args) {
const hooks = this.hooks[hookType] || [];
for (const hook of hooks) {
if (typeof hook === 'function') {
await hook(...args);
}
}
}
public getFieldByPath(fieldPath: string) { public getFieldByPath(fieldPath: string) {
const [tableName, fieldName] = fieldPath.split('.'); const [tableName, fieldName] = fieldPath.split('.');
return this.getTable(tableName).getField(fieldName); return this.getTable(tableName).getField(fieldName);

View File

@ -534,8 +534,6 @@ export abstract class Model extends SequelizeModel {
...options, ...options,
transaction, transaction,
}); });
// @ts-ignore
// await this.sequelize.runHooks('afterUpdateAssociations', this, options);
if (!options.transaction) { if (!options.transaction) {
await transaction.commit(); await transaction.commit();

View File

@ -139,6 +139,7 @@ export class Table {
constructor(options: TableOptions, context: TabelContext) { constructor(options: TableOptions, context: TabelContext) {
const { database } = context; const { database } = context;
database.runHooks('beforeTableInit', options);
database.emit('beforeTableInit', options); database.emit('beforeTableInit', options);
const { const {
model, model,
@ -158,6 +159,7 @@ export class Table {
this.setFields(fields); this.setFields(fields);
this.initSortable(); this.initSortable();
database.emit('afterTableInit', this); database.emit('afterTableInit', this);
database.runHooks('afterTableInit', this);
} }
public initSortable() { public initSortable() {
@ -313,6 +315,7 @@ export class Table {
* @param reinitialize * @param reinitialize
*/ */
public addField(options: FieldOptions, reinitialize: Reinitialize = true) { public addField(options: FieldOptions, reinitialize: Reinitialize = true) {
this.database.runHooks('beforeAddField', options, this);
this.database.emit('beforeAddField', options, this); this.database.emit('beforeAddField', options, this);
const { name, index } = options; const { name, index } = options;
const field = buildField(options, { const field = buildField(options, {
@ -350,6 +353,7 @@ export class Table {
} }
this.modelInit(reinitialize); this.modelInit(reinitialize);
this.database.emit('afterAddField', field, this); this.database.emit('afterAddField', field, this);
this.database.runHooks('afterAddField', field, this);
return field; return field;
} }

View File

@ -5,31 +5,40 @@ import * as models from './models';
import { createOrUpdate, findAll } from './actions'; import { createOrUpdate, findAll } from './actions';
import { create } from './actions/fields'; import { create } from './actions/fields';
registerModels(models);
export default { export default {
name: 'collections', name: 'collections',
async load(this: Plugin) { async load(this: Plugin) {
const database = this.app.db; const database = this.app.db;
registerModels(models);
database.import({ database.import({
directory: path.resolve(__dirname, 'collections'), directory: path.resolve(__dirname, 'collections'),
}); });
this.app.on('beforeStart', async () => { this.app.on('beforeStart', async () => {
await database.getModel('collections').load(); await database.getModel('collections').load({
skipExisting: true,
});
}); });
this.app.on('db.init', async () => { this.app.on('db.init', async () => {
const userTable = database.getTable('users'); const tableNames = ['users', 'applications'];
const config = userTable.getOptions();
const Collection = database.getModel('collections'); const Collection = database.getModel('collections');
const collection = await Collection.create(config); for (const tableName of tableNames) {
await collection.updateAssociations({ const table = database.getTable(tableName);
generalFields: config.fields.filter((field) => field.state !== 0), console.log(tableName, table);
systemFields: config.fields.filter((field) => field.state === 0), if (!table) {
}); continue;
await collection.migrate(); }
const config = table.getOptions();
const collection = await Collection.create(config);
await collection.updateAssociations({
generalFields: config.fields.filter((field) => field.state !== 0),
systemFields: config.fields.filter((field) => field.state === 0),
});
// await collection.migrate();
}
}); });
const [Collection, Field] = database.getModels(['collections', 'fields']); const [Collection, Field] = database.getModels(['collections', 'fields']);

View File

@ -1,5 +1,5 @@
{ {
"name": "@nocobase/plugin-saas", "name": "@nocobase/plugin-multi-apps",
"version": "0.4.0-alpha.7", "version": "0.4.0-alpha.7",
"main": "lib/index.js", "main": "lib/index.js",
"license": "MIT", "license": "MIT",

View File

@ -31,6 +31,7 @@ function createApp(opts) {
}, },
}, },
}, },
// 不能再 bodyParser会卡死
bodyParser: false, bodyParser: false,
// dataWrapping: false, // dataWrapping: false,
resourcer: { resourcer: {
@ -40,9 +41,8 @@ function createApp(opts) {
const app = new Application(options); const app = new Application(options);
app.db.sequelize.beforeDefine((model, options) => { app.db.sequelize.beforeDefine((model, options) => {
options.tableName = `saas_${name}_${ options.tableName = `saas_${name}_${options.tableName || options.name.plural
options.tableName || options.name.plural }`;
}`;
}); });
app.resource({ app.resource({
@ -126,9 +126,19 @@ export default {
this.app['apps'] = new Map<string, Application>(); this.app['apps'] = new Map<string, Application>();
this.app.collection({ this.app.collection({
name: 'applications', name: 'applications',
title: '应用',
fields: [ fields: [
{ type: 'string', name: 'name', unique: true }, {
{ type: 'belongsTo', name: 'user' }, type: 'string',
name: 'name',
interface: 'string',
unique: true,
uiSchema: {
type: 'string',
title: '名称',
'x-component': 'Input',
},
},
], ],
}); });
this.app.use( this.app.use(
@ -138,6 +148,23 @@ export default {
}, },
}), }),
); );
this.app.db.on('applications.afterCreate', async (model) => {
const name = model.get('name');
const app = createApp({
name,
});
(async () => {
await app.load();
await app.db.sync({
force: true,
alter: {
drop: true,
},
});
await app.emitAsync('db.init');
await app.destroy();
})()
});
this.app this.app
.command('app:create') .command('app:create')
.argument('<appName>') .argument('<appName>')