fix(plugin-users): test errors

This commit is contained in:
chenos 2022-04-10 22:54:05 +08:00
parent 0fd41c9036
commit 6843bad133
4 changed files with 23 additions and 18 deletions

View File

@ -1,14 +1,16 @@
import Database from '@nocobase/database';
import PluginACL from '@nocobase/plugin-acl';
import UsersPlugin from '@nocobase/plugin-users';
import { mockServer, MockServer } from '@nocobase/test';
import { userPluginConfig } from './utils';
describe('createdBy/updatedBy', () => {
let api: MockServer;
let db: Database;
beforeEach(async () => {
api = mockServer();
api.plugin(require('../server').default, userPluginConfig);
api.plugin(UsersPlugin, userPluginConfig);
api.plugin(PluginACL);
await api.loadAndInstall();
db = api.db;
});

View File

@ -27,7 +27,7 @@ export function setCurrentRole(ctx) {
} else if (userRoles.length > 1) {
const role = userRoles.find((role) => role.name === currentRole);
if (!role) {
const defaultRole = userRoles.find((role) => role.rolesUsers?.default);
const defaultRole = userRoles.find((role) => role?.rolesUsers?.default);
currentRole = (defaultRole || userRoles[0])?.name;
}
}

View File

@ -7,10 +7,14 @@ export class UserModel extends Model {
}
const db = (this.constructor as any).database as Database;
const repository = db.getRepository('rolesUsers');
if (!repository) {
return false;
}
const transaction = options.transaction || (await db.sequelize.transaction());
try {
await db.getRepository('rolesUsers').update({
await repository.update({
filter: {
userId: this.get('id'),
},
@ -19,8 +23,7 @@ export class UserModel extends Model {
},
transaction,
});
await db.getRepository('rolesUsers').update({
await repository.update({
filter: {
userId: this.get('id'),
roleName,

View File

@ -28,19 +28,19 @@ export default class UsersPlugin extends Plugin<UserPluginConfig> {
this.db.registerModels({ UserModel });
this.db.on('users.afterCreateWithAssociations', async (model, options) => {
const { transaction } = options;
if (this.app.db.getCollection('roles')) {
const defaultRole = await this.app.db.getRepository('roles').findOne({
const repository = this.app.db.getRepository('roles');
if (!repository) {
return;
}
const defaultRole = await repository.findOne({
filter: {
default: true,
},
transaction,
});
if (defaultRole && (await model.countRoles({ transaction })) == 0) {
await model.addRoles(defaultRole, { transaction });
}
}
});
this.db.on('afterDefineCollection', (collection: Collection) => {