On Server Application Structure documentation page of Socket.io, two methods are presented to use modules for better code clarity. Those modules are CommonJS.
I managed to translate the first to ESM, but the syntax of the second one blocks me, with the (io) => containing multiple functions.
As a reference, here is the code :
index.js
const httpServer = require("http").createServer();
const io = require("socket.io")(httpServer);
const { createOrder, readOrder } = require("./orderHandler")(io);
const { updatePassword } = require("./userHandler")(io);
const onConnection = (socket) => {
socket.on("order:create", createOrder);
socket.on("order:read", readOrder);
socket.on("user:update-password", updatePassword);
}
io.on("connection", onConnection);
orderHandler.js
module.exports = (io) => {
const createOrder = function (payload) {
const socket = this; // hence the 'function' above, as an arrow function will not work
// ...
};
const readOrder = function (orderId, callback) {
// ...
};
return {
createOrder,
readOrder
}
}
What is your solution to translate those two files and keeping the same one-line clarity as :
socket.on("user:update-password", updatePassword);
Also, is there a specific terminology about this kind of export orderHandler.js ? (like something called “an arrowed object” or “topped class level export”)
I searched on Node.js documentation, without success.
With the help of AI, I managed a result, but the code became way less elegant (but still working).