diff --git a/packages/plugin-collections/src/hooks/generateName.ts b/packages/plugin-collections/src/hooks/generateName.ts new file mode 100644 index 000000000..9e9f47cc2 --- /dev/null +++ b/packages/plugin-collections/src/hooks/generateName.ts @@ -0,0 +1,5 @@ +import { BaseModel } from '../models'; + +export default async function (model: BaseModel) { + model.generateNameIfNull(); +} diff --git a/packages/plugin-collections/src/hooks/index.ts b/packages/plugin-collections/src/hooks/index.ts index d6f1b98e6..bbb882a22 100644 --- a/packages/plugin-collections/src/hooks/index.ts +++ b/packages/plugin-collections/src/hooks/index.ts @@ -3,6 +3,7 @@ import collectionsAfterCreate from './collections-after-create'; import fieldsBeforeValidate from './fields-before-validate'; import fieldsAfterCreate from './fields-after-create'; +import generateName from './generateName'; export default { collections: { @@ -12,5 +13,14 @@ export default { fields: { beforeValidate: fieldsBeforeValidate, afterCreate: fieldsAfterCreate - } + }, + actions: { + beforeValidate: generateName + }, + views: { + beforeValidate: generateName + }, + tabs: { + beforeValidate: generateName + }, }; diff --git a/packages/plugin-collections/src/models/base.ts b/packages/plugin-collections/src/models/base.ts index ab4ae6b42..d861d8874 100644 --- a/packages/plugin-collections/src/models/base.ts +++ b/packages/plugin-collections/src/models/base.ts @@ -2,8 +2,22 @@ import _ from 'lodash'; import { getDataTypeKey, Model } from '@nocobase/database'; import { Utils } from 'sequelize'; +export function generateName(title?: string): string { + return `${Math.random().toString(36).replace('0.', '').slice(-4).padStart(4, '0')}`; +} + export class BaseModel extends Model { + generateName() { + this.set('name', generateName()); + } + + generateNameIfNull() { + if (!this.get('name')) { + this.generateName(); + } + } + get additionalAttribute() { const tableOptions = this.database.getTable(this.constructor.name).getOptions(); return _.get(tableOptions, 'additionalAttribute') || 'options';