forked from wit-ai/wit-api-only-tutorial
-
Notifications
You must be signed in to change notification settings - Fork 0
/
shared.js
85 lines (75 loc) · 1.83 KB
/
shared.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
79
80
81
82
83
84
85
const readline = require('readline');
const fetch = require('node-fetch');
// ------------------------------------------------------------
// Config
const NEW_ACCESS_TOKEN = ''; // TODO: fill this in
const FIREBASE_CONFIG = {}; // TODO: fill this in
// ------------------------------------------------------------
// Wit API Calls
function queryWit(text, n = 1) {
return fetch(
`https://api.wit.ai/message?v=20170307&n=${n}&q=${encodeURIComponent(text)}`,
{
headers: {
Authorization: `Bearer ${NEW_ACCESS_TOKEN}`,
'Content-Type': 'application/json',
},
}
).then(res => res.json());
}
function validateSamples(samples) {
return fetch('https://api.wit.ai/samples?v=20170307', {
method: 'POST',
headers: {
Authorization: `Bearer ${NEW_ACCESS_TOKEN}`,
'Content-Type': 'application/json',
},
body: JSON.stringify(samples),
})
.then(res => res.json())
}
// ------------------------------------------------------------
// Helper Functions
function interactive(handler) {
const rl = readline.createInterface({
input: process.stdin,
output: process.stdout,
});
rl.setPrompt('> ');
const prompt = () => {
rl.prompt();
rl.write(null, {ctrl: true, name: 'e'});
};
rl
.on('line', line => {
line = line.trim();
if (!line) {
prompt();
return;
}
if (line === 'q') {
rl.close();
return;
}
handler(line, rl).then(prompt);
})
.on('close', () => {
console.log('good bye! :)');
});
prompt();
}
function firstEntity(entities, name) {
return entities &&
entities[name] &&
Array.isArray(entities[name]) &&
entities[name] &&
entities[name][0];
}
module.exports = {
queryWit,
validateSamples,
interactive,
firstEntity,
NEW_ACCESS_TOKEN,
FIREBASE_CONFIG,
};