chore(collection-manager): Throw an error when the value of foreignKey is the same as otherKey (#2780)

* chore(collection-manager): throw an error when the value of foreignKey is the same as otherKey

* fix: test
This commit is contained in:
ChengLei Shao 2023-10-10 12:05:53 +08:00 committed by GitHub
parent bccec4385a
commit d7664c9a41
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 50 additions and 0 deletions

View File

@ -34,6 +34,44 @@ describe('belongsToMany', () => {
await app.destroy();
});
it('should throw error when through table foreign keys are same name', async () => {
await Collection.repository.create({
values: {
name: 'A',
},
context: {},
});
await Collection.repository.create({
values: {
name: 'B',
},
context: {},
});
let error;
try {
await Field.repository.create({
values: {
name: 'bs',
type: 'belongsToMany',
collectionName: 'A',
target: 'B',
sourceKey: 'id',
targetKey: 'id',
foreignKey: 'a_id',
otherKey: 'a_id',
},
context: {},
});
} catch (e) {
error = e;
}
expect(error).toBeDefined();
});
it('should define belongs to many when change alias name', async () => {
await Collection.repository.create({
values: {

View File

@ -0,0 +1,9 @@
export function beforeCreateForValidateField() {
return async (model, { transaction }) => {
if (model.type === 'belongsToMany') {
if (model.get('foreignKey') === model.get('otherKey')) {
throw new Error('foreignKey and otherKey can not be the same');
}
}
};
}

View File

@ -18,6 +18,7 @@ import { CollectionModel, FieldModel } from './models';
import collectionActions from './resourcers/collections';
import viewResourcer from './resourcers/views';
import sqlResourcer from './resourcers/sql';
import { beforeCreateForValidateField } from './hooks/beforeCreateForValidateField';
export class CollectionManagerPlugin extends Plugin {
public schema: string;
@ -110,6 +111,8 @@ export class CollectionManagerPlugin extends Plugin {
}
});
this.app.db.on('fields.beforeCreate', beforeCreateForValidateField());
this.app.db.on('fields.afterCreate', afterCreateForReverseField(this.app.db));
this.app.db.on('fields.afterCreate', async (model: FieldModel, { context, transaction }) => {