Skip to content

Commit

Permalink
refactor: remove find after visitor creation
Browse files Browse the repository at this point in the history
  • Loading branch information
ricardogarim committed Jun 26, 2024
1 parent c92583f commit c869396
Show file tree
Hide file tree
Showing 4 changed files with 39 additions and 47 deletions.
2 changes: 1 addition & 1 deletion apps/meteor/app/livechat/imports/server/rest/sms.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,7 @@ const defineVisitor = async (smsNumber: string, targetDepartment?: string) => {
throw new Meteor.Error('error-invalid-visitor', 'Invalid visitor');
}

return LivechatVisitors.findOneEnabledById(livechatVisitor._id);
return livechatVisitor;
};

const normalizeLocationSharing = (payload: ServiceData) => {
Expand Down
7 changes: 3 additions & 4 deletions apps/meteor/app/livechat/server/api/v1/message.ts
Original file line number Diff line number Diff line change
Expand Up @@ -251,7 +251,7 @@ API.v1.addRoute(
async post() {
const visitorToken = this.bodyParams.visitor.token;

let visitor = await LivechatVisitors.getVisitorByToken(visitorToken, {});
const visitor = await LivechatVisitors.getVisitorByToken(visitorToken, {});
let rid: string;
if (visitor) {
const extraQuery = await callbacks.run('livechat.applyRoomRestrictions', {});
Expand All @@ -267,11 +267,10 @@ API.v1.addRoute(
const guest: typeof this.bodyParams.visitor & { connectionData?: unknown } = this.bodyParams.visitor;
guest.connectionData = normalizeHttpHeaderData(this.request.headers);

const livechatVisitor = await LivechatTyped.registerGuest(guest);
if (!livechatVisitor) {
const visitor = await LivechatTyped.registerGuest(guest);
if (!visitor) {
throw new Error('error-livechat-visitor-registration');
}
visitor = await LivechatVisitors.findOneEnabledById(livechatVisitor?._id);
}

const guest = visitor;
Expand Down
45 changes: 21 additions & 24 deletions apps/meteor/app/livechat/server/api/v1/visitor.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import type { ILivechatCustomField, ILivechatVisitor, IRoom } from '@rocket.chat/core-typings';
import type { ILivechatCustomField, IRoom } from '@rocket.chat/core-typings';
import { LivechatVisitors as VisitorsRaw, LivechatCustomField, LivechatRooms } from '@rocket.chat/models';
import { Match, check } from 'meteor/check';
import { Meteor } from 'meteor/meteor';
Expand Down Expand Up @@ -47,31 +47,28 @@ API.v1.addRoute('livechat/visitor', {
connectionData: normalizeHttpHeaderData(this.request.headers),
};

const livechatVisitor = await LivechatTyped.registerGuest(guest);
if (!livechatVisitor) {
const visitor = await LivechatTyped.registerGuest(guest);
if (!visitor) {
throw new Meteor.Error('error-livechat-visitor-registration', 'Error registering visitor', {
method: 'livechat/visitor',
});
}

let visitor: ILivechatVisitor | null = await VisitorsRaw.findOneEnabledById(livechatVisitor._id, {});
if (visitor) {
const extraQuery = await callbacks.run('livechat.applyRoomRestrictions', {});
// If it's updating an existing visitor, it must also update the roomInfo
const rooms = await LivechatRooms.findOpenByVisitorToken(visitor?.token, {}, extraQuery).toArray();
await Promise.all(
rooms.map(
(room: IRoom) =>
visitor &&
LivechatTyped.saveRoomInfo(room, {
_id: visitor._id,
name: visitor.name,
phone: visitor.phone?.[0]?.phoneNumber,
livechatData: visitor.livechatData as { [k: string]: string },
}),
),
);
}
const extraQuery = await callbacks.run('livechat.applyRoomRestrictions', {});
// If it's updating an existing visitor, it must also update the roomInfo
const rooms = await LivechatRooms.findOpenByVisitorToken(visitor?.token, {}, extraQuery).toArray();
await Promise.all(
rooms.map(
(room: IRoom) =>
visitor &&
LivechatTyped.saveRoomInfo(room, {
_id: visitor._id,
name: visitor.name,
phone: visitor.phone?.[0]?.phoneNumber,
livechatData: visitor.livechatData as { [k: string]: string },
}),
),
);

if (customFields && Array.isArray(customFields) && customFields.length > 0) {
const keys = customFields.map((field) => field.key);
Expand Down Expand Up @@ -101,21 +98,21 @@ API.v1.addRoute('livechat/visitor', {
if (processedKeys.length !== keys.length) {
LivechatTyped.logger.warn({
msg: 'Some custom fields were not processed',
visitorId: livechatVisitor._id,
visitorId: visitor._id,
missingKeys: keys.filter((key) => !processedKeys.includes(key)),
});
}

if (errors.length > 0) {
LivechatTyped.logger.error({
msg: 'Error updating custom fields',
visitorId: livechatVisitor._id,
visitorId: visitor._id,
errors,
});
throw new Error('error-updating-custom-fields');
}

visitor = await VisitorsRaw.findOneEnabledById(livechatVisitor._id);
return API.v1.success({ visitor: await VisitorsRaw.findOneEnabledById(visitor._id) });
}

if (!visitor) {
Expand Down
32 changes: 14 additions & 18 deletions apps/meteor/app/livechat/server/methods/registerGuest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,24 +23,24 @@ declare module '@rocket.chat/ui-contexts' {
department?: string;
customFields?: Array<{ key: string; value: string; overwrite: boolean; scope?: unknown }>;
}): {
userId: string;
visitor: ILivechatVisitor | null;
userId: ILivechatVisitor['_id'];
visitor: Pick<ILivechatVisitor, '_id' | 'token' | 'name' | 'username' | 'visitorEmails' | 'department'>;
};
}
}

Meteor.methods<ServerMethods>({
async 'livechat:registerGuest'({ token, name, email, department, customFields } = {}): Promise<{
userId: string;
visitor: ILivechatVisitor | null;
userId: ILivechatVisitor['_id'];
visitor: Pick<ILivechatVisitor, '_id' | 'token' | 'name' | 'username' | 'visitorEmails' | 'department'>;
}> {
methodDeprecationLogger.method('livechat:registerGuest', '7.0.0');

if (!token) {
throw new Meteor.Error('error-invalid-token', 'Invalid token', { method: 'livechat:registerGuest' });
}

const livechatVisitor = await LivechatTyped.registerGuest.call(this, {
const visitor = await LivechatTyped.registerGuest.call(this, {
token,
name,
email,
Expand All @@ -50,17 +50,6 @@ Meteor.methods<ServerMethods>({
// update visited page history to not expire
await Messages.keepHistoryForToken(token);

// TODO: remove unneeded find - registerGuest returns created record
const visitor = await LivechatVisitors.getVisitorByToken(token, {
projection: {
token: 1,
name: 1,
username: 1,
visitorEmails: 1,
department: 1,
},
});

if (!visitor) {
throw new Meteor.Error('error-invalid-visitor', 'Invalid visitor', { method: 'livechat:registerGuest' });
}
Expand Down Expand Up @@ -93,8 +82,15 @@ Meteor.methods<ServerMethods>({
}

return {
userId: livechatVisitor?._id ?? '',
visitor,
userId: visitor._id,
visitor: {
_id: visitor._id,
token: visitor.token,
name: visitor.name,
username: visitor.username,
visitorEmails: visitor.visitorEmails,
department: visitor.department,
},
};
},
});

0 comments on commit c869396

Please sign in to comment.