Showing
2 changed files
with
62 additions
and
0 deletions
routes/api/server_watson.js
0 → 100644
1 | +const express = require("express"); | ||
2 | +const router = express.Router(); | ||
3 | +const AssistantV2 = require("ibm-watson/assistant/v2"); | ||
4 | +const { IamAuthenticator } = require("ibm-watson/auth"); | ||
5 | + | ||
6 | +const authenticator = new IamAuthenticator({ | ||
7 | + apikey: process.env.WATSON_ASSISTANT_APIKEY, | ||
8 | +}); | ||
9 | + | ||
10 | +const assistant = new AssistantV2({ | ||
11 | + version: "2019-02-28", | ||
12 | + authenticator: authenticator, | ||
13 | + url: process.env.WATSON_ASSISTANT_URL, | ||
14 | +}); | ||
15 | + | ||
16 | +router.get("/session", async (req, res) => { | ||
17 | + try { | ||
18 | + const session = await assistant.createSession({ | ||
19 | + assistantId: process.env.WATSON_ASSISTANT_ID, | ||
20 | + }); | ||
21 | + res.json(session["result"]); | ||
22 | + } catch (err) { | ||
23 | + res.send("There was an error processing your request."); | ||
24 | + console.log(err); | ||
25 | + } | ||
26 | +}); | ||
27 | + | ||
28 | +router.post("/message", async (req, res) => { | ||
29 | + let payload = { | ||
30 | + assistantId: process.env.WATSON_ASSISTANT_ID, | ||
31 | + sessionId: req.headers.session_id, | ||
32 | + input: { | ||
33 | + message_type: "text", | ||
34 | + text: req.body.input, | ||
35 | + }, | ||
36 | + }; | ||
37 | + | ||
38 | + try { | ||
39 | + const message = await assistant.message(payload); | ||
40 | + res.json(message["result"]); | ||
41 | + } catch (err) { | ||
42 | + res.send("There was an error processing your request."); | ||
43 | + console.log(err); | ||
44 | + } | ||
45 | +}); | ||
46 | + | ||
47 | +module.exports = router; |
server.js
0 → 100644
1 | +const express = require("express"); | ||
2 | +const dotenv = require("dotenv"); | ||
3 | +const app = express(); | ||
4 | + | ||
5 | +dotenv.config(); | ||
6 | + | ||
7 | +app.use(express.json()); | ||
8 | + | ||
9 | +const watsonRoute = require("./routes/api/server_watson"); | ||
10 | +app.use("/api/watson", watsonRoute); | ||
11 | + | ||
12 | +const port = process.env.PORT || 5000; | ||
13 | +app.listen(port, () => { | ||
14 | + console.log(`Server is listening http://localhost:${port}`); | ||
15 | +}); |
-
Please register or login to post a comment