-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
88 lines (80 loc) · 2.06 KB
/
index.js
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
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
import { createClient } from 'redis';
import consola from 'consola';
import { red, cyan } from 'kolorist';
console.clear()
consola.info('Starting NodeJS Microservice ')
consola.info('Service is running')
const client = createClient()
const subscriber = client.duplicate();
await subscriber.connect();
const publisher = client.duplicate();
await publisher.connect();
consola.success('connected to redis client')
/**
* isEmitter 判断是否为 event-based 模式
*
* 通过 JSON.stringify 判断是否为 event-based 模式。
* 原理:在 event-based 模式下, pattern 是不带 cmd 的。
*
* @param {string} pattern 模式
* @returns boolean
*/
function isEmitter(pattern) {
try {
JSON.stringify(pattern)
return false
} catch {
return true
}
}
/**
* 解析来自 NestJS Gateway 发布的信息
* @param {string} message
* @returns object
*/
function parseEventDataFromGateway(message) {
message = JSON.parse(message)
return {
id: message.id,
data: message.data,
pattern: JSON.stringify(message.pattern),
isEmitter: isEmitter(message.pattern),
}
}
/**
* 快捷生成模式
* @param {string} pattern 活动名称
* @param {boolean} isEmit 是否为 event-based 模式
* @returns string
*/
function generagtePattern(pattern, isEmit) {
if (!isEmit) {
return JSON.stringify({ cmd: pattern })
}
return pattern
}
/**
* 生成响应数据
* @param {string} id 事件ID
* @param {string | object} data 事件数据
* @returns string
*/
function generagteResponse(id, data) {
return JSON.stringify(
{
response: data,
isDisposed: true,
id,
}
)
}
const pattern = generagtePattern("user.get.master", false)
await subscriber.subscribe(pattern, async (message) => {
const { id, data, pattern, isEmitter } = parseEventDataFromGateway(message)
console.log("Message: ", message)
console.log("Event ID: ", id)
console.log("Data: ", data)
console.log("Pattern: ", pattern)
console.log("isEmitter: ", isEmitter)
await publisher.publish(`${pattern}.reply`, generagteResponse(id, { name: 'test' }))
});