refactor: responder... responds, elegance

This commit is contained in:
cha0s 2020-07-22 03:47:16 -05:00
parent 0ca11a0ec4
commit cc6d4e6250
12 changed files with 65 additions and 58 deletions

View File

@ -4,11 +4,10 @@ import {allModels} from '~/server/models/registrar';
export default {
Packet: AddFavorite,
validator: () => true,
responder: async (packet, socket, fn) => {
validator: async () => true,
responder: async (packet, socket) => {
const {req} = socket;
await req.user.createFavorite({channel: packet.data});
socket.to(`/user/${req.userId}`, packet);
fn();
},
};

View File

@ -1,21 +1,29 @@
import {validateUsername} from '~/common/channel';
import AddFriend from '~/common/packets/add-friend.packet';
import {allModels} from '~/server/models/registrar';
import ValidationError from './validation-error';
export default {
Packet: AddFriend,
validator: () => true,
responder: async (packet, socket, fn) => {
limiter: {points: 20, duration: 60},
validator: async ({data: {nameOrStatus}}) => {
if (!validateUsername(nameOrStatus)) {
throw new ValidationError('Invalid username');
}
},
responder: async (packet, socket) => {
const {req} = socket;
const {
Friendship,
User,
} = allModels();
const adderId = req.user.id;
const user = await User.findOne({where: {redditUsername: packet.data.nameOrStatus}});
if (!user) {
return;
}
const user = (
await User.findOne({where: {redditUsername: packet.data.nameOrStatus}})
|| await User.create({redditUsername: packet.data.nameOrStatus})
);
const addeeId = user.id;
let friendship = await Friendship.findOne({where: {adderId: addeeId, addeeId: adderId}});
const friendshipIsActive = !!friendship;
@ -33,6 +41,6 @@ export default {
nameOrStatus: friendship.status,
}));
});
fn(addeeId);
return addeeId;
},
};

View File

@ -9,8 +9,8 @@ import {removeFavoritedUser} from './remove-favorite';
export default {
Packet: Block,
validator: () => true,
responder: async (packet, socket, fn) => {
validator: async () => true,
responder: async (packet, socket) => {
const {req} = socket;
const id = packet.data;
const {Friendship, User} = allModels();
@ -29,6 +29,5 @@ export default {
socket.to(`/user/${req.userId}`, packet);
socket.to(`/user/${id}`, new RemoveFriend(req.userId));
socket.to(`/user/${req.userId}`, new RemoveFriend(id));
fn();
},
};

View File

@ -21,11 +21,11 @@ export const userJoin = async (channel, socket) => {
export default {
Packet: Join,
validator: () => true,
responder: async (packet, socket, fn) => {
validator: async () => true,
responder: async (packet, socket) => {
const {req} = socket;
const {channel} = packet.data;
await userJoin(channel, socket.socket);
fn(await channelState(req, channel));
return channelState(req, channel);
},
};

View File

@ -16,10 +16,9 @@ export const userLeave = async (channel, socket) => {
export default {
Packet: Leave,
validator: () => true,
responder: async (packet, socket, fn) => {
validator: async () => true,
responder: async (packet, socket) => {
const {channel} = packet.data;
await userLeave(channel, socket);
fn();
return userLeave(channel, socket);
},
};

View File

@ -8,7 +8,7 @@ import {allModels} from '~/server/models/registrar';
export default {
Packet: Message,
limiter: {points: 10, duration: 15},
validator: () => true,
validator: async () => true,
responder: async (packet, socket, fn) => {
const {req} = socket;
const {pubClient} = req.adapter;
@ -35,15 +35,17 @@ export default {
uuid,
}))
));
pubClient
.multi()
.set(key, JSON.stringify({
message,
owner,
socket: socket.id,
timestamp,
}))
.expire(key, '/r/anonymous' === channel ? 60 : 600)
.exec(() => fn([timestamp, uuid]));
return new Promise((resolve, reject) => {
pubClient
.multi()
.set(key, JSON.stringify({
message,
owner,
socket: socket.id,
timestamp,
}))
.expire(key, '/r/anonymous' === channel ? 60 : 600)
.exec((error) => (error ? reject(error) : resolve([timestamp, uuid])));
});
},
};

View File

@ -18,8 +18,8 @@ export const removeFavoritedUser = async (socket, user, other) => {
export default {
Packet: RemoveFavorite,
validator: () => true,
responder: async (packet, socket, fn) => {
validator: async () => true,
responder: async (packet, socket) => {
const {req} = socket;
const {Favorite} = allModels();
const favorites = await req.user.getFavorites();
@ -30,6 +30,5 @@ export default {
},
});
socket.to(`/user/${req.userId}`, packet);
fn();
},
},
};

View File

@ -8,8 +8,8 @@ import {removeFavoritedUser} from './remove-favorite';
export default {
Packet: RemoveFriend,
validator: () => true,
responder: async (packet, socket, fn) => {
validator: async () => true,
responder: async (packet, socket) => {
const {req} = socket;
const id = packet.data;
const {Friendship, User} = allModels();
@ -26,6 +26,5 @@ export default {
const user = await User.findByPk(id);
removeFavoritedUser(socket, user, req.user);
removeFavoritedUser(socket, req.user, user);
fn();
},
};

View File

@ -4,8 +4,8 @@ import {allModels} from '~/server/models/registrar';
export default {
Packet: Unblock,
validator: () => true,
responder: async (packet, socket, fn) => {
validator: async () => true,
responder: async (packet, socket) => {
const {req} = socket;
const {Block: BlockModel} = allModels();
await BlockModel.destroy({
@ -15,6 +15,5 @@ export default {
},
});
socket.to(`/user/${req.userId}`, packet);
fn();
},
};

View File

@ -4,11 +4,11 @@ import {allModels} from '~/server/models/registrar';
export default {
Packet: Usernames,
validator: () => true,
responder: async (packet, socket, fn) => {
validator: async () => true,
responder: async (packet) => {
const {User} = allModels();
fn(await Promise.all(packet.data.map(
return Promise.all(packet.data.map(
async (id) => (await User.findByPk(id)).redditUsername,
)));
));
},
};

View File

@ -0,0 +1 @@
export default class ValidationError extends Error {}

View File

@ -63,22 +63,24 @@ export function createSocketServer(httpServer) {
});
socketServer.on('connect', (socket) => {
socket.on('packet', async (packet, fn) => {
const {limiter, responder} = packetHandlers.get(packet.constructor);
if (limiter) {
try {
const {limiter, responder, validator} = packetHandlers.get(packet.constructor);
try {
if (limiter) {
await limiter.consume(socket.id);
responder(packet, socket, (...args) => fn(undefined, ...args));
}
catch (error) {
if (error instanceof Error) {
fn({code: 500});
throw error;
}
fn({code: 429, ttr: Math.round(error.msBeforeNext / 1000) || 1});
}
await validator(packet, socket);
fn(undefined, await responder(packet, socket));
}
else {
responder(packet, socket, (...args) => fn(undefined, ...args));
catch (error) {
if (error instanceof Error) {
fn({code: 500});
throw error;
}
if (error.msBeforeNext) {
fn({code: 429, ttr: Math.round(error.msBeforeNext / 1000) || 1});
return;
}
fn(error);
}
});
socket.on('disconnecting', async () => {