forked from watson-developer-cloud/discovery-nodejs
-
Notifications
You must be signed in to change notification settings - Fork 0
/
app.js
executable file
·80 lines (62 loc) · 2.24 KB
/
app.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
const queryBuilder = require('./src/query-builder');
const NEWS_ENVIRONMENT_ID = 'system';
const NEWS_COLLECTION_ID = 'news';
const DiscoveryV1 = require('watson-developer-cloud/discovery/v1');
const discovery = new DiscoveryV1({
// If unspecified here, the DISCOVERY_USERNAME and
// DISCOVERY_PASSWORD env properties will be checked
// After that, the SDK will fall back to the bluemix-provided VCAP_SERVICES environment property
// username: '<username>',
// password: '<password>',
version_date: '2017-08-01',
});
// Bootstrap application settings
const express = require('express');
const path = require('path');
const app = express();
require('./config/express')(app);
function getWidgetQuery(request) {
const widgetQueries = request.query.widgetQueries;
if (!widgetQueries) {
return null;
}
return widgetQueries.split(',').reduce((widgetQuery, finalWidgetQuery) => {
const queryBuilderWidgetQuery = queryBuilder.widgetQueries[widgetQuery];
if (queryBuilderWidgetQuery) {
const widgetAggregations = queryBuilderWidgetQuery.aggregations;
if (widgetAggregations) {
const currentAggregations = finalWidgetQuery.aggregations || [];
delete queryBuilderWidgetQuery.aggregations;
return Object.assign({}, finalWidgetQuery, queryBuilderWidgetQuery, {
aggregations: currentAggregations.concat(widgetAggregations),
});
}
}
return Object.assign({}, finalWidgetQuery, queryBuilderWidgetQuery);
}, {});
}
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'build', 'index.html'));
});
// setup query endpoint for news
app.post('/api/query', (req, res, next) => {
const queryParams = queryBuilder.build(req.body, getWidgetQuery(req));
if (queryParams.aggregations) {
queryParams.aggregation = `[${queryParams.aggregations.join(',')}]`;
delete queryParams.aggregations;
}
const params = Object.assign({}, queryParams, {
environment_id: NEWS_ENVIRONMENT_ID,
collection_id: NEWS_COLLECTION_ID,
});
discovery.query(params, (error, response) => {
if (error) {
next(error);
} else {
res.json(response);
}
});
});
// error-handler settings for all other routes
require('./config/error-handler')(app);
module.exports = app;