diff options
author | Evgeny Zinoviev <me@ch1p.io> | 2021-03-03 01:05:25 +0300 |
---|---|---|
committer | Evgeny Zinoviev <me@ch1p.io> | 2021-03-03 01:05:25 +0300 |
commit | 4cc2e3029fedca4f48f4f112282a7e381b6292e4 (patch) | |
tree | 27f18feaabb6fd649e04f2a36898166db0e5f91a /src/lib | |
parent | 04b28698f2267f324354abb44c4508ac2c5c1332 (diff) |
refactor code and set process.title
Diffstat (limited to 'src/lib')
-rw-r--r-- | src/lib/request-handler.js | 59 | ||||
-rw-r--r-- | src/lib/server.js | 4 |
2 files changed, 61 insertions, 2 deletions
diff --git a/src/lib/request-handler.js b/src/lib/request-handler.js new file mode 100644 index 0000000..4ab06fb --- /dev/null +++ b/src/lib/request-handler.js @@ -0,0 +1,59 @@ +const {getLogger} = require('./logger') +const {ResponseMessage} = require('./server') + +class RequestHandler { + + constructor() { + /** + * @type {Map<string, Function>} + */ + this.handlers = new Map() + + /** + * @type {Logger} + */ + this.logger = getLogger('RequestHandler') + } + + /** + * @param {string} requestType + * @param {Function} handler + */ + set(requestType, handler) { + if (this.handlers.has(requestType)) + throw new Error(`handler for '${requestType}' has already been set`) + + this.handlers.set(requestType, handler) + } + + /** + * @param {RequestMessage} message + * @param {Connection} connection + */ + process(message, connection) { + this.logger.info('process:', message) + + if (this.handlers.has(message.requestType)) { + const f = this.handlers.get(message.requestType) + const result = f(message.requestData || {}, message.requestNo, connection) + if (result instanceof Promise) { + result.catch(error => { + this.logger.error(`${message.requestType}:`, error) + + connection.send( + new ResponseMessage(message.requestNo) + .setError('server error: ' + error?.message) + ) + }) + } + } else { + connection.send( + new ResponseMessage(message.requestNo) + .setError(`unknown request type: '${message.requestType}'`) + ) + } + } + +} + +module.exports = RequestHandler
\ No newline at end of file diff --git a/src/lib/server.js b/src/lib/server.js index 81c2c84..1d923a8 100644 --- a/src/lib/server.js +++ b/src/lib/server.js @@ -50,7 +50,7 @@ class ResponseMessage extends Message { this.error = null /** - * @type {null|string|number|object|array} + * @type {null|object} */ this.data = null } @@ -108,7 +108,7 @@ class RequestMessage extends Message { this.requestType = type /** - * @type any + * @type {null|string|number|object|array} */ this.requestData = data |