server_watson.js
1.79 KB
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
const express = require("express");
const router = express.Router();
const AssistantV2 = require("ibm-watson/assistant/v2");
const { IamAuthenticator } = require("ibm-watson/auth");
const request = require('request');
const parser = require('xml2json');
const coronaUrl = "http://openapi.data.go.kr/openapi/service/rest/Covid19/getCovid19InfStateJson";
const queryParams = '?' + encodeURIComponent('ServiceKey') + '=AZrC9RiqrxwllsI6PMbA9orNqoHCHvmriEKYHfdcpewFnbChIrmKpdehGjBt6fVGDbIAcwS0UVd7Ms5AMX29ig%3D%3D';
const authenticator = new IamAuthenticator({
apikey: process.env.WATSON_ASSISTANT_APIKEY,
});
const assistant = new AssistantV2({
version: "2019-02-28",
authenticator: authenticator,
url: process.env.WATSON_ASSISTANT_URL,
});
router.get("/session", async (req, res) => {
try {
const session = await assistant.createSession({
assistantId: process.env.WATSON_ASSISTANT_ID,
});
res.json(session["result"]);
} catch (err) {
res.send("There was an error processing your request.");
console.log(err);
}
});
router.post("/message", async (req, res) => {
let payload = {
assistantId: process.env.WATSON_ASSISTANT_ID,
sessionId: req.headers.session_id,
input: {
message_type: "text",
text: req.body.input,
},
};
try {
const message = await assistant.message(payload);
res.json(message["result"]);
} catch (err) {
res.send("There was an error processing your request.");
console.log(err);
}
});
router.get("/corona", async (req, res) => {
await request({
url: coronaUrl + queryParams,
method: 'GET'
}, (err, r, body) => {
// console.log("err : ", err);
// console.log("res : ", res);
// console.log("body : ", body);
const json = parser.toJson(body);
res.send(json);
});
});
module.exports = router;