-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathindex.js
93 lines (91 loc) · 2.2 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
89
90
91
92
93
const helper = require('think-helper');
const assert = require('assert');
const deprecate = require('depd')('think-websocket');
module.exports = app => {
let instance;
app.on('appReady', () => {
const config = helper.parseAdapterConfig(app.think.config('websocket'));
const Handle = config.handle;
assert(helper.isFunction(Handle), 'websocket.handle must be a function');
instance = new Handle(app.server, config, app);
instance.run();
app.websocket = instance;
});
return {
context: {
/**
* get socket data
*/
get data() {
deprecate('ctx.data is deprecated, use ctx.wsData instead');
return this.req.websocketData;
},
/**
* get socket data
*/
get wsData() {
return this.req.websocketData;
},
/**
* get wsCallback
*/
get wsCallback() {
return this.req.wsCallback;
},
/**
* get socket
*/
get websocket() {
return this.req.websocket;
},
/**
* is websocket request
*/
get isWebsocket() {
return this.isMethod('WEBSOCKET');
},
/**
* emit an event
* @param {String} event
* @param {Mixed} data
*/
emit(event, data) {
this.res.statusCode = 200;
instance.emit(event, data, this.req.websocket);
},
/**
* broadcast event
* @param {String} event
* @param {Mixed} data
*/
broadcast(event, data) {
this.res.statusCode = 200;
instance.broadcast(event, data, this.req.websocket);
}
},
controller: {
get data() {
deprecate('controller.data is deprecated, use controller.wsData instead');
return this.ctx.data;
},
get wsData() {
return this.ctx.wsData;
},
get wsCallback() {
return this.ctx.wsCallback;
},
get websocket() {
return this.ctx.websocket;
},
get isWebsocket() {
return this.ctx.isWebsocket;
},
emit(event, data) {
return this.ctx.emit(event, data);
},
broadcast(event, data) {
return this.ctx.broadcast(event, data);
}
}
};
};