fix(database): find model in hooks (#4694)

* chore: test

* fix(database): find model in hooks
This commit is contained in:
ChengLei Shao 2024-06-18 15:31:45 +08:00 committed by GitHub
parent 3838793c50
commit 06e166f8da
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
4 changed files with 75 additions and 8 deletions

View File

@ -0,0 +1,67 @@
/**
* This file is part of the NocoBase (R) project.
* Copyright (c) 2020-2024 NocoBase Co., Ltd.
* Authors: NocoBase Team.
*
* This project is dual-licensed under AGPL-3.0 and NocoBase Commercial License.
* For more information, please refer to: https://www.nocobase.com/agreement.
*/
import { Database } from '../../database';
import { mockDatabase } from '../';
describe('hook', () => {
let db: Database;
beforeEach(async () => {
db = mockDatabase();
await db.clean({ drop: true });
});
afterEach(async () => {
await db.close();
});
it('should get hook modelName', async () => {
const Posts = db.collection({
name: 'posts',
fields: [
{
type: 'string',
name: 'title',
},
],
});
expect(Posts.model.options.modelName).toBe('posts');
const Tags = db.collection({
name: 'tags',
fields: [
{
type: 'string',
name: 'name',
},
],
});
Posts.setField('tags', {
type: 'belongsToMany',
target: 'tags',
through: 'post',
});
await db.sync();
const throughCollection = db.getCollection('post');
throughCollection.setField('test', { type: 'string' });
const callback = vi.fn();
db.on('post.afterSync', (options) => {
callback(options);
});
await throughCollection.sync();
expect(callback).toHaveBeenCalledOnce();
});
});

View File

@ -243,6 +243,8 @@ export class Collection<
this.model = class extends M {};
this.model.init(null, this.sequelizeModelOptions());
this.model.options.modelName = this.options.name;
if (!autoGenId) {
this.model.removeAttribute('id');
}

View File

@ -50,7 +50,8 @@ export class SortField extends Field {
}
};
initRecordsSortValue = async ({ transaction }) => {
initRecordsSortValue = async (options) => {
const { transaction } = options;
const orderField = (() => {
const model = this.collection.model;

View File

@ -44,13 +44,10 @@ export class ModelHook {
if (arg['model']) {
return arg['model'].name;
}
const plural = arg?.name?.plural;
if (this.database.sequelize.isDefined(plural)) {
return plural;
}
const singular = arg?.name?.singular;
if (this.database.sequelize.isDefined(singular)) {
return singular;
const modelName = arg['modelName'];
if (this.database.sequelize.isDefined(modelName)) {
return modelName;
}
}
}