summaryrefslogtreecommitdiff
path: root/src/lib
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib')
-rw-r--r--src/lib/request-handler.js59
-rw-r--r--src/lib/server.js4
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