-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathChat.js
45 lines (38 loc) · 1.14 KB
/
Chat.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
const clone = require("ramda/src/clone");
const selectMatch = require("./selectMatch");
async function call(context, command, text) {
const response = await command(text, context);
return typeof response === "function" ? call(context, response, text) : response;
}
const methods = ["getState", "hello", "respondTo"];
class Chat {
constructor(config, state = {}) {
if (!config) throw new Error("Missing config for new Chat");
this.config = config;
this.contexts = [];
this.state = state;
methods.forEach(method => {
this[method] = this[method].bind(this);
});
}
async getState() {
return clone(this.state);
}
async hello() {
const { config } = this;
const { hello } = config.content;
return { value: hello };
}
async respondTo(request) {
const { config, contexts } = this;
const { value } = request;
if (value) {
const { command, context } = await selectMatch(config, contexts, value);
const response = await call(context, command, value);
return { value: response };
} else {
return { value: config.content.emptyRequest };
}
}
}
module.exports = Chat;