Remove non-null assertions for Db collections (#3111)

* 📘 Remove unions to `null`

*  Track `Db` initialization state

* 🔥 Remove non-null assertions

* 👕 Remove lint exceptions

* 🔥 Remove leftover assertion
This commit is contained in:
Iván Ovejero
2022-04-14 09:02:12 +02:00
committed by GitHub
parent e45ac7eb6a
commit 3e5d981f3f
31 changed files with 130 additions and 152 deletions

View File

@@ -15,7 +15,7 @@ import * as config from '../../config';
import { getWebhookBaseUrl } from '../WebhookHelpers';
export async function getWorkflowOwner(workflowId: string | number): Promise<User> {
const sharedWorkflow = await Db.collections.SharedWorkflow!.findOneOrFail({
const sharedWorkflow = await Db.collections.SharedWorkflow.findOneOrFail({
where: { workflow: { id: workflowId } },
relations: ['user', 'user.globalRole'],
});
@@ -33,7 +33,7 @@ export function isEmailSetUp(): boolean {
}
async function getInstanceOwnerRole(): Promise<Role> {
const ownerRole = await Db.collections.Role!.findOneOrFail({
const ownerRole = await Db.collections.Role.findOneOrFail({
where: {
name: 'owner',
scope: 'global',
@@ -45,7 +45,7 @@ async function getInstanceOwnerRole(): Promise<Role> {
export async function getInstanceOwner(): Promise<User> {
const ownerRole = await getInstanceOwnerRole();
const owner = await Db.collections.User!.findOneOrFail({
const owner = await Db.collections.User.findOneOrFail({
relations: ['globalRole'],
where: {
globalRole: ownerRole,
@@ -121,7 +121,7 @@ export function sanitizeUser(user: User, withoutKeys?: string[]): PublicUser {
}
export async function getUserById(userId: string): Promise<User> {
const user = await Db.collections.User!.findOneOrFail(userId, {
const user = await Db.collections.User.findOneOrFail(userId, {
relations: ['globalRole'],
});
return user;
@@ -174,7 +174,7 @@ export async function checkPermissionsForExecution(
}
// Check for the user's permission to all used credentials
const credentialCount = await Db.collections.SharedCredentials!.count({
const credentialCount = await Db.collections.SharedCredentials.count({
where: {
user: { id: userId },
credentials: In(ids),

View File

@@ -37,7 +37,7 @@ export function issueJWT(user: User): JwtToken {
}
export async function resolveJwtContent(jwtPayload: JwtPayload): Promise<User> {
const user = await Db.collections.User!.findOne(jwtPayload.id, {
const user = await Db.collections.User.findOne(jwtPayload.id, {
relations: ['globalRole'],
});

View File

@@ -60,7 +60,6 @@ export class UserManagementMailer {
let template = await getTemplate('invite', 'invite.html');
template = replaceStrings(template, inviteEmailData);
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
const result = await this.mailer?.sendMail({
emailRecipients: inviteEmailData.email,
subject: 'You have been invited to n8n',

View File

@@ -1,6 +1,5 @@
/* eslint-disable @typescript-eslint/naming-convention */
/* eslint-disable import/no-cycle */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable @typescript-eslint/no-unsafe-member-access */
import { Request, Response } from 'express';
import { IDataObject } from 'n8n-workflow';
@@ -32,7 +31,7 @@ export function authenticationMethods(this: N8nApp): void {
let user;
try {
user = await Db.collections.User!.findOne(
user = await Db.collections.User.findOne(
{
email: req.body.email,
},
@@ -91,7 +90,7 @@ export function authenticationMethods(this: N8nApp): void {
}
try {
user = await Db.collections.User!.findOneOrFail({ relations: ['globalRole'] });
user = await Db.collections.User.findOneOrFail({ relations: ['globalRole'] });
} catch (error) {
throw new Error(
'No users found in database - did you wipe the users table? Create at least one user.',

View File

@@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/no-non-null-assertion */
/* eslint-disable import/no-cycle */
import express from 'express';
@@ -53,7 +52,7 @@ export function meNamespace(this: N8nApp): void {
await validateEntity(newUser);
const user = await Db.collections.User!.save(newUser);
const user = await Db.collections.User.save(newUser);
Logger.info('User updated successfully', { userId: user.id });
@@ -99,7 +98,7 @@ export function meNamespace(this: N8nApp): void {
req.user.password = await hashPassword(validPassword);
const user = await Db.collections.User!.save(req.user);
const user = await Db.collections.User.save(req.user);
Logger.info('Password updated successfully', { userId: user.id });
await issueCookie(res, user);
@@ -135,7 +134,7 @@ export function meNamespace(this: N8nApp): void {
);
}
await Db.collections.User!.save({
await Db.collections.User.save({
id: req.user.id,
personalizationAnswers,
});

View File

@@ -55,7 +55,7 @@ export function ownerNamespace(this: N8nApp): void {
);
}
let owner = await Db.collections.User!.findOne(userId, {
let owner = await Db.collections.User.findOne(userId, {
relations: ['globalRole'],
});
@@ -78,11 +78,11 @@ export function ownerNamespace(this: N8nApp): void {
await validateEntity(owner);
owner = await Db.collections.User!.save(owner);
owner = await Db.collections.User.save(owner);
Logger.info('Owner was set up successfully', { userId: req.user.id });
await Db.collections.Settings!.update(
await Db.collections.Settings.update(
{ key: 'userManagement.isInstanceOwnerSetUp' },
{ value: JSON.stringify(true) },
);
@@ -108,7 +108,7 @@ export function ownerNamespace(this: N8nApp): void {
`/${this.restEndpoint}/owner/skip-setup`,
// eslint-disable-next-line @typescript-eslint/naming-convention
ResponseHelper.send(async (_req: AuthenticatedRequest, _res: express.Response) => {
await Db.collections.Settings!.update(
await Db.collections.Settings.update(
{ key: 'userManagement.skipInstanceOwnerSetup' },
{ value: JSON.stringify(true) },
);

View File

@@ -53,7 +53,7 @@ export function passwordResetNamespace(this: N8nApp): void {
}
// User should just be able to reset password if one is already present
const user = await Db.collections.User!.findOne({ email, password: Not(IsNull()) });
const user = await Db.collections.User.findOne({ email, password: Not(IsNull()) });
if (!user || !user.password) {
Logger.debug(
@@ -69,7 +69,7 @@ export function passwordResetNamespace(this: N8nApp): void {
const resetPasswordTokenExpiration = Math.floor(Date.now() / 1000) + 7200;
await Db.collections.User!.update(id, { resetPasswordToken, resetPasswordTokenExpiration });
await Db.collections.User.update(id, { resetPasswordToken, resetPasswordTokenExpiration });
const baseUrl = getInstanceBaseUrl();
const url = new URL(`${baseUrl}/change-password`);
@@ -134,7 +134,7 @@ export function passwordResetNamespace(this: N8nApp): void {
// Timestamp is saved in seconds
const currentTimestamp = Math.floor(Date.now() / 1000);
const user = await Db.collections.User!.findOne({
const user = await Db.collections.User.findOne({
id,
resetPasswordToken,
resetPasswordTokenExpiration: MoreThanOrEqual(currentTimestamp),
@@ -187,7 +187,7 @@ export function passwordResetNamespace(this: N8nApp): void {
// Timestamp is saved in seconds
const currentTimestamp = Math.floor(Date.now() / 1000);
const user = await Db.collections.User!.findOne({
const user = await Db.collections.User.findOne({
id: userId,
resetPasswordToken,
resetPasswordTokenExpiration: MoreThanOrEqual(currentTimestamp),
@@ -204,7 +204,7 @@ export function passwordResetNamespace(this: N8nApp): void {
throw new ResponseHelper.ResponseError('', undefined, 404);
}
await Db.collections.User!.update(userId, {
await Db.collections.User.update(userId, {
password: await hashPassword(validPassword),
resetPasswordToken: null,
resetPasswordTokenExpiration: null,

View File

@@ -1,6 +1,5 @@
/* eslint-disable no-restricted-syntax */
/* eslint-disable import/no-cycle */
/* eslint-disable @typescript-eslint/no-non-null-assertion */
import { Response } from 'express';
import { In } from 'typeorm';
import validator from 'validator';
@@ -108,7 +107,7 @@ export function usersNamespace(this: N8nApp): void {
createUsers[invite.email] = null;
});
const role = await Db.collections.Role!.findOne({ scope: 'global', name: 'member' });
const role = await Db.collections.Role.findOne({ scope: 'global', name: 'member' });
if (!role) {
Logger.error(
@@ -122,7 +121,7 @@ export function usersNamespace(this: N8nApp): void {
}
// remove/exclude existing users from creation
const existingUsers = await Db.collections.User!.find({
const existingUsers = await Db.collections.User.find({
where: { email: In(Object.keys(createUsers)) },
});
existingUsers.forEach((user) => {
@@ -190,6 +189,7 @@ export function usersNamespace(this: N8nApp): void {
};
if (result?.success) {
void InternalHooksManager.getInstance().onUserTransactionalEmail({
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
user_id: id!,
message_type: 'New user invite',
});
@@ -249,7 +249,7 @@ export function usersNamespace(this: N8nApp): void {
}
}
const users = await Db.collections.User!.find({ where: { id: In([inviterId, inviteeId]) } });
const users = await Db.collections.User.find({ where: { id: In([inviterId, inviteeId]) } });
if (users.length !== 2) {
Logger.debug(
@@ -317,7 +317,7 @@ export function usersNamespace(this: N8nApp): void {
const validPassword = validatePassword(password);
const users = await Db.collections.User!.find({
const users = await Db.collections.User.find({
where: { id: In([inviterId, inviteeId]) },
relations: ['globalRole'],
});
@@ -351,7 +351,7 @@ export function usersNamespace(this: N8nApp): void {
invitee.lastName = lastName;
invitee.password = await hashPassword(validPassword);
const updatedUser = await Db.collections.User!.save(invitee);
const updatedUser = await Db.collections.User.save(invitee);
await issueCookie(res, updatedUser);
@@ -366,7 +366,7 @@ export function usersNamespace(this: N8nApp): void {
this.app.get(
`/${this.restEndpoint}/users`,
ResponseHelper.send(async () => {
const users = await Db.collections.User!.find({ relations: ['globalRole'] });
const users = await Db.collections.User.find({ relations: ['globalRole'] });
return users.map((user): PublicUser => sanitizeUser(user, ['personalizationAnswers']));
}),
@@ -398,7 +398,7 @@ export function usersNamespace(this: N8nApp): void {
);
}
const users = await Db.collections.User!.find({
const users = await Db.collections.User.find({
where: { id: In([transferId, idToDelete]) },
});
@@ -432,11 +432,11 @@ export function usersNamespace(this: N8nApp): void {
}
const [ownedSharedWorkflows, ownedSharedCredentials] = await Promise.all([
Db.collections.SharedWorkflow!.find({
Db.collections.SharedWorkflow.find({
relations: ['workflow'],
where: { user: userToDelete },
}),
Db.collections.SharedCredentials!.find({
Db.collections.SharedCredentials.find({
relations: ['credentials'],
where: { user: userToDelete },
}),
@@ -494,7 +494,7 @@ export function usersNamespace(this: N8nApp): void {
);
}
const reinvitee = await Db.collections.User!.findOne({ id: idToReinvite });
const reinvitee = await Db.collections.User.findOne({ id: idToReinvite });
if (!reinvitee) {
Logger.debug(