-
-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathattach.ts
More file actions
129 lines (128 loc) · 4.26 KB
/
attach.ts
File metadata and controls
129 lines (128 loc) · 4.26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
import http from "node:http";
import type { Server } from "socket.io";
import { AbstractAction } from "./action";
import { Client } from "./client";
import { ensureError } from "./common-helpers";
import { Config } from "./config";
import { makeDistribution } from "./distribution";
import { EmitterConfig, makeEmitter, makeRoomService } from "./emission";
import { ClientContext, IndependentContext } from "./handler";
import { defaultHooks } from "./hooks";
import { AbstractLogger } from "./logger";
import { Namespaces, normalizeNS } from "./namespace";
import { makeRemoteClients } from "./remote-client";
import { getStartupLogo } from "./startup-logo";
export const attachSockets = async <NS extends Namespaces>({
io,
actions,
target,
config: { namespaces, timeout, startupLogo = true },
logger: rootLogger = console,
}: {
/**
* @desc The Socket.IO server
* @example new Server()
* */
io: Server;
/**
* @desc The array of handling rules for the incoming Socket.IO events
* @example [ onPing ]
* */
actions: AbstractAction[];
/**
* @desc HTTP or HTTPS server to attach the sockets to
* @example http.createServer().listen(8090)
* */
target: http.Server;
/** @desc The configuration describing the emission (outgoing events) */
config: Config<NS>;
/**
* @desc The instance of a logger
* @default console
* */
logger?: AbstractLogger;
}): Promise<Server> => {
for (const name in namespaces) {
type NSEmissions = NS[typeof name]["emission"];
type NSMeta = NS[typeof name]["metadata"];
const ns = io.of(normalizeNS(name));
const { emission, hooks, metadata } = namespaces[name];
const {
onConnection,
onDisconnect,
onAnyIncoming,
onAnyOutgoing,
onStartup,
onError,
} = { ...defaultHooks, ...hooks };
const emitCfg: EmitterConfig<NSEmissions> = { emission, timeout };
const nsCtx: IndependentContext<NSEmissions, NSMeta> = {
logger: rootLogger,
withRooms: makeRoomService({ subject: ns, metadata, ...emitCfg }),
all: {
getClients: async () =>
makeRemoteClients({
sockets: await ns.fetchSockets(),
metadata,
...emitCfg,
}),
getRooms: () => Array.from(ns.adapter.rooms.keys()),
broadcast: makeEmitter({ subject: ns, ...emitCfg }),
},
};
ns.on("connection", async (socket) => {
const emit = makeEmitter({ subject: socket, ...emitCfg });
const broadcast = makeEmitter({ subject: socket.broadcast, ...emitCfg });
const client: Client<NSEmissions, NSMeta> = {
emit,
broadcast,
id: socket.id,
handshake: socket.handshake,
getRequest: <T extends http.IncomingMessage>() => socket.request as T,
isConnected: () => socket.connected,
getRooms: () => Array.from(socket.rooms),
getData: () => socket.data || {},
setData: (value) => {
metadata.parse(value); // validation only, no transformations
socket.data = value;
},
...makeDistribution(socket),
};
const ctx: ClientContext<NSEmissions, NSMeta> = {
...nsCtx,
client,
withRooms: makeRoomService({ subject: ns, metadata, ...emitCfg }),
};
await onConnection(ctx);
socket.onAny((event, ...payload) =>
onAnyIncoming({ event, payload, ...ctx }),
);
socket.onAnyOutgoing((event, ...payload) =>
onAnyOutgoing({ event, payload, ...ctx }),
);
for (const action of actions) {
if (action.namespace === name) {
const { event } = action;
socket.on(event, async (...params) => {
try {
return await action.execute({ params, ...ctx }); // await required
} catch (error) {
return onError({
...ctx,
event,
payload: params,
error: ensureError(error),
});
}
});
}
}
socket.on("disconnect", () => onDisconnect(ctx));
});
await onStartup(nsCtx);
}
(startupLogo ? console.log : () => {})(getStartupLogo());
rootLogger.debug("Running", process.env.TSDOWN_BUILD || "from sources");
rootLogger.info("Listening", target.address());
return io.attach(target);
};