1 100
import {
2
    BreakMiddleware,
3
    SocketOn,
4
    SocketOnByHandler,
5
    SocketServerOnByHandler,
6
    SocketServerEvents,
7
    SocketServerOn
8
} from "../../index";
9 100
import SocketIOStatic = require("socket.io");
10 100
import {SocketHandler} from "../../services/socket-handler.adapter";
11 100
import {Injectable, ComparableSchema, SchemaTypes} from "@sugoi/core";
12 100
import {SocketSchemaPolicy} from "../../decorators/schema-policy.decorator";
13

14 100
const instanceId = SocketHandler.IDPrefix + SocketHandler.COUNTER_START;
15

16
@Injectable()
17 100
export class SocketService {
18 100
    static connectedAmount = 0;
19 100
    static socketIds = {};
20
    static lastMessage: string;
21
    static lastConnected: string;
22 0
    public message = "wow!";
23

24
    @SocketOn(SocketServerEvents.DISCONNECT, "/")
25 100
    static handleDisconnect(socket: SocketIOStatic.Socket, data) {
26 100
        SocketService.connectedAmount--;
27 100
        console.log("disconnection, amount: %s", SocketService.connectedAmount);
28
    }
29

30

31 100
    @SocketOnByHandler("message", "/", instanceId, ((socket, data: any) => {
32 100
        if (!data) {
33 100
            BreakMiddleware()
34
        }
35 100
        data.timestamp = new Date();
36
    }))
37
    @SocketSchemaPolicy({msg:ComparableSchema.ofType(SchemaTypes.STRING).setMandatory(true)})
38 100
    static getMessage(socket, data) {
39 100
        this.lastMessage = data;
40
    }
41

42 100
    @SocketServerOn(SocketServerEvents.CONNECTION, "/", ((socket, data) => SocketService.socketIds[socket.id] = true ))
43 100
    static handleConnection(socket: SocketIOStatic.Socket) {
44 100
        SocketService.connectedAmount++;
45 100
        console.log("new connection %s, amount: %s", socket.id, SocketService.connectedAmount);
46 100
        socket.emit("connected", {status: true})
47
    }
48

49 100
    @SocketServerOnByHandler(SocketServerEvents.CONNECTION, "/", instanceId, ((socket, data) => {
50 100
        SocketService.lastConnected = socket.id;
51 100
        BreakMiddleware()
52
    }))
53 100
    static handleConnection2(socket, data) {
54 0
        SocketService.lastConnected = null;
55
    }
56
}

Read our documentation on viewing source code .

Loading