-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathapp.js
55 lines (48 loc) · 1.45 KB
/
app.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
'use strict';
const assert = require('assert');
const path = require('path');
const os = require('os');
const pluginName = 'udp';
function resolveController(controller, app) {
if (typeof controller === 'string') {
const actions = controller.split('.');
let obj = app[pluginName].controller;
actions.forEach(key => {
obj = obj[key];
if (!obj) throw new Error(`controller '${controller}' not exists`);
});
controller = obj;
}
// ensure controller is exists
if (!controller) throw new Error('controller not exists');
return controller;
}
function EggUdp(app) {
this.app = app;
const udpPort = app.config.udp.port;
assert(udpPort, 'udp port is not exists');
const dgram = require('dgram');
const udp = dgram.createSocket('udp4');
const platform = os.platform();
// if platform is Windows, add exclusive prop onto bind method
if (platform === 'win32') {
udp.bind({ port: udpPort, exclusive: true });
} else {
udp.bind(udpPort);
}
this.udp = udp;
}
EggUdp.prototype.handle = function(handler) {
const controller = resolveController(handler, this.app);
controller(this.udp);
};
module.exports = app => {
const udp = new EggUdp(app);
app[pluginName] = udp;
app[pluginName].controller = app[pluginName].controller || {};
new app.loader.FileLoader({
directory: path.join(app.config.baseDir, 'app', pluginName, 'controller'),
target: app[pluginName].controller,
inject: app,
}).load();
};