Skip to content

Commit

Permalink
Untested - Update Guild Members when Delete Guild
Browse files Browse the repository at this point in the history
  • Loading branch information
theADAMJR committed Aug 12, 2021
1 parent d253ecb commit 19b4496
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 10 deletions.
30 changes: 22 additions & 8 deletions backend/src/ws/events/guild-delete.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,12 +3,13 @@ import { Socket } from 'socket.io';
import { WS } from '../websocket';
import { Guild } from '../../data/models/guild';
import { User } from '../../data/models/user';
import SessionManager from '../session-manager';

export default class implements WSEvent<'GUILD_DELETE'> {
public on = 'GUILD_DELETE' as const;

public async invoke({ sessions }: WS, client: Socket, { guildId }: API.WSPayload.GuildDelete) {
const userId = sessions.get(client.id);
public async invoke(ws: WS, client: Socket, { guildId }: API.WSPayload.GuildDelete) {
const userId = ws.sessions.get(client.id);
const guild = await Guild.findById(guildId);
if (!guild)
throw new TypeError('Guild not found');
Expand All @@ -17,13 +18,26 @@ export default class implements WSEvent<'GUILD_DELETE'> {
throw new TypeError('Only the guild owner can do this');

await guild.deleteOne();

// remove guild id from all member.guildIds
await User.updateOne(
{ guildIds: guildId },
{ $pull: { guildIds: guildId } },
);
await this.updateMembers(ws, guild);

client.emit('GUILD_DELETE', { guildId } as API.WSResponse.GuildDelete);
}

private async updateMembers({ sessions, io }: WS, guild: Entity.Guild) {
// is it better to iterate User.findOne, or just use User.find once?
const users = await User.find({ guildIds: guild.id });

// tell connected guild members that they're no longer in that guild
const clientIds = io.sockets.adapter.rooms.get(guild.id)!;
for (const clientId of clientIds) {
const client = io.sockets.sockets.get(clientId)!;
const { guildIds } = users.find(u => u.id === sessions.get(clientId))!;

const index = guildIds.indexOf(guild.id);
guildIds.splice(index, 1);

client.emit('USER_UPDATE', { payload: { guildIds } } as API.WSResponse.UserUpdate);
client.leave(guild.id);
}
}
}
4 changes: 2 additions & 2 deletions frontend/src/components/ws-listener.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -85,9 +85,9 @@ const WSListener: React.FunctionComponent = () => {
dispatch(users.fetched(args.user));
});
ws.on('USER_DELETE', () => {
dispatch(logoutUser());
history.push('/');
ws.disconnect();
history.push('/');
dispatch(logoutUser());
});
ws.on('USER_UPDATE', (args) => {
// update member in guild
Expand Down

0 comments on commit 19b4496

Please sign in to comment.