forked from microsoft/BotBuilder-Samples
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
94 lines (77 loc) · 2.82 KB
/
index.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
86
87
88
89
90
91
92
93
94
require('dotenv-extended').load({
path: '../.env'
});
var express = require('express');
var router = express.Router();
var _ = require('lodash');
var LuisActions = require('../../../core');
var ModelUrl = process.env.LUIS_MODEL_URL;
var SampleActions = require('../../all');
router.get('/', function (req, res, next) {
res.render('index');
});
router.post('/', function (req, res, next) {
var query = req.body.query;
var actionModel = parseActionModel(req.body.actionModel);
// restart if missing query or model
if (!query && !actionModel) {
return res.render('index');
}
tryEvaluate(actionModel, query, req.body)
.then(actionModel => {
if(actionModel.contextModel) {
// triggering Contextual Action from scratch is not supported on this Web Sample
return res.render('index');
}
switch (actionModel.status) {
case LuisActions.Status.NoActionRecognized:
// No action identified, restart
return res.render('index', { query: query });
case LuisActions.Status.MissingParameters:
// Missing or invalidate parameters
var action = SampleActions.find(a => a.intentName === actionModel.intentName);
var viewModel = {
query: query,
hasIntent: true,
actionModelJson: JSON.stringify(actionModel),
fields: createFieldsViewModel(action.schema, actionModel.parameters, actionModel.parameterErrors)
};
return res.render('index', viewModel);
case LuisActions.Status.Fulfilled:
// Action fulfilled
return res.render('fulfill', { result: actionModel.result });
}
}).catch(err => {
console.error('Error with LuisAction', err);
res.render('error', { message: 'Error with LuisAction', error: err });
});
});
module.exports = router;
function tryEvaluate(actionModel, query, formPost) {
if (actionModel) {
// Populate action parameters from form data
var action = SampleActions.find(a => a.intentName === actionModel.intentName);
actionModel.parameters = _.pick(formPost, _.keys(action.schema));
return LuisActions.evaluate(ModelUrl, SampleActions, actionModel);
} else {
return LuisActions.evaluate(ModelUrl, SampleActions, null, query);
}
}
function createFieldsViewModel(schema, parameteres, fieldErrors) {
return _.map(schema, function (paramenterSchema, parameterName) {
var fieldError = fieldErrors.find(function (err) { return err.parameterName === parameterName; });
return {
fieldName: parameterName,
fieldType: paramenterSchema.type,
fieldValue: parameteres[parameterName],
fieldError: fieldError ? fieldError.message : null
};
});
}
function parseActionModel(actionModelJson) {
try {
return JSON.parse(actionModelJson);
} catch (err) {
return null;
}
}