refactor(core): Delete duplicate code across all commands (#5452)

This commit is contained in:
कारतोफ्फेलस्क्रिप्ट™
2023-02-10 14:59:20 +01:00
committed by GitHub
parent 8494c97821
commit 5194513850
26 changed files with 979 additions and 1345 deletions

View File

@@ -1,10 +1,21 @@
import { Not } from 'typeorm';
import * as Db from '@/Db';
import type { CredentialsEntity } from '@db/entities/CredentialsEntity';
import { User } from '@db/entities/User';
import { BaseCommand } from '../BaseCommand';
const defaultUserProps = {
firstName: null,
lastName: null,
email: null,
password: null,
resetPasswordToken: null,
};
export class Reset extends BaseCommand {
static description = '\nResets the database to the default user state';
static description = 'Resets the database to the default user state';
static examples = ['$ n8n user-management:reset'];
async run(): Promise<void> {
const owner = await this.getInstanceOwner();
@@ -30,7 +41,7 @@ export class Reset extends BaseCommand {
);
await Db.collections.User.delete({ id: Not(owner.id) });
await Db.collections.User.save(Object.assign(owner, this.defaultUserProps));
await Db.collections.User.save(Object.assign(owner, defaultUserProps));
const danglingCredentials: CredentialsEntity[] =
(await Db.collections.Credentials.createQueryBuilder('credentials')
@@ -58,6 +69,25 @@ export class Reset extends BaseCommand {
this.logger.info('Successfully reset the database to default user state.');
}
async getInstanceOwner(): Promise<User> {
const globalRole = await Db.collections.Role.findOneByOrFail({
name: 'owner',
scope: 'global',
});
const owner = await Db.collections.User.findOneBy({ globalRoleId: globalRole.id });
if (owner) return owner;
const user = new User();
Object.assign(user, { ...defaultUserProps, globalRole });
await Db.collections.User.save(user);
return Db.collections.User.findOneByOrFail({ globalRoleId: globalRole.id });
}
async catch(error: Error): Promise<void> {
this.logger.error('Error resetting database. See log messages for details.');
this.logger.error(error.message);