refactor(core): Continue moving typeorm operators to repositories (no-changelog) (#8186)

Follow-up to: #8163
This commit is contained in:
Iván Ovejero
2024-01-02 17:53:24 +01:00
committed by GitHub
parent 0ca2759d75
commit 40c1eeeddd
35 changed files with 341 additions and 354 deletions

View File

@@ -138,7 +138,7 @@ export class AuthController {
}
try {
user = await this.userService.findOneOrFail({ where: {} });
user = await this.userRepository.findOneOrFail({ where: {}, relations: ['globalRole'] });
} catch (error) {
throw new InternalServerError(
'No users found in database - did you wipe the users table? Create at least one user.',

View File

@@ -163,7 +163,7 @@ export class InvitationController {
invitee.lastName = lastName;
invitee.password = await this.passwordUtility.hash(validPassword);
const updatedUser = await this.userService.save(invitee);
const updatedUser = await this.userRepository.save(invitee);
await issueCookie(res, updatedUser);

View File

@@ -20,6 +20,7 @@ import { Logger } from '@/Logger';
import { ExternalHooks } from '@/ExternalHooks';
import { InternalHooks } from '@/InternalHooks';
import { BadRequestError } from '@/errors/response-errors/bad-request.error';
import { UserRepository } from '@/databases/repositories/user.repository';
@Authorized()
@RestController('/me')
@@ -30,6 +31,7 @@ export class MeController {
private readonly internalHooks: InternalHooks,
private readonly userService: UserService,
private readonly passwordUtility: PasswordUtility,
private readonly userRepository: UserRepository,
) {}
/**
@@ -76,7 +78,10 @@ export class MeController {
await this.externalHooks.run('user.profile.beforeUpdate', [userId, currentEmail, payload]);
await this.userService.update(userId, payload);
const user = await this.userService.findOneOrFail({ where: { id: userId } });
const user = await this.userRepository.findOneOrFail({
where: { id: userId },
relations: ['globalRole'],
});
this.logger.info('User updated successfully', { userId });
@@ -132,7 +137,7 @@ export class MeController {
req.user.password = await this.passwordUtility.hash(validPassword);
const user = await this.userService.save(req.user);
const user = await this.userRepository.save(req.user);
this.logger.info('Password updated successfully', { userId: user.id });
await issueCookie(res, user);
@@ -164,7 +169,7 @@ export class MeController {
throw new BadRequestError('Personalization answers are mandatory');
}
await this.userService.save({
await this.userRepository.save({
id: req.user.id,
// @ts-ignore
personalizationAnswers,
@@ -227,9 +232,10 @@ export class MeController {
await this.userService.updateSettings(id, payload);
const user = await this.userService.findOneOrFail({
const user = await this.userRepository.findOneOrFail({
select: ['settings'],
where: { id },
relations: ['globalRole'],
});
return user.settings;

View File

@@ -13,6 +13,7 @@ import { UserService } from '@/services/user.service';
import { Logger } from '@/Logger';
import { BadRequestError } from '@/errors/response-errors/bad-request.error';
import { InternalHooks } from '@/InternalHooks';
import { UserRepository } from '@/databases/repositories/user.repository';
@Authorized(['global', 'owner'])
@RestController('/owner')
@@ -24,6 +25,7 @@ export class OwnerController {
private readonly userService: UserService,
private readonly passwordUtility: PasswordUtility,
private readonly postHog: PostHogClient,
private readonly userRepository: UserRepository,
) {}
/**
@@ -85,7 +87,7 @@ export class OwnerController {
await validateEntity(owner);
owner = await this.userService.save(owner);
owner = await this.userRepository.save(owner);
this.logger.info('Owner was set up successfully', { userId });

View File

@@ -1,6 +1,5 @@
import { Response } from 'express';
import { rateLimit } from 'express-rate-limit';
import { IsNull, Not } from 'typeorm';
import validator from 'validator';
import { Get, Post, RestController } from '@/decorators';
@@ -23,6 +22,7 @@ import { BadRequestError } from '@/errors/response-errors/bad-request.error';
import { UnauthorizedError } from '@/errors/response-errors/unauthorized.error';
import { NotFoundError } from '@/errors/response-errors/not-found.error';
import { UnprocessableRequestError } from '@/errors/response-errors/unprocessable.error';
import { UserRepository } from '@/databases/repositories/user.repository';
const throttle = rateLimit({
windowMs: 5 * 60 * 1000, // 5 minutes
@@ -42,6 +42,7 @@ export class PasswordResetController {
private readonly urlService: UrlService,
private readonly license: License,
private readonly passwordUtility: PasswordUtility,
private readonly userRepository: UserRepository,
) {}
/**
@@ -78,13 +79,7 @@ export class PasswordResetController {
}
// User should just be able to reset password if one is already present
const user = await this.userService.findOne({
where: {
email,
password: Not(IsNull()),
},
relations: ['authIdentities', 'globalRole'],
});
const user = await this.userRepository.findNonShellUser(email);
if (!user?.isOwner && !this.license.isWithinUsersLimit()) {
this.logger.debug(

View File

@@ -1,5 +1,4 @@
import type { FindManyOptions } from 'typeorm';
import { In, Not } from 'typeorm';
import { In } from 'typeorm';
import { User } from '@db/entities/User';
import { SharedCredentials } from '@db/entities/SharedCredentials';
import { SharedWorkflow } from '@db/entities/SharedWorkflow';
@@ -21,6 +20,7 @@ import { BadRequestError } from '@/errors/response-errors/bad-request.error';
import { License } from '@/License';
import { ExternalHooks } from '@/ExternalHooks';
import { InternalHooks } from '@/InternalHooks';
import { UserRepository } from '@/databases/repositories/user.repository';
@Authorized()
@RestController('/users')
@@ -35,6 +35,7 @@ export class UsersController {
private readonly roleService: RoleService,
private readonly userService: UserService,
private readonly license: License,
private readonly userRepository: UserRepository,
) {}
static ERROR_MESSAGES = {
@@ -49,44 +50,6 @@ export class UsersController {
},
} as const;
private async toFindManyOptions(listQueryOptions?: ListQuery.Options) {
const findManyOptions: FindManyOptions<User> = {};
if (!listQueryOptions) {
findManyOptions.relations = ['globalRole', 'authIdentities'];
return findManyOptions;
}
const { filter, select, take, skip } = listQueryOptions;
if (select) findManyOptions.select = select;
if (take) findManyOptions.take = take;
if (skip) findManyOptions.skip = skip;
if (take && !select) {
findManyOptions.relations = ['globalRole', 'authIdentities'];
}
if (take && select && !select?.id) {
findManyOptions.select = { ...findManyOptions.select, id: true }; // pagination requires id
}
if (filter) {
const { isOwner, ...otherFilters } = filter;
findManyOptions.where = otherFilters;
if (isOwner !== undefined) {
const ownerRole = await this.roleService.findGlobalOwnerRole();
findManyOptions.relations = ['globalRole'];
findManyOptions.where.globalRole = { id: isOwner ? ownerRole.id : Not(ownerRole.id) };
}
}
return findManyOptions;
}
private removeSupplementaryFields(
publicUsers: Array<Partial<PublicUser>>,
listQueryOptions: ListQuery.Options,
@@ -122,9 +85,14 @@ export class UsersController {
async listUsers(req: ListQuery.Request) {
const { listQueryOptions } = req;
const findManyOptions = await this.toFindManyOptions(listQueryOptions);
const globalOwner = await this.roleService.findGlobalOwnerRole();
const users = await this.userService.findMany(findManyOptions);
const findManyOptions = await this.userRepository.toFindManyOptions(
listQueryOptions,
globalOwner.id,
);
const users = await this.userRepository.find(findManyOptions);
const publicUsers: Array<Partial<PublicUser>> = await Promise.all(
users.map(async (u) =>
@@ -140,8 +108,9 @@ export class UsersController {
@Get('/:id/password-reset-link')
@RequireGlobalScope('user:resetPassword')
async getUserPasswordResetLink(req: UserRequest.PasswordResetLink) {
const user = await this.userService.findOneOrFail({
const user = await this.userRepository.findOneOrFail({
where: { id: req.params.id },
relations: ['globalRole'],
});
if (!user) {
throw new NotFoundError('User not found');
@@ -160,9 +129,10 @@ export class UsersController {
await this.userService.updateSettings(id, payload);
const user = await this.userService.findOneOrFail({
const user = await this.userRepository.findOneOrFail({
select: ['settings'],
where: { id },
relations: ['globalRole'],
});
return user.settings;
@@ -192,10 +162,9 @@ export class UsersController {
);
}
const users = await this.userService.findMany({
where: { id: In([transferId, idToDelete]) },
relations: ['globalRole'],
});
const userIds = transferId ? [transferId, idToDelete] : [idToDelete];
const users = await this.userRepository.findManybyIds(userIds);
if (!users.length || (transferId && users.length !== 2)) {
throw new NotFoundError(
@@ -354,8 +323,9 @@ export class UsersController {
throw new UnauthorizedError(NO_USER_TO_OWNER);
}
const targetUser = await this.userService.findOne({
const targetUser = await this.userRepository.findOne({
where: { id: req.params.id },
relations: ['globalRole'],
});
if (targetUser === null) {