|
| 1 | +/* eslint-disable no-underscore-dangle */ |
| 2 | +import { fileURLToPath } from 'url'; |
| 3 | +import path, { dirname } from 'path'; |
| 4 | + |
| 5 | +import express from 'express'; |
| 6 | +import asyncHandler from 'express-async-handler'; |
| 7 | +import { Server } from 'socket.io'; |
| 8 | + |
| 9 | +import { executeWithAdminRights, getEnvValue, isEnvTrue } from 'hlambda'; |
| 10 | + |
| 11 | +// // Define constants & errors |
| 12 | +// import constants from "./../../constants/constants.index.js"; |
| 13 | +import errors from './errors.socket-io.js'; |
| 14 | + |
| 15 | +const __filename = fileURLToPath(import.meta.url); |
| 16 | +const __dirname = dirname(__filename); |
| 17 | + |
| 18 | +// Pull from global scope hlambdaEventEmitter |
| 19 | +const { hlambdaEventEmitter } = global; |
| 20 | +// -------------------------------------------------------------------------------- |
| 21 | +// Why do we do this? |
| 22 | +// Hlambda emitts event 'server-ready' when the server starts to listen. In that event we have reference to server instance. |
| 23 | +// Socket.io needs that server instance reference to work. This is not necessary if you want to run another server on different port. |
| 24 | +let io; |
| 25 | +const attachSocketIoServer = async (server) => { |
| 26 | + // const server = await global.HLAMBDA_SERVER_INSTANCE; |
| 27 | + // const io = new Server(server, {}); |
| 28 | + io = new Server(server, {}); // We want to use io from router. |
| 29 | + |
| 30 | + io.on('connection', (socket) => { |
| 31 | + console.log('Socket connected!'); |
| 32 | + |
| 33 | + socket.on('chat message', (msg) => { |
| 34 | + io.emit('chat message', msg); |
| 35 | + }); |
| 36 | + |
| 37 | + socket.on('disconnect', () => { |
| 38 | + console.log('Socket disconnected!'); |
| 39 | + }); |
| 40 | + }); |
| 41 | +}; |
| 42 | + |
| 43 | +// Listen for event. |
| 44 | +hlambdaEventEmitter.on('server-ready', (server) => { |
| 45 | + console.log(`[hlambdaEventEmitter] 'server-ready' event occurred!`.green); |
| 46 | + attachSocketIoServer(server); |
| 47 | +}); |
| 48 | +// -------------------------------------------------------------------------------- |
| 49 | + |
| 50 | +// Create express router |
| 51 | +const router = express.Router(); |
| 52 | + |
| 53 | +// Example of serving static files on route /io |
| 54 | +router.use('/io', express.static(path.resolve(__dirname, './public'))); |
| 55 | + |
| 56 | +router.get( |
| 57 | + '/io/msg', |
| 58 | + asyncHandler((req, res) => { |
| 59 | + if (typeof io === 'undefined') { |
| 60 | + throw new Error(errors.SOCKET_SERVER_NOT_RUNNING); |
| 61 | + } |
| 62 | + |
| 63 | + io.emit('chat message', 'Server message!'); |
| 64 | + |
| 65 | + res.json({ |
| 66 | + done: true, |
| 67 | + }); |
| 68 | + }) |
| 69 | +); |
| 70 | + |
| 71 | +export default router; |
0 commit comments