Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Handler: client, getAllClients, getAllRooms and withRooms().getClients() #16

Merged
merged 3 commits into from
Feb 8, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions example/actions/chat.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,9 @@ import { actionsFactory } from "../factories";

export const onChat = actionsFactory.build({
input: z.tuple([z.string()]),
handler: async ({ input: [message], socketId, broadcast, logger }) => {
handler: async ({ input: [message], client, broadcast, logger }) => {
try {
broadcast("chat", message, { from: socketId });
broadcast("chat", message, { from: client.id });
} catch (error) {
logger.error("Failed to broadcast", error);
}
Expand Down
4 changes: 2 additions & 2 deletions example/actions/subscribe.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,15 +4,15 @@ import { actionsFactory } from "../factories";
/** @desc The action demonstrates no acknowledgement and constraints on emission awareness */
export const onSubscribe = actionsFactory.build({
input: z.tuple([]).rest(z.unknown()),
handler: async ({ logger, emit, isConnected }) => {
handler: async ({ logger, emit, client }) => {
logger.info("Subscribed");
while (true) {
try {
emit("time", new Date()); // <— payload type constraints
await new Promise<void>((resolve, reject) => {
const timer = setTimeout(() => {
clearTimeout(timer);
if (!isConnected()) {
if (!client.isConnected()) {
reject("Disconnected");
}
resolve();
Expand Down
52 changes: 37 additions & 15 deletions src/action.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,8 @@ describe("Action", () => {
const isConnectedMock = vi.fn();
const withRoomsMock = vi.fn();
const getRoomsMock = vi.fn();
const getAllRoomsMock = vi.fn();
const getAllClientsMock = vi.fn();

test("should handle simple action", async () => {
await simpleAction.execute({
Expand All @@ -42,20 +44,28 @@ describe("Action", () => {
emit: emitMock,
broadcast: broadcastMock,
withRooms: withRoomsMock,
getRooms: getRoomsMock,
isConnected: isConnectedMock,
socketId: "ID",
getAllClients: getAllClientsMock,
getAllRooms: getAllRoomsMock,
client: {
getRooms: getRoomsMock,
isConnected: isConnectedMock,
id: "ID",
},
});
expect(loggerMock.error).not.toHaveBeenCalled();
expect(simpleHandler).toHaveBeenLastCalledWith({
broadcast: broadcastMock,
withRooms: withRoomsMock,
getRooms: getRoomsMock,
getAllClients: getAllClientsMock,
getAllRooms: getAllRoomsMock,
emit: emitMock,
input: ["some"],
isConnected: isConnectedMock,
logger: loggerMock,
socketId: "ID",
client: {
isConnected: isConnectedMock,
getRooms: getRoomsMock,
id: "ID",
},
});
});

Expand All @@ -68,20 +78,28 @@ describe("Action", () => {
emit: emitMock,
broadcast: broadcastMock,
withRooms: withRoomsMock,
getRooms: getRoomsMock,
isConnected: isConnectedMock,
socketId: "ID",
getAllClients: getAllClientsMock,
getAllRooms: getAllRoomsMock,
client: {
getRooms: getRoomsMock,
isConnected: isConnectedMock,
id: "ID",
},
});
expect(loggerMock.error).not.toHaveBeenCalled();
expect(ackHandler).toHaveBeenLastCalledWith({
client: {
id: "ID",
getRooms: getRoomsMock,
isConnected: isConnectedMock,
},
broadcast: broadcastMock,
withRooms: withRoomsMock,
getRooms: getRoomsMock,
getAllClients: getAllClientsMock,
getAllRooms: getAllRoomsMock,
emit: emitMock,
input: ["some"],
isConnected: isConnectedMock,
logger: loggerMock,
socketId: "ID",
});
expect(ackMock).toHaveBeenLastCalledWith(123); // from ackHandler
});
Expand All @@ -94,9 +112,13 @@ describe("Action", () => {
emit: emitMock,
broadcast: broadcastMock,
withRooms: withRoomsMock,
getRooms: getRoomsMock,
isConnected: isConnectedMock,
socketId: "ID",
getAllClients: getAllClientsMock,
getAllRooms: getAllRoomsMock,
client: {
getRooms: getRoomsMock,
isConnected: isConnectedMock,
id: "ID",
},
});
expect(loggerMock.error).toHaveBeenCalled();
});
Expand Down
17 changes: 9 additions & 8 deletions src/action.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,34 +4,36 @@ import { z } from "zod";
import { ActionNoAckDef, ActionWithAckDef } from "./actions-factory";
import { Broadcaster, EmissionMap, Emitter, RoomService } from "./emission";
import { AbstractLogger } from "./logger";
import { RemoteClint } from "./utils";

export interface SocketFeatures {
export interface Client {
isConnected: () => boolean;
socketId: Socket["id"];
id: Socket["id"];
getRooms: () => string[];
}

export interface HandlingFeatures<E extends EmissionMap> {
client: Client;
logger: AbstractLogger;
emit: Emitter<E>;
broadcast: Broadcaster<E>;
withRooms: RoomService<E>;
getAllRooms: () => string[];
getAllClients: () => Promise<RemoteClint[]>;
}

export type Handler<IN, OUT, E extends EmissionMap> = (
params: {
input: IN;
} & SocketFeatures &
HandlingFeatures<E>,
} & HandlingFeatures<E>,
) => Promise<OUT>;

export abstract class AbstractAction {
public abstract execute(
params: {
event: string;
params: unknown[];
} & SocketFeatures &
HandlingFeatures<EmissionMap>,
} & HandlingFeatures<EmissionMap>,
): Promise<void>;
}

Expand Down Expand Up @@ -88,8 +90,7 @@ export class Action<
}: {
event: string;
params: unknown[];
} & SocketFeatures &
HandlingFeatures<EmissionMap>): Promise<void> {
} & HandlingFeatures<EmissionMap>): Promise<void> {
try {
const input = this.#parseInput(params);
logger.debug(
Expand Down
49 changes: 41 additions & 8 deletions src/attach.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,9 +13,23 @@ describe("Attach", () => {
on: vi.fn(),
onAny: vi.fn(),
};
const adapterMock = {
rooms: new Map([
["room1", ["ID"]],
["room2", ["ID"]],
["room3", ["other"]],
]),
};
const ioMock = {
on: vi.fn(),
attach: vi.fn(),
of: vi.fn(() => ({
adapter: adapterMock,
})),
fetchSockets: vi.fn(async () => [
{ id: "ID", rooms: new Set(["room1", "room2"]) },
{ id: "other", rooms: new Set(["room3"]) },
]),
};
const targetMock = {
address: vi.fn(),
Expand Down Expand Up @@ -68,25 +82,44 @@ describe("Attach", () => {
expect(actionsMock.test.execute).toHaveBeenLastCalledWith({
broadcast: expect.any(Function),
withRooms: expect.any(Function),
getRooms: expect.any(Function),
getAllClients: expect.any(Function),
getAllRooms: expect.any(Function),
emit: expect.any(Function),
event: "test",
isConnected: expect.any(Function),
logger: loggerMock,
params: [[123, 456]],
socketId: "ID",
client: {
id: "ID",
isConnected: expect.any(Function),
getRooms: expect.any(Function),
},
});

// getRooms:
expect(actionsMock.test.execute.mock.lastCall[0].getRooms()).toEqual([
"room1",
"room2",
]);
expect(
actionsMock.test.execute.mock.lastCall[0].client.getRooms(),
).toEqual(["room1", "room2"]);

// isConnected:
expect(
actionsMock.test.execute.mock.lastCall[0].isConnected(),
actionsMock.test.execute.mock.lastCall[0].client.isConnected(),
).toBeFalsy();

// getAllRooms:
expect(actionsMock.test.execute.mock.lastCall[0].getAllRooms()).toEqual([
"room1",
"room2",
"room3",
]);
expect(ioMock.of).toHaveBeenLastCalledWith("/");

// getAllClients:
await expect(
actionsMock.test.execute.mock.lastCall[0].getAllClients(),
).resolves.toEqual([
{ id: "ID", rooms: ["room1", "room2"] },
{ id: "other", rooms: ["room3"] },
]);
});
});
});
29 changes: 18 additions & 11 deletions src/attach.ts
Original file line number Diff line number Diff line change
@@ -1,25 +1,26 @@
import http from "node:http";
import type { Server } from "socket.io";
import { ActionMap, Handler, HandlingFeatures, SocketFeatures } from "./action";
import { ActionMap, Handler, HandlingFeatures } from "./action";
import { Config } from "./config";
import {
EmissionMap,
makeBroadcaster,
makeEmitter,
makeRoomService,
} from "./emission";
import { mapFetchedSockets } from "./utils";

export const attachSockets = <E extends EmissionMap>({
io,
actions,
target,
config,
onConnection = ({ socketId }) =>
config.logger.debug("User connected", socketId),
onDisconnect = ({ socketId }) =>
config.logger.debug("User disconnected", socketId),
onAnyEvent = ({ input: [event], socketId }) =>
config.logger.debug(`${event} from ${socketId}`),
onConnection = ({ client }) =>
config.logger.debug("User connected", client.id),
onDisconnect = ({ client }) =>
config.logger.debug("User disconnected", client.id),
onAnyEvent = ({ input: [event], client }) =>
config.logger.debug(`${event} from ${client.id}`),
}: {
/**
* @desc The Socket.IO server
Expand All @@ -44,18 +45,24 @@ export const attachSockets = <E extends EmissionMap>({
onAnyEvent?: Handler<[string], void, E>;
}): Server => {
config.logger.info("ZOD-SOCKETS", target.address());
const getAllRooms = () => Array.from(io.of("/").adapter.rooms.keys());
const getAllClients = async () => mapFetchedSockets(await io.fetchSockets());
io.on("connection", async (socket) => {
const emit = makeEmitter({ socket, config });
const broadcast = makeBroadcaster({ socket, config });
const withRooms = makeRoomService({ socket, config });
const commons: SocketFeatures & HandlingFeatures<E> = {
socketId: socket.id,
isConnected: () => socket.connected,
getRooms: () => Array.from(socket.rooms),
const commons: HandlingFeatures<E> = {
client: {
id: socket.id,
isConnected: () => socket.connected,
getRooms: () => Array.from(socket.rooms),
},
logger: config.logger,
emit,
broadcast,
withRooms,
getAllClients,
getAllRooms,
};
await onConnection({ input: [], ...commons });
socket.onAny((event) => onAnyEvent({ input: [event], ...commons }));
Expand Down
14 changes: 12 additions & 2 deletions src/emission.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,12 +6,16 @@ import { AbstractLogger } from "./logger";

describe("Emission", () => {
const broadcastMock: Record<
"emit" | "timeout" | "emitWithAck",
"emit" | "timeout" | "emitWithAck" | "fetchSockets",
MockedFunction<any>
> = {
emit: vi.fn(),
timeout: vi.fn(() => broadcastMock),
emitWithAck: vi.fn(),
fetchSockets: vi.fn(async () => [
{ id: "ID", rooms: new Set(["room1", "room2"]) },
{ id: "other", rooms: new Set(["room3"]) },
]),
};

const socketMock: Record<
Expand All @@ -21,13 +25,15 @@ describe("Emission", () => {
id: string;
broadcast: typeof broadcastMock;
to: (rooms: string | string[]) => typeof broadcastMock;
in: (rooms: string | string[]) => typeof broadcastMock;
} = {
id: "ID",
emit: vi.fn(),
timeout: vi.fn(() => socketMock),
emitWithAck: vi.fn(),
broadcast: broadcastMock,
to: vi.fn(() => broadcastMock),
in: vi.fn(() => broadcastMock),
join: vi.fn(),
leave: vi.fn(),
};
Expand Down Expand Up @@ -80,7 +86,7 @@ describe("Emission", () => {
config,
});
expect(typeof withRooms).toBe("function");
const { broadcast, leave, join } = withRooms(rooms);
const { broadcast, leave, join, getClients } = withRooms(rooms);
expect(socketMock.to).toHaveBeenLastCalledWith(rooms);
for (const method of [broadcast, leave, join]) {
expect(typeof method).toBe("function");
Expand All @@ -96,6 +102,10 @@ describe("Emission", () => {
expect(socketMock.leave).toHaveBeenCalledWith(room);
}
}
await expect(getClients()).resolves.toEqual([
{ id: "ID", rooms: ["room1", "room2"] },
{ id: "other", rooms: ["room3"] },
]);
},
);
});
Expand Down
4 changes: 4 additions & 0 deletions src/emission.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import assert from "node:assert/strict";
import type { Socket } from "socket.io";
import { z } from "zod";
import { Config } from "./config";
import { RemoteClint, mapFetchedSockets } from "./utils";

export interface Emission {
schema: z.AnyZodTuple;
Expand Down Expand Up @@ -31,6 +32,7 @@ export type RoomService<E extends EmissionMap> = (rooms: string | string[]) => {
broadcast: Broadcaster<E>;
join: () => void | Promise<void>;
leave: () => void | Promise<void>;
getClients: () => Promise<RemoteClint[]>;
};

/**
Expand Down Expand Up @@ -84,6 +86,8 @@ export const makeRoomService =
...rest
}: MakerParams<E>): RoomService<E> =>
(rooms) => ({
getClients: async () =>
mapFetchedSockets(await socket.in(rooms).fetchSockets()),
join: () => socket.join(rooms),
leave: () =>
typeof rooms === "string"
Expand Down
Loading