/
gateway.service.ts
54 lines (45 loc) 路 1.57 KB
/
gateway.service.ts
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
import type { SocketMetadata } from '~/types/socket-meta'
import type { RemoteSocket, Socket } from 'socket.io'
import type {
DecorateAcknowledgementsWithMultipleResponses,
DefaultEventsMap,
} from 'socket.io/dist/typed-events'
import { Injectable } from '@nestjs/common'
import { RedisKeys } from '~/constants/cache.constant'
import { getRedisKey, safeJSONParse } from '~/utils'
import { CacheService } from '../redis/cache.service'
export type SocketType =
| Socket<DefaultEventsMap, DefaultEventsMap, DefaultEventsMap, any>
| RemoteSocket<
DecorateAcknowledgementsWithMultipleResponses<DefaultEventsMap>,
any
>
@Injectable()
export class GatewayService {
constructor(private readonly cacheService: CacheService) {
cacheService.getClient().del(getRedisKey(RedisKeys.Socket))
}
async setSocketMetadata(socket: SocketType, value: object) {
const existValue = await this.getSocketMetadata(socket)
const client = this.cacheService.getClient()
const data = {
...existValue,
...value,
}
// socket.data = data
await client.hset(
getRedisKey(RedisKeys.Socket),
socket.id,
JSON.stringify(data),
)
}
async getSocketMetadata(socket: SocketType): Promise<SocketMetadata> {
const client = this.cacheService.getClient()
const data = await client.hget(getRedisKey(RedisKeys.Socket), socket.id)
return safeJSONParse(data) || {}
}
async clearSocketMetadata(socket: SocketType) {
const client = this.cacheService.getClient()
await client.hdel(getRedisKey(RedisKeys.Socket), socket.id)
}
}