47 lines
1.2 KiB
TypeScript
47 lines
1.2 KiB
TypeScript
// server/socketio.ts
|
|
import type { NextApiRequest, NextApiResponse } from 'next';
|
|
import { Server as IOServer } from 'socket.io';
|
|
import type { Server as HTTPServer } from 'http';
|
|
|
|
// TS-Hilfstypen
|
|
type NextApiResponseWithSocket = NextApiResponse & {
|
|
socket: {
|
|
server: HTTPServer & {
|
|
io?: IOServer;
|
|
};
|
|
};
|
|
};
|
|
|
|
export default function handler(
|
|
_req: NextApiRequest,
|
|
res: NextApiResponseWithSocket,
|
|
) {
|
|
if (!res.socket.server.io) {
|
|
const io = new IOServer(res.socket.server, {
|
|
path: '/api/socketio',
|
|
cors: {
|
|
origin: '*', // für lokal egal, in Produktion einschränken
|
|
},
|
|
});
|
|
|
|
// global speichern, damit wir aus anderen Routen darauf zugreifen können
|
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
(global as any).devicesIo = io;
|
|
|
|
io.on('connection', (socket) => {
|
|
console.log('[Socket.IO] client connected', socket.id);
|
|
|
|
socket.on('disconnect', () => {
|
|
console.log('[Socket.IO] client disconnected', socket.id);
|
|
});
|
|
});
|
|
|
|
res.socket.server.io = io;
|
|
console.log('[Socket.IO] server initialized');
|
|
} else {
|
|
console.log('[Socket.IO] server already running');
|
|
}
|
|
|
|
res.end();
|
|
}
|