-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstartReST.js
78 lines (69 loc) · 2.39 KB
/
startReST.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
const Koa = require("koa");
const Body = require("koa-body");
const { checkBot, UserExit } = require("@numical/ubibot-util/");
const endPoints = require("./endPoints");
const addCors = require("./addCors");
const addHeaders = require("./addHeaders");
const addRouter = require("./addRouter");
const defaultOptions = {
port: 1971,
store: require("./inMemoryStore"),
idGenerator: require("./IdGenerator")
};
const startReST = ({ botFactory, options }) => {
const { port, store, idGenerator } = { ...defaultOptions, ...options };
const healthCheck = async ({ response }) => {
response.status = 200;
};
const newBot = async ({ response }) => {
const botId = await idGenerator();
const bot = botFactory();
checkBot(bot);
const { value: botResponse } = await bot.hello();
await storeState({ botId, bot });
response.body = { botId, botResponse };
};
const existingBot = async ({ request, response, params }) => {
const { userRequest } = request.body;
const { botId } = params;
const botState = await store.get(botId);
if (botState) {
try {
const bot = botFactory(botState);
const { value: botResponse } = await bot.respondTo(userRequest);
await storeState({ botId, bot });
response.body = { botId, botResponse };
} catch (err) {
const botResponse = err instanceof UserExit ? err.message : `Unexpected Error: ${err.message}`;
await store.remove(botId);
response.body = { botId, botResponse };
}
} else {
response.status = 404;
}
};
const storeState = async ({ botId, bot }) => {
const state = bot.getState ? await bot.getState() : {};
await store.set(botId, state);
};
const createApp = () => {
const app = new Koa();
app.use(new Body());
addHeaders(app);
addCors(app);
const router = addRouter(app);
router.get(endPoints.healthCheck, healthCheck);
router.post(endPoints.bots, newBot);
router.post(endPoints.bot(":botId"), existingBot);
return app;
};
return createApp().listen(port, () => {
console.log(`
Ubibot http server listening on port ${port} and pid ${process.pid}
Endpoints available :
- GET ${endPoints.healthCheck} : returns 200 if all OK
- POST ${endPoints.bots} : starts a conversation with a new bot
- POST ${endPoints.bot("xxx")} : continues a conversation with an existing bot`);
});
};
module.exports = startReST;