Skip to content

Commit

Permalink
refactor(chat): split participantsLog from main ChatRoom schema due t…
Browse files Browse the repository at this point in the history
…o SQL support (#900)
  • Loading branch information
kkopanidis authored Jan 18, 2024
1 parent e6a110b commit 87884d3
Show file tree
Hide file tree
Showing 4 changed files with 99 additions and 46 deletions.
60 changes: 60 additions & 0 deletions modules/chat/src/models/ChatParticipantsLog.schema.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,60 @@
import { ConduitModel, DatabaseProvider, TYPE } from '@conduitplatform/grpc-sdk';
import { ConduitActiveSchema } from '@conduitplatform/module-tools';
import { User } from './User.model';
import { ChatRoom } from './ChatRoom.schema';

const schema: ConduitModel = {
_id: TYPE.ObjectId,
action: {
type: TYPE.String,
enum: ['add', 'remove', 'create', 'join', 'leave'],
required: true,
},
user: {
type: TYPE.Relation,
model: 'User',
required: true,
},
chatRoom: {
type: TYPE.Relation,
model: 'ChatRoom',
required: true,
},
createdAt: TYPE.Date,
updatedAt: TYPE.Date,
};
const modelOptions = {
timestamps: true,
conduit: {
permissions: {
extendable: true,
canCreate: false,
canModify: 'ExtensionOnly',
canDelete: false,
},
},
} as const;
const collectionName = undefined;

export class ChatParticipantsLog extends ConduitActiveSchema<ChatParticipantsLog> {
private static _instance: ChatParticipantsLog;
_id: string;
action: 'add' | 'remove' | 'create' | 'join' | 'leave';
user: string | User;
chatRoom: string | ChatRoom;
createdAt: Date;
updatedAt: Date;

private constructor(database: DatabaseProvider) {
super(database, ChatParticipantsLog.name, schema, modelOptions, collectionName);
}

static getInstance(database?: DatabaseProvider) {
if (ChatParticipantsLog._instance) return ChatParticipantsLog._instance;
if (!database) {
throw new Error('No database instance provided!');
}
ChatParticipantsLog._instance = new ChatParticipantsLog(database);
return ChatParticipantsLog._instance;
}
}
25 changes: 4 additions & 21 deletions modules/chat/src/models/ChatRoom.schema.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { ConduitModel, DatabaseProvider, TYPE } from '@conduitplatform/grpc-sdk';
import { ConduitActiveSchema } from '@conduitplatform/module-tools';
import { User } from './User.model';
import { ChatParticipantsLog } from './ChatParticipantsLog.schema';

const schema: ConduitModel = {
_id: TYPE.ObjectId,
Expand All @@ -21,22 +22,8 @@ const schema: ConduitModel = {
},
participantsLog: [
{
type: {
action: {
type: TYPE.String,
enum: ['add', 'remove', 'create', 'join', 'leave'],
required: true,
},
user: {
type: TYPE.Relation,
model: 'User',
required: true,
},
timestamp: {
type: TYPE.Date,
required: true,
},
},
type: TYPE.Relation,
model: 'ChatParticipantsLog',
},
],
deleted: {
Expand Down Expand Up @@ -65,11 +52,7 @@ export class ChatRoom extends ConduitActiveSchema<ChatRoom> {
name: string;
creator?: string | User;
participants: string[] | User[];
participantsLog: {
action: 'add' | 'remove' | 'create' | 'join' | 'leave';
user: string | User;
timestamp: Date;
}[];
participantsLog: (string | ChatParticipantsLog)[];
deleted: boolean;
createdAt: Date;
updatedAt: Date;
Expand Down
1 change: 1 addition & 0 deletions modules/chat/src/models/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ export * from './ChatRoom.schema';
export * from './Message.schema';
export * from './User.model';
export * from './InvitationToken.schema';
export * from './ChatParticipantsLog.schema';
59 changes: 34 additions & 25 deletions modules/chat/src/routes/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ import {
GrpcServer,
RoutingManager,
} from '@conduitplatform/module-tools';
import { ChatMessage, ChatRoom, User } from '../models';
import { ChatMessage, ChatParticipantsLog, ChatRoom, User } from '../models';
import { isArray, isNil } from 'lodash';
import { status } from '@grpc/grpc-js';
import { sendInvitations, validateUsersInput } from '../utils';
Expand Down Expand Up @@ -69,18 +69,11 @@ export class ChatRoutes {
} catch (e) {
throw new GrpcError(status.INTERNAL, (e as Error).message);
}
let room;
let room: ChatRoom;
const query: Query<ChatRoom> = {
name: roomName,
creator: user._id,
participants: [user._id],
participantsLog: [
{
user: user._id,
action: 'create',
timestamp: new Date(new Date().getUTCMilliseconds()),
},
],
};
const config = await this.grpcSdk.config.get('chat');
if (config.explicit_room_joins.enabled) {
Expand All @@ -89,6 +82,14 @@ export class ChatRoutes {
.catch((e: Error) => {
throw new GrpcError(status.INTERNAL, e.message);
});
const participantsLog = await ChatParticipantsLog.getInstance().create({
user: user._id,
action: 'create',
chatRoom: room._id,
});
room = (await ChatRoom.getInstance().findByIdAndUpdate(room._id, {
participantsLog: [participantsLog._id],
})) as ChatRoom;
const serverConfig = await this.grpcSdk.config.get('router');
await sendInvitations(
usersToBeAdded,
Expand All @@ -103,23 +104,26 @@ export class ChatRoutes {
});
} else {
query['participants'] = Array.from(new Set([user._id, ...users]));
query['participantsLog'] = [
room = await ChatRoom.getInstance()
.create(query)
.catch((e: Error) => {
throw new GrpcError(status.INTERNAL, e.message);
});
const participantsLog = await ChatParticipantsLog.getInstance().createMany([
{
user: user._id,
action: 'create',
timestamp: new Date(new Date().getUTCMilliseconds()),
chatRoom: room._id,
},
...users.map((userId: string) => ({
user: userId,
action: 'join' as 'join',
timestamp: new Date(new Date().getUTCMilliseconds()),
chatRoom: room._id,
})),
];
room = await ChatRoom.getInstance()
.create(query)
.catch((e: Error) => {
throw new GrpcError(status.INTERNAL, e.message);
});
]);
room = (await ChatRoom.getInstance().findByIdAndUpdate(room._id, {
participantsLog: participantsLog.map(log => log._id),
})) as ChatRoom;
}
this.grpcSdk.bus?.publish(
'chat:create:ChatRoom',
Expand Down Expand Up @@ -177,16 +181,19 @@ export class ChatRoutes {
});
return ret!;
} else {
const participantsLog = await ChatParticipantsLog.getInstance().createMany(
users.map((userId: string) => ({
user: userId,
action: 'join' as 'join',
chatRoom: room._id,
})),
);
await ChatRoom.getInstance()
.findByIdAndUpdate(room._id, {
participants: Array.from(new Set([...room.participants, ...users])),
participantsLog: [
...room.participantsLog,
...users.map((userId: string) => ({
user: userId,
action: 'join' as 'join',
timestamp: new Date(new Date().getUTCMilliseconds()),
})),
...participantsLog.map(log => log._id),
],
})
.catch((e: Error) => {
Expand All @@ -213,11 +220,13 @@ export class ChatRoutes {
const index = room.participants.indexOf(user._id);
if (index > -1) {
room.participants.splice(index, 1);
room.participantsLog.push({
const participantsLog = await ChatParticipantsLog.getInstance().create({
user: user._id,
action: 'leave' as 'leave',
timestamp: new Date(new Date().getUTCMilliseconds()),
chatRoom: room._id,
});

room.participantsLog.push(participantsLog);
if (
(room.participants.length === 1 &&
ConfigController.getInstance().config.deleteEmptyRooms) ||
Expand Down

0 comments on commit 87884d3

Please sign in to comment.