diff --git a/packages/plugins/@nocobase/plugin-data-source-main/src/server/__tests__/collections.repository.test.ts b/packages/plugins/@nocobase/plugin-data-source-main/src/server/__tests__/collections.repository.test.ts index 1650391393..d3438dd40c 100644 --- a/packages/plugins/@nocobase/plugin-data-source-main/src/server/__tests__/collections.repository.test.ts +++ b/packages/plugins/@nocobase/plugin-data-source-main/src/server/__tests__/collections.repository.test.ts @@ -31,6 +31,40 @@ describe('collections repository', () => { await app.destroy(); }); + it('should not create collection already exists', async () => { + db.collection({ + name: 'jobs', + fields: [ + { + type: 'string', + name: 'title', + }, + ], + }); + + await db.sync(); + + let err; + + try { + await Collection.repository.create({ + values: { + name: 'jobs', + fields: [ + { + type: 'string', + name: 'title', + }, + ], + }, + }); + } catch (e) { + err = e; + } + + expect(err).toBeTruthy(); + }); + it('should load through table with foreignKey', async () => { await Collection.repository.create({ values: { diff --git a/packages/plugins/@nocobase/plugin-data-source-main/src/server/server.ts b/packages/plugins/@nocobase/plugin-data-source-main/src/server/server.ts index c1d7ef384e..82816ced7e 100644 --- a/packages/plugins/@nocobase/plugin-data-source-main/src/server/server.ts +++ b/packages/plugins/@nocobase/plugin-data-source-main/src/server/server.ts @@ -91,6 +91,12 @@ export class PluginDataSourceMainServer extends Plugin { this.app.db.on('collections.beforeCreate', beforeCreateForViewCollection(this.db)); + this.app.db.on('collections.beforeCreate', async (model: CollectionModel, options) => { + if (this.app.db.getCollection(model.get('name')) && model.get('from') !== 'db2cm' && !model.get('isThrough')) { + throw new Error(`Collection named ${model.get('name')} already exists`); + } + }); + this.app.db.on( 'collections.afterSaveWithAssociations', async (model: CollectionModel, { context, transaction }) => {