Skip to content

Commit

Permalink
Chore: refactor/tsc-perf (#26040)
Browse files Browse the repository at this point in the history
Co-authored-by: Guilherme Gazzo <guilherme@gazzo.xyz>
Co-authored-by: Pierre Lehnen <pierre.lehnen@rocket.chat>
Co-authored-by: Guilherme Gazzo <guilhermegazzo@gmail.com>
  • Loading branch information
4 people committed Jul 2, 2022
1 parent 12c1cf6 commit 3427e5e
Show file tree
Hide file tree
Showing 121 changed files with 673 additions and 1,815 deletions.
5 changes: 3 additions & 2 deletions apps/meteor/app/2fa/server/functions/resetTOTP.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,10 @@ const sendResetNotification = async function (uid: string): Promise<void> {
html,
} as any);
} catch (error) {
throw new Meteor.Error('error-email-send-failed', `Error trying to send email: ${error.message}`, {
const message = error instanceof Error ? error.message : String(error);
throw new Meteor.Error('error-email-send-failed', `Error trying to send email: ${message}`, {
function: 'resetUserTOTP',
message: error.message,
message,
});
}
});
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/action-links/server/lib/actionLinks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ function getMessageById(messageId: IMessage['_id']): IMessage | undefined {
}
return Promise.await(getMessageForUser(messageId, user));
} catch (e) {
throw new Meteor.Error(e.message, 'Invalid message', {
throw new Meteor.Error(e instanceof Error ? e.message : String(e), 'Invalid message', {
function: 'actionLinks.getMessage',
});
}
Expand Down
22 changes: 8 additions & 14 deletions apps/meteor/app/api/server/lib/getUploadFormData.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,26 +13,20 @@ type UploadResult = {
fileBuffer: Buffer;
};

export const getUploadFormData = async <T extends string, K, V extends ValidateFunction<K>>(
export const getUploadFormData = async <
T extends string,
K extends Record<string, string> = Record<string, string>,
V extends ValidateFunction<K> = ValidateFunction<K>,
>(
{ request }: { request: Request },
options: {
field?: T;
validate?: V;
} = {},
): Promise<
[
UploadResult,
K extends unknown
? {
[k: string]: string;
}
: K,
T,
]
> =>
): Promise<[UploadResult, K, T]> =>
new Promise((resolve, reject) => {
const bb = busboy({ headers: request.headers, defParamCharset: 'utf8' });
const fields: { [K: string]: string } = Object.create(null);
const fields = Object.create(null) as K;

let uploadedFile: UploadResult | undefined;

Expand Down Expand Up @@ -69,7 +63,7 @@ export const getUploadFormData = async <T extends string, K, V extends ValidateF
},
);

bb.on('field', (fieldname, value) => {
bb.on('field', (fieldname: keyof K, value: K[keyof K]) => {
fields[fieldname] = value;
});

Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/api/server/v1/voip/rooms.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Random } from 'meteor/random';
import type { ILivechatAgent, IVoipRoom } from '@rocket.chat/core-typings';
import { isVoipRoomProps, isVoipRoomsProps, isVoipRoomCloseProps } from '@rocket.chat/rest-typings/dist/v1/voip';
import { isVoipRoomProps, isVoipRoomsProps, isVoipRoomCloseProps } from '@rocket.chat/rest-typings';
import { VoipRoom, LivechatVisitors, Users } from '@rocket.chat/models';

import { API } from '../../api';
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/apps/client/orchestrator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,7 +89,7 @@ class AppClientOrchestrator {
}

public async getApps(): Promise<App[]> {
const result = await APIClient.get('/apps');
const result = await APIClient.get<'/apps'>('/apps');

if ('apps' in result) {
// TODO: chapter day: multiple results are returned, but we only need one
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/apps/server/bridges/http.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,7 @@ export class AppHttpBridge extends HttpBridge {
}

return result;
} catch (e) {
} catch (e: any) {
return e.response;
}
}
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/autotranslate/server/googleTranslate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -94,7 +94,7 @@ class GoogleAutoTranslate extends AutoTranslate {
result = HTTP.get('https://translation.googleapis.com/language/translate/v2/languages', {
params,
});
} catch (e) {
} catch (e: any) {
// Fallback: Get the English names of the target languages
if (
e.response &&
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ export async function getConfirmationPoll(deviceCode: string): Promise<CloudConf
let result;
try {
result = HTTP.get(`${cloudUrl}/api/v2/register/workspace/poll?token=${deviceCode}`);
} catch (e) {
} catch (e: any) {
if (e.response && e.response.data && e.response.data.error) {
SystemLogger.error(`Failed to register with Rocket.Chat Cloud. ErrorCode: ${e.response.data.error}`);
} else {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ export async function startRegisterWorkspaceSetupWizard(resend = false, email: s
result = HTTP.post(`${cloudUrl}/api/v2/register/workspace/intent?resent=${resend}`, {
data: regInfo,
});
} catch (e) {
} catch (e: any) {
if (e.response && e.response.data && e.response.data.error) {
SystemLogger.error(`Failed to register with Rocket.Chat Cloud. ErrorCode: ${e.response.data.error}`);
} else {
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/file-upload/server/methods/sendFileMessage.ts
Original file line number Diff line number Diff line change
Expand Up @@ -129,12 +129,12 @@ Meteor.methods({
const msg = Meteor.call('sendMessage', {
rid: roomId,
ts: new Date(),
msg: '',
file: files[0],
files,
groupable: false,
attachments,
...msgData,
msg: msgData.msg ?? '',
groupable: msgData.groupable ?? false,
});

callbacks.runAsync('afterFileUpload', { user, room, message: msg });
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,7 @@ export class ImportDataConverter {
}
} catch (e) {
this._logger.error(e);
this.saveError(_id, e);
this.saveError(_id, e instanceof Error ? e : new Error(String(e)));
}
});
}
Expand Down Expand Up @@ -622,7 +622,7 @@ export class ImportDataConverter {
afterImportFn(data, 'message', true);
}
} catch (e) {
this.saveError(_id, e);
this.saveError(_id, e instanceof Error ? e : new Error(String(e)));
}
});

Expand Down Expand Up @@ -932,7 +932,7 @@ export class ImportDataConverter {
afterImportFn(data, 'channel', !existingRoom);
}
} catch (e) {
this.saveError(_id, e);
this.saveError(_id, e instanceof Error ? e : new Error(String(e)));
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -182,7 +182,7 @@ export const validateOutgoingIntegration = function (
integrationData.scriptError = undefined;
} catch (e) {
integrationData.scriptCompiled = undefined;
integrationData.scriptError = _.pick(e, 'name', 'message', 'stack');
integrationData.scriptError = e instanceof Error ? _.pick(e, 'name', 'message', 'stack') : undefined;
}
}

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -93,7 +93,7 @@ Meteor.methods({
integrationData.scriptError = undefined;
} catch (e) {
integrationData.scriptCompiled = undefined;
integrationData.scriptError = _.pick(e, 'name', 'message', 'stack');
integrationData.scriptError = e instanceof Error ? _.pick(e, 'name', 'message', 'stack') : undefined;
}
}

Expand Down
6 changes: 4 additions & 2 deletions apps/meteor/app/katex/client/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -152,8 +152,10 @@ class Katex {
'\\href': '\\@secondoftwo',
},
});
} catch ({ message }) {
return `<div class="katex-error katex-${displayMode ? 'block' : 'inline'}-error">${escapeHTML(message)}</div>`;
} catch (e) {
return `<div class="katex-error katex-${displayMode ? 'block' : 'inline'}-error">${escapeHTML(
e instanceof Error ? e.message : String(e),
)}</div>`;
}
};

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ Meteor.methods({
try {
Promise.await(businessHourManager.saveBusinessHour(businessHourData));
} catch (e) {
throw new Meteor.Error(e.message);
throw new Meteor.Error(e instanceof Error ? e.message : String(e));
}
},
});
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ export class SAMLServiceProvider {

return callback(null, target);
} catch (error) {
return callback(error);
return callback(error instanceof Error ? error : String(error));
}
});
}
Expand Down Expand Up @@ -154,7 +154,7 @@ export class SAMLServiceProvider {
}
callback(null, target);
} catch (error) {
callback(error);
callback(error instanceof Error ? error : String(error));
}
});
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ export class LogoutRequestParser {
const msg = doc.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:protocol', 'StatusMessage');
SAMLUtils.log(`Unexpected msg from IDP. Does your session still exist at IDP? Idp returned: \n ${msg}`);

return callback(e, null);
return callback(e instanceof Error ? e : String(e), null);
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ export class ResponseParser {

this.verifySignatures(response, assertionData, xml);
} catch (e) {
return callback(e, null, false);
return callback(e instanceof Error ? e : String(e), null, false);
}

const profile: Record<string, any> = {};
Expand All @@ -74,7 +74,7 @@ export class ResponseParser {
try {
issuer = this.getIssuer(assertion);
} catch (e) {
return callback(e, null, false);
return callback(e instanceof Error ? e : String(e), null, false);
}

if (issuer) {
Expand All @@ -95,14 +95,14 @@ export class ResponseParser {
try {
this.validateSubjectConditions(subject);
} catch (e) {
return callback(e, null, false);
return callback(e instanceof Error ? e : String(e), null, false);
}
}

try {
this.validateAssertionConditions(assertion);
} catch (e) {
return callback(e, null, false);
return callback(e instanceof Error ? e : String(e), null, false);
}

const authnStatement = assertion.getElementsByTagNameNS('urn:oasis:names:tc:SAML:2.0:assertion', 'AuthnStatement')[0];
Expand Down
5 changes: 5 additions & 0 deletions apps/meteor/app/models/server/models/Rooms.js
Original file line number Diff line number Diff line change
Expand Up @@ -990,6 +990,11 @@ export class Rooms extends Base {
return this.update(query, update);
}

/**
* @param {string} _id
* @param {string?} messageId
* @returns {Promise<void>}
*/
resetLastMessageById(_id, messageId = undefined) {
const query = { _id };
const lastMessage = Messages.getLastVisibleMessageSentWithNoTypeByRoomId(_id, messageId);
Expand Down
4 changes: 2 additions & 2 deletions apps/meteor/app/models/server/models/_oplogHandle.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ class CustomOplogHandle {

await mongo.db.admin().command({ replSetGetStatus: 1 });
} catch (e) {
if (e.message.startsWith('not authorized')) {
if (e instanceof Error && e.message.startsWith('not authorized')) {
console.info(
'Change Stream is available for your installation, give admin permissions to your database user to use this improved version.',
);
Expand Down Expand Up @@ -214,7 +214,7 @@ if (!isRunningMs()) {
try {
oplogHandle = Promise.await(new CustomOplogHandle().start());
} catch (e) {
console.error(e.message);
console.error(e instanceof Error ? e.message : e);
}
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -83,7 +83,7 @@ class NotificationClass {
NotificationQueue.removeById(notification._id);
} catch (e) {
SystemLogger.error(e);
await NotificationQueue.setErrorById(notification._id, e.message);
await NotificationQueue.setErrorById(notification._id, e instanceof Error ? e.message : String(e));
}

if (counter >= this.maxBatchSize) {
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/ui/client/lib/fileUpload.ts
Original file line number Diff line number Diff line change
Expand Up @@ -130,7 +130,7 @@ export const uploadFileWithMessage = async (
if (!Session.get('uploading').length) {
UserAction.stop(rid, USER_ACTIVITIES.USER_UPLOADING, { tmid });
}
} catch (error) {
} catch (error: any) {
const uploads = Session.get('uploading');
uploads
.filter((u) => u.id === upload.id)
Expand Down
3 changes: 2 additions & 1 deletion apps/meteor/app/utils/client/lib/RestApiClient.ts
Original file line number Diff line number Diff line change
Expand Up @@ -36,8 +36,9 @@ APIClient.use(async function (request, next) {
throw error;
}

const e = await error.json();

return new Promise(async (resolve, reject) => {
const e = await error.json();
process2faReturn({
error: e,
result: null,
Expand Down
7 changes: 7 additions & 0 deletions apps/meteor/app/utils/lib/getUserPreference.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
import { Users } from '../../models';
import { settings } from '../../settings';

/**
* @summary Get a user preference
* @param {String} userId The user ID
* @param {String} preference The preference name
* @param {unknown?} defaultValue The default value
* @returns {unknown} The preference value
*/
export const getUserPreference = (user, key, defaultValue = undefined) => {
let preference;
if (typeof user === typeof '') {
Expand Down
2 changes: 1 addition & 1 deletion apps/meteor/app/videobridge/client/tabBar.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ addAction('start-call', ({ room }) => {
try {
await VideoConfManager.loadCapabilities();
dispatchPopup({ rid: room._id });
} catch (error) {
} catch (error: any) {
dispatchWarning(error.error);
}
});
Expand Down
12 changes: 6 additions & 6 deletions apps/meteor/app/webdav/server/lib/webdavClientAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export class WebdavClientAdapter {
async stat(path: string): Promise<undefined> {
try {
return await this._client.stat(path);
} catch (error) {
} catch (error: any) {
throw new Error(
error.response && error.response.statusText ? error.response.statusText : 'Error checking if directory exists on webdav',
);
Expand All @@ -33,39 +33,39 @@ export class WebdavClientAdapter {
async createDirectory(path: string): Promise<Response> {
try {
return await this._client.createDirectory(path);
} catch (error) {
} catch (error: any) {
throw new Error(error.response && error.response.statusText ? error.response.statusText : 'Error creating directory on webdav');
}
}

async deleteFile(path: string): Promise<Response> {
try {
return await this._client.deleteFile(path);
} catch (error) {
} catch (error: any) {
throw new Error(error.response && error.response.statusText ? error.response.statusText : 'Error deleting file on webdav');
}
}

async getFileContents(filename: string): Promise<Buffer> {
try {
return (await this._client.getFileContents(filename)) as Buffer;
} catch (error) {
} catch (error: any) {
throw new Error(error.response && error.response.statusText ? error.response.statusText : 'Error getting file contents webdav');
}
}

async getDirectoryContents(path: string): Promise<Array<Stat>> {
try {
return await this._client.getDirectoryContents(path);
} catch (error) {
} catch (error: any) {
throw new Error(error.response && error.response.statusText ? error.response.statusText : 'Error getting directory contents webdav');
}
}

async putFileContents(path: string, data: Buffer, options: Record<string, any> = {}): Promise<any> {
try {
return await this._client.putFileContents(path, data, options);
} catch (error) {
} catch (error: any) {
throw new Error(error.response?.statusText ?? 'Error updating file contents.');
}
}
Expand Down
Loading

0 comments on commit 3427e5e

Please sign in to comment.