refactor: remove Promise.await (#28539)

pull/28487/head^2
Guilherme Gazzo 3 years ago committed by GitHub
parent 322d8fb41a
commit e6752c8e32
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 4
      apps/meteor/app/api/server/v1/users.ts
  2. 6
      apps/meteor/app/apps/server/bridges/commands.ts
  3. 2
      apps/meteor/app/apps/server/bridges/livechat.ts
  4. 2
      apps/meteor/app/apps/server/bridges/messages.ts
  5. 2
      apps/meteor/app/authentication/server/hooks/login.ts
  6. 4
      apps/meteor/app/e2e/server/methods/resetOwnE2EKey.ts
  7. 2
      apps/meteor/app/lib/server/functions/saveUser.js
  8. 2
      apps/meteor/app/lib/server/functions/saveUserIdentity.ts
  9. 8
      apps/meteor/app/lib/server/functions/setUsername.ts
  10. 10
      apps/meteor/app/lib/server/functions/updateMessage.ts
  11. 2
      apps/meteor/app/livechat/server/api/v1/message.ts
  12. 4
      apps/meteor/app/livechat/server/api/v1/videoCall.ts
  13. 2
      apps/meteor/app/livechat/server/api/v1/visitor.ts
  14. 4
      apps/meteor/app/livechat/server/hooks/leadCapture.js
  15. 8
      apps/meteor/app/livechat/server/lib/Livechat.js
  16. 2
      apps/meteor/app/reactions/server/setReaction.ts
  17. 2
      apps/meteor/app/slackbridge/server/SlackAdapter.js
  18. 4
      apps/meteor/app/user-status/server/methods/setUserStatus.ts
  19. 2
      apps/meteor/definition/IRoomTypeConfig.ts
  20. 2
      apps/meteor/ee/app/livechat-enterprise/server/lib/LivechatEnterprise.js
  21. 4
      apps/meteor/ee/app/models/server/models/LivechatUnit.js
  22. 4
      apps/meteor/ee/server/lib/audit/startup.ts
  23. 14
      apps/meteor/ee/server/startup/seatsCap.ts
  24. 4
      apps/meteor/server/features/EmailInbox/EmailInbox_Outgoing.ts
  25. 8
      apps/meteor/server/lib/resetUserE2EKey.ts
  26. 3
      apps/meteor/server/lib/roles/createOrUpdateProtectedRole.ts
  27. 2
      apps/meteor/server/lib/rooms/roomCoordinator.ts
  28. 2
      apps/meteor/server/lib/rooms/roomTypes/livechat.ts
  29. 4
      apps/meteor/server/services/federation/infrastructure/rocket-chat/adapters/Message.ts

@ -950,13 +950,13 @@ API.v1.addRoute(
throw new Meteor.Error('error-not-allowed', 'Not allowed');
}
if (!resetUserE2EEncriptionKey(user._id, true)) {
if (!(await resetUserE2EEncriptionKey(user._id, true))) {
return API.v1.failure();
}
return API.v1.success();
}
resetUserE2EEncriptionKey(this.userId, false);
await resetUserE2EEncriptionKey(this.userId, false);
return API.v1.success();
},
},

@ -162,12 +162,12 @@ export class AppCommandsBridge extends CommandBridge {
}
}
private _appCommandExecutor(
private async _appCommandExecutor(
command: string,
parameters: any,
message: RequiredField<Partial<IMessage>, 'rid'>,
triggerId?: string,
): void {
): Promise<void> {
const user = this.orch.getConverters()?.get('users').convertById(Meteor.userId());
const room = this.orch.getConverters()?.get('rooms').convertById(message.rid);
const threadId = message.tmid;
@ -181,7 +181,7 @@ export class AppCommandsBridge extends CommandBridge {
triggerId,
);
void Promise.await(this.orch.getManager()?.getCommandManager().executeCommand(command, context));
await this.orch.getManager()?.getCommandManager().executeCommand(command, context);
}
private _appCommandPreviewer(command: string, parameters: any, message: RequiredField<Partial<IMessage>, 'rid'>): any {

@ -70,7 +70,7 @@ export class AppLivechatBridge extends LivechatBridge {
message: this.orch.getConverters()?.get('messages').convertAppMessage(message),
};
Livechat.updateMessage(data);
await Livechat.updateMessage(data);
}
protected async createRoom(visitor: IVisitor, agent: IUser, appId: string, extraParams?: IExtraRoomParams): Promise<ILivechatRoom> {

@ -48,7 +48,7 @@ export class AppMessageBridge extends MessageBridge {
const msg = this.orch.getConverters()?.get('messages').convertAppMessage(message);
const editor = Users.findOneById(message.editor.id);
updateMessage(msg, editor);
await updateMessage(msg, editor);
}
protected async notifyUser(user: IUser, message: IMessage, appId: string): Promise<void> {

@ -19,5 +19,5 @@ callbacks.add('afterValidateLogin', (login: ILoginAttempt) => {
return;
}
Promise.await(saveSuccessfulLogin(login));
return saveSuccessfulLogin(login);
});

@ -12,7 +12,7 @@ declare module '@rocket.chat/ui-contexts' {
}
Meteor.methods<ServerMethods>({
'e2e.resetOwnE2EKey': twoFactorRequired(() => {
'e2e.resetOwnE2EKey': twoFactorRequired(async () => {
const userId = Meteor.userId();
if (!userId) {
@ -21,7 +21,7 @@ Meteor.methods<ServerMethods>({
});
}
if (!resetUserE2EEncriptionKey(userId, false)) {
if (!(await resetUserE2EEncriptionKey(userId, false))) {
return false;
}
return true;

@ -370,7 +370,7 @@ export const saveUser = async function (userId, userData) {
}
if (typeof userData.statusText === 'string') {
setStatusText(userData._id, userData.statusText);
await setStatusText(userData._id, userData.statusText);
}
if (userData.email) {

@ -34,7 +34,7 @@ export async function saveUserIdentity({ _id, name: rawName, username: rawUserna
return false;
}
if (!_setUsername(_id, username, user)) {
if (!(await _setUsername(_id, username, user))) {
return false;
}
user.username = username;

@ -13,7 +13,7 @@ import { checkUsernameAvailability, setUserAvatar } from '.';
import { getAvatarSuggestionForUser } from './getAvatarSuggestionForUser';
import { SystemLogger } from '../../../../server/lib/logger/system';
export const _setUsername = function (userId: string, u: string, fullUser: IUser): unknown {
export const _setUsername = async function (userId: string, u: string, fullUser: IUser): Promise<unknown> {
const username = u.trim();
if (!userId || !username) {
return false;
@ -54,7 +54,7 @@ export const _setUsername = function (userId: string, u: string, fullUser: IUser
user.username = username;
if (!previousUsername && settings.get('Accounts_SetDefaultAvatar') === true) {
// eslint-disable-next-line @typescript-eslint/ban-types
const avatarSuggestions = Promise.await(getAvatarSuggestionForUser(user)) as {};
const avatarSuggestions = (await getAvatarSuggestionForUser(user)) as {};
let gravatar;
Object.keys(avatarSuggestions).some((service) => {
const avatarData = avatarSuggestions[+service as keyof typeof avatarSuggestions];
@ -75,9 +75,9 @@ export const _setUsername = function (userId: string, u: string, fullUser: IUser
// If it's the first username and the user has an invite Token, then join the invite room
if (!previousUsername && user.inviteToken) {
const inviteData = Promise.await(Invites.findOneById(user.inviteToken));
const inviteData = await Invites.findOneById(user.inviteToken);
if (inviteData?.rid) {
Promise.await(addUserToRoom(inviteData.rid, user));
await addUserToRoom(inviteData.rid, user);
}
}

@ -8,7 +8,7 @@ import { callbacks } from '../../../../lib/callbacks';
import { Apps } from '../../../../ee/server/apps';
import { parseUrlsInMessage } from './parseUrlsInMessage';
export const updateMessage = function (message: IMessage, user: IUser, originalMessage?: IMessage): void {
export const updateMessage = async function (message: IMessage, user: IUser, originalMessage?: IMessage): Promise<void> {
if (!originalMessage) {
originalMessage = Messages.findOneById(message._id);
}
@ -17,14 +17,14 @@ export const updateMessage = function (message: IMessage, user: IUser, originalM
if (message && Apps && Apps.isLoaded()) {
const appMessage = Object.assign({}, originalMessage, message);
const prevent = Promise.await(Apps.getBridges()?.getListenerBridge().messageEvent('IPreMessageUpdatedPrevent', appMessage));
const prevent = await Apps.getBridges()?.getListenerBridge().messageEvent('IPreMessageUpdatedPrevent', appMessage);
if (prevent) {
throw new Meteor.Error('error-app-prevented-updating', 'A Rocket.Chat App prevented the message updating.');
}
let result;
result = Promise.await(Apps.getBridges()?.getListenerBridge().messageEvent('IPreMessageUpdatedExtend', appMessage));
result = Promise.await(Apps.getBridges()?.getListenerBridge().messageEvent('IPreMessageUpdatedModify', result));
result = await Apps.getBridges()?.getListenerBridge().messageEvent('IPreMessageUpdatedExtend', appMessage);
result = await Apps.getBridges()?.getListenerBridge().messageEvent('IPreMessageUpdatedModify', result);
if (typeof result === 'object') {
message = Object.assign(appMessage, result);
@ -33,7 +33,7 @@ export const updateMessage = function (message: IMessage, user: IUser, originalM
// If we keep history of edits, insert a new message to store history information
if (settings.get('Message_KeepHistory')) {
Promise.await(MessagesRaw.cloneAndSaveAsHistoryById(message._id, user as Required<Pick<IUser, '_id' | 'username' | 'name'>>));
await MessagesRaw.cloneAndSaveAsHistoryById(message._id, user as Required<Pick<IUser, '_id' | 'username' | 'name'>>);
}
Object.assign<IMessage, Omit<IEditedMessage, keyof IMessage>>(message, {

@ -124,7 +124,7 @@ API.v1.addRoute(
throw new Error('invalid-message');
}
const result = Livechat.updateMessage({
const result = await Livechat.updateMessage({
guest,
message: { _id: msg._id, msg: this.bodyParams.msg },
});

@ -33,7 +33,7 @@ API.v1.addRoute(
}
const config = await settings();
if (!config.theme || !config.theme.actionLinks || !config.theme.actionLinks.webrtc) {
if (!config.theme?.actionLinks?.webrtc) {
throw new Error('invalid-livechat-config');
}
@ -89,7 +89,7 @@ API.v1.addRoute(
throw new Error('invalid-callId');
}
Livechat.updateCallStatus(callId, rid, status, this.user);
await Livechat.updateCallStatus(callId, rid, status, this.user);
return API.v1.success({ status });
},

@ -159,7 +159,7 @@ API.v1.addRoute('livechat/visitor.callStatus', {
if (!guest) {
throw new Meteor.Error('invalid-token');
}
Livechat.updateCallStatus(callId, rid, callStatus, guest);
await Livechat.updateCallStatus(callId, rid, callStatus, guest);
return API.v1.success({ token, callStatus });
},
});

@ -30,7 +30,7 @@ function validateMessage(message, room) {
callbacks.add(
'afterSaveMessage',
function (message, room) {
async function (message, room) {
if (!isOmnichannelRoom(room)) {
return message;
}
@ -46,7 +46,7 @@ callbacks.add(
const msgEmails = message.msg.match(emailRegexp);
if (msgEmails || msgPhones) {
Promise.await(LivechatVisitors.saveGuestEmailPhoneById(room.v._id, msgEmails, msgPhones));
await LivechatVisitors.saveGuestEmailPhoneById(room.v._id, msgEmails, msgPhones);
callbacks.run('livechat.leadCapture', room);
}

@ -230,7 +230,7 @@ export const Livechat = {
});
},
updateMessage({ guest, message }) {
async updateMessage({ guest, message }) {
check(message, Match.ObjectIncluding({ _id: String }));
const originalMessage = Messages.findOneById(message._id);
@ -247,7 +247,7 @@ export const Livechat = {
});
}
updateMessage(message, guest);
await updateMessage(message, guest);
return true;
},
@ -1295,10 +1295,10 @@ export const Livechat = {
};
await LivechatVisitors.updateById(contactId, updateUser);
},
updateCallStatus(callId, rid, status, user) {
async updateCallStatus(callId, rid, status, user) {
Rooms.setCallStatus(rid, status);
if (status === 'ended' || status === 'declined') {
if (Promise.await(VideoConf.declineLivechatCall(callId))) {
if (await VideoConf.declineLivechatCall(callId)) {
return;
}

@ -102,7 +102,7 @@ async function setReaction(room: IRoom, user: IUser, message: IMessage, reaction
isReacted = true;
}
Promise.await(Apps.triggerEvent(AppEvents.IPostMessageReacted, message, user, reaction, isReacted));
await Apps.triggerEvent(AppEvents.IPostMessageReacted, message, user, reaction, isReacted);
msgStream.emit(message.rid, message);
}

@ -857,7 +857,7 @@ export default class SlackAdapter {
updatedBySlack: true, // We don't want to notify slack about this change since Slack initiated it
};
updateMessage(rocketMsgObj, rocketUser);
await updateMessage(rocketMsgObj, rocketUser);
slackLogger.debug('Rocket message updated by Slack');
}
}

@ -14,7 +14,7 @@ declare module '@rocket.chat/ui-contexts' {
}
Meteor.methods<ServerMethods>({
setUserStatus: (statusType, statusText) => {
setUserStatus: async (statusType, statusText) => {
const userId = Meteor.userId();
if (!userId) {
throw new Meteor.Error('error-invalid-user', 'Invalid user', { method: 'setUserStatus' });
@ -38,7 +38,7 @@ Meteor.methods<ServerMethods>({
});
}
setStatusText(userId, statusText);
await setStatusText(userId, statusText);
}
},
});

@ -112,7 +112,7 @@ export interface IRoomTypeServerDirectives {
notificationMessage: string,
userId: string,
) => { title: string | undefined; text: string };
getMsgSender: (senderId: IRocketChatRecord['_id']) => IRocketChatRecord | undefined;
getMsgSender: (senderId: IRocketChatRecord['_id']) => Promise<IRocketChatRecord | undefined>;
includeInRoomSearch: () => boolean;
getReadReceiptsExtraData: (message: IMessage) => Partial<ReadReceipt>;
includeInDashboard: () => boolean;

@ -64,7 +64,7 @@ export const LivechatEnterprise = {
return true;
},
removeUnit(_id) {
async removeUnit(_id) {
check(_id, String);
const unit = LivechatUnit.findOneById(_id, { fields: { _id: 1 } });

@ -132,10 +132,10 @@ class LivechatUnit extends LivechatDepartment {
return this.update(query, update, { multi: true });
}
removeById(_id) {
async removeById(_id) {
LivechatUnitMonitors.removeByUnitId(_id);
this.removeParentAndAncestorById(_id);
Promise.await(LivechatRooms.removeUnitAssociationFromRooms(_id));
await LivechatRooms.removeUnitAssociationFromRooms(_id);
const query = { _id };
return this.remove(query);

@ -1,6 +1,6 @@
import { Permissions } from '@rocket.chat/models';
import { createOrUpdateProtectedRole } from '../../../../server/lib/roles/createOrUpdateProtectedRole';
import { createOrUpdateProtectedRoleAsync } from '../../../../server/lib/roles/createOrUpdateProtectedRole';
export const createPermissions = async () => {
const permissions = [
@ -17,5 +17,5 @@ export const createPermissions = async () => {
void Permissions.create(permission._id, permission.roles);
}
return Promise.all(defaultRoles.map((role) => createOrUpdateProtectedRole(role.name, role)));
return Promise.all(defaultRoles.map((role) => createOrUpdateProtectedRoleAsync(role.name, role)));
};

@ -108,22 +108,20 @@ async function handleMaxSeatsBanners() {
}
}
const handleMaxSeatsBannersSync = () => Promise.await(handleMaxSeatsBanners);
callbacks.add('afterCreateUser', handleMaxSeatsBanners, callbacks.priority.MEDIUM, 'handle-max-seats-banners');
callbacks.add('afterCreateUser', handleMaxSeatsBannersSync, callbacks.priority.MEDIUM, 'handle-max-seats-banners');
callbacks.add('afterSaveUser', handleMaxSeatsBanners, callbacks.priority.MEDIUM, 'handle-max-seats-banners');
callbacks.add('afterSaveUser', handleMaxSeatsBannersSync, callbacks.priority.MEDIUM, 'handle-max-seats-banners');
callbacks.add('afterDeleteUser', handleMaxSeatsBanners, callbacks.priority.MEDIUM, 'handle-max-seats-banners');
callbacks.add('afterDeleteUser', handleMaxSeatsBannersSync, callbacks.priority.MEDIUM, 'handle-max-seats-banners');
callbacks.add('afterDeactivateUser', handleMaxSeatsBanners, callbacks.priority.MEDIUM, 'handle-max-seats-banners');
callbacks.add('afterDeactivateUser', handleMaxSeatsBannersSync, callbacks.priority.MEDIUM, 'handle-max-seats-banners');
callbacks.add('afterActivateUser', handleMaxSeatsBannersSync, callbacks.priority.MEDIUM, 'handle-max-seats-banners');
callbacks.add('afterActivateUser', handleMaxSeatsBanners, callbacks.priority.MEDIUM, 'handle-max-seats-banners');
Meteor.startup(async () => {
await createSeatsLimitBanners();
await handleMaxSeatsBanners();
onValidateLicenses(handleMaxSeatsBannersSync);
onValidateLicenses(handleMaxSeatsBanners);
});

@ -81,7 +81,7 @@ async function sendEmail(inbox: Inbox, mail: Mail.Options, options?: any): Promi
slashCommands.add({
command: 'sendEmailAttachment',
callback: (command: any, params: string) => {
callback: async (command: any, params: string) => {
logger.debug('sendEmailAttachment command: ', command, params);
if (command !== 'sendEmailAttachment' || !Match.test(params, String)) {
return;
@ -105,7 +105,7 @@ slashCommands.add({
});
}
const file = Promise.await(Uploads.findOneById(message.file._id));
const file = await Uploads.findOneById(message.file._id);
if (!file) {
return;

@ -7,7 +7,7 @@ import { settings } from '../../app/settings/server';
import * as Mailer from '../../app/mailer/server/api';
import { isUserIdFederated } from './isUserIdFederated';
const sendResetNotitification = function (uid: string): void {
const sendResetNotification = function (uid: string): void {
const user: IUser = Users.findOneById(uid, {});
if (!user) {
throw new Meteor.Error('invalid-user');
@ -57,12 +57,12 @@ const sendResetNotitification = function (uid: string): void {
}
};
export function resetUserE2EEncriptionKey(uid: string, notifyUser: boolean): boolean {
export async function resetUserE2EEncriptionKey(uid: string, notifyUser: boolean): Promise<boolean> {
if (notifyUser) {
sendResetNotitification(uid);
sendResetNotification(uid);
}
const isUserFederated = Promise.await(isUserIdFederated(uid));
const isUserFederated = await isUserIdFederated(uid);
if (isUserFederated) {
throw new Meteor.Error('error-not-allowed', 'Federated Users cant have TOTP', { function: 'resetTOTP' });
}

@ -29,6 +29,3 @@ export const createOrUpdateProtectedRoleAsync = async (
protected: true,
});
};
export const createOrUpdateProtectedRole = (...args: Parameters<typeof createOrUpdateProtectedRoleAsync>): void =>
Promise.await(createOrUpdateProtectedRoleAsync(...args));

@ -48,7 +48,7 @@ class RoomCoordinatorServer extends RoomCoordinator {
return { title, text };
},
getMsgSender(senderId: IRocketChatRecord['_id']): IRocketChatRecord | undefined {
getMsgSender(senderId: IRocketChatRecord['_id']): Promise<IRocketChatRecord | undefined> {
return Users.findOneById(senderId);
},
includeInRoomSearch(): boolean {

@ -39,7 +39,7 @@ roomCoordinator.add(LivechatRoomType, {
},
getMsgSender(senderId) {
return Promise.await(LivechatVisitors.findOneById(senderId));
return LivechatVisitors.findOneById(senderId);
},
getReadReceiptsExtraData(message) {

@ -80,7 +80,7 @@ export class RocketChatMessageAdapter {
senderExternalId: user.getExternalId(),
}),
};
updateMessage(updatedMessage, user.getInternalReference(), originalMessage);
await updateMessage(updatedMessage, user.getInternalReference(), originalMessage);
}
private async getMessageToReplyToWhenQuoting(
@ -140,7 +140,7 @@ export class RocketChatMessageAdapter {
user,
),
};
updateMessage(updatedMessage, user.getInternalReference(), editedMessage);
await updateMessage(updatedMessage, user.getInternalReference(), editedMessage);
}
public async sendFileMessage(

Loading…
Cancel
Save