Skip to content

Commit 3844d18

Browse files
committed
Linting and updating.
- Remove request. - Amend healthcheck. - Remove dead code
1 parent bf5ed24 commit 3844d18

21 files changed

+155
-1335
lines changed

app/app.js

Lines changed: 1 addition & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@ const cookieParser = require('cookie-parser');
55
const logger = require('morgan');
66
const bodyParser = require('body-parser');
77
const indexRouter = require('./routes/index');
8-
const healthRouter = require('./routes/health');
98
const crypto = require('crypto');
109
const session = require('express-session');
1110
const flash = require('connect-flash');
@@ -83,19 +82,12 @@ app.use(function (req, res, next) {
8382
next();
8483
});
8584

86-
const proxyLDRouter = require('./routes/proxy-ld');
87-
const DeviceConvertor = require('./controllers/ngsi-ld/device-convert');
8885
const DataPersist = require('./controllers/ngsi-ld/building-update');
8986
const japaneseRouter = require('./routes/japanese');
90-
app.use('/', proxyLDRouter);
91-
app.post('/device/subscription/initialize', DeviceConvertor.duplicateDevices);
9287
app.post('/building/subscription', DataPersist.duplicateBuildings);
93-
app.post('/device/subscription/:attrib', DeviceConvertor.shadowDeviceMeasures);
94-
9588
app.use('/japanese/ngsi-ld/v1/', japaneseRouter);
96-
97-
app.use('/health', healthRouter);
9889
app.use('/', indexRouter);
90+
app.use('/health', require('express-healthcheck')());
9991

10092
// catch 404 and forward to error handler
10193
app.use(function (req, res, next) {

app/bin/healthcheck.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@
22

33
const http = require('http');
44
const port = process.env.WEB_APP_PORT || '3000';
5-
const path = process.env.HEALTHCHECK_PATH || '/version';
5+
const path = process.env.HEALTHCHECK_PATH || '/health';
66
const httpCode = process.env.HEALTHCHECK_CODE || 200;
77

88
const options = {

app/controllers/history.js

Lines changed: 22 additions & 107 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
const request = require('request');
21
const moment = require('moment');
32
const _ = require('lodash');
43
const debug = require('debug')('tutorial:history');
@@ -8,25 +7,6 @@ const crateUrl = process.env.CRATE_DB_SERVICE_URL || 'http://localhost:4200/_sql
87

98
const nsgiLdPrefix = process.env.NGSI_LD_PREFIX !== undefined ? process.env.NGSI_LD_PREFIX : 'urn:ngsi-ld:';
109

11-
function readCometMotionCount(id, aggMethod) {
12-
debug('readCometMotionCount');
13-
return new Promise(function (resolve, reject) {
14-
const options = {
15-
method: 'GET',
16-
url: cometUrl + 'Motion/id/' + nsgiLdPrefix + 'Motion:' + id + '/attributes/count',
17-
qs: { aggrMethod: aggMethod, aggrPeriod: 'minute' },
18-
headers: {
19-
'fiware-servicepath': '/',
20-
'fiware-service': 'openiot'
21-
}
22-
};
23-
24-
request(options, (error, response, body) => {
25-
return error ? reject(error) : resolve(JSON.parse(body));
26-
});
27-
});
28-
}
29-
3010
function readCrateMotionCount(id, aggMethod) {
3111
debug('readCrateMotionCount');
3212
return new Promise(function (resolve, reject) {
@@ -38,16 +18,18 @@ function readCrateMotionCount(id, aggMethod) {
3818
" FROM mtopeniot.etdevice WHERE entity_id = 'urn:ngsi-ld:Device:pig" +
3919
id +
4020
"' GROUP BY minute ORDER BY minute";
41-
const options = {
42-
method: 'POST',
43-
url: crateUrl,
21+
return fetch(crateUrl, {
4422
headers: { 'Content-Type': 'application/json' },
45-
body: { stmt: sqlStatement },
46-
json: true
47-
};
48-
request(options, (error, response, body) => {
49-
return error ? reject(error) : resolve(body);
50-
});
23+
method: 'POST',
24+
body: JSON.stringify({ stmt: sqlStatement })
25+
})
26+
.then((r) => r.json().then((data) => ({ status: r.status, body: data })))
27+
.then((data) => {
28+
return resolve(data.body);
29+
})
30+
.catch((e) => {
31+
return reject(e);
32+
});
5133
});
5234
}
5335

@@ -62,66 +44,21 @@ function readCrateLampLuminosity(id, aggMethod) {
6244
" FROM mtopeniot.etfillinglevelsensor WHERE entity_id = 'urn:ngsi-ld:Device:filling" +
6345
id +
6446
"' GROUP BY minute ORDER BY minute";
65-
const options = {
66-
method: 'POST',
67-
url: crateUrl,
47+
return fetch(crateUrl, {
6848
headers: { 'Content-Type': 'application/json' },
69-
body: { stmt: sqlStatement },
70-
json: true
71-
};
72-
request(options, (error, response, body) => {
73-
return error ? reject(error) : resolve(body);
74-
});
75-
});
76-
}
77-
78-
function readCometLampLuminosity(id, aggMethod) {
79-
debug('readCometLampLuminosity');
80-
return new Promise(function (resolve, reject) {
81-
const options = {
82-
method: 'GET',
83-
url: cometUrl + 'Lamp/id/' + nsgiLdPrefix + 'Lamp:' + id + '/attributes/luminosity',
84-
qs: { aggrMethod: aggMethod, aggrPeriod: 'minute' },
85-
headers: {
86-
'fiware-servicepath': '/',
87-
'fiware-service': 'openiot'
88-
}
89-
};
90-
request(options, (error, response, body) => {
91-
return error ? reject(error) : resolve(JSON.parse(body));
92-
});
49+
method: 'POST',
50+
body: JSON.stringify({ stmt: sqlStatement })
51+
})
52+
.then((r) => r.json().then((data) => ({ status: r.status, body: data })))
53+
.then((data) => {
54+
return resolve(data.body);
55+
})
56+
.catch((e) => {
57+
return reject(e);
58+
});
9359
});
9460
}
9561

96-
function cometToTimeSeries(cometResponse, aggMethod, hexColor) {
97-
debug('cometToTimeSeries');
98-
const data = [];
99-
const labels = [];
100-
const color = [];
101-
102-
if (
103-
cometResponse &&
104-
cometResponse.contextResponses[0].contextElement.attributes.length > 0 &&
105-
cometResponse.contextResponses[0].contextElement.attributes[0].values.length > 0
106-
) {
107-
const values = cometResponse.contextResponses[0].contextElement.attributes[0].values[0];
108-
let date = moment(values._id.origin);
109-
110-
_.forEach(values.points, (element) => {
111-
data.push({ t: date.valueOf(), y: element[aggMethod] });
112-
labels.push(date.format('HH:mm'));
113-
color.push(hexColor);
114-
date = date.clone().add(1, 'm');
115-
});
116-
}
117-
118-
return {
119-
labels,
120-
data,
121-
color
122-
};
123-
}
124-
12562
function crateToTimeSeries(crateResponse, aggMethod, hexColor) {
12663
debug('crateToTimeSeries');
12764

@@ -145,27 +82,6 @@ function crateToTimeSeries(crateResponse, aggMethod, hexColor) {
14582
};
14683
}
14784

148-
async function readCometDeviceHistory(req, res) {
149-
debug('readCometDeviceHistory');
150-
const id = req.params.deviceId.split(':').pop();
151-
152-
const cometMotionData = await readCometMotionCount(id, 'sum');
153-
const cometLampMinData = await readCometLampLuminosity(id, 'min');
154-
const cometLampMaxData = await readCometLampLuminosity(id, 'max');
155-
156-
const sumMotionData = cometToTimeSeries(cometMotionData, 'sum', '#45d3dd');
157-
const minLampData = cometToTimeSeries(cometLampMinData, 'min', '#45d3dd');
158-
const maxLampData = cometToTimeSeries(cometLampMaxData, 'max', '#45d3dd');
159-
160-
res.render('history', {
161-
title: 'IoT Device History',
162-
id,
163-
sumMotionData,
164-
minLampData,
165-
maxLampData
166-
});
167-
}
168-
16985
async function readCrateDeviceHistory(req, res) {
17086
debug('readCrateDeviceHistory');
17187
const id = req.params.deviceId.split(':').pop();
@@ -188,6 +104,5 @@ async function readCrateDeviceHistory(req, res) {
188104
}
189105

190106
module.exports = {
191-
readCometDeviceHistory,
192107
readCrateDeviceHistory
193108
};

app/controllers/iot/command-listener.js

Lines changed: 36 additions & 35 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,6 @@
55
// broker.
66
//
77

8-
const request = require('request');
98
const debug = require('debug')('tutorial:command-listener');
109
const Security = require('../security');
1110

@@ -53,6 +52,17 @@ function createNGSILDRequest(action, id) {
5352
return { method, url, headers, body, json: true };
5453
}
5554

55+
async function parse(response) {
56+
let text = '';
57+
try {
58+
text = await response.text();
59+
const data = JSON.parse(text);
60+
return data;
61+
} catch (err) {
62+
return text;
63+
}
64+
}
65+
5666
// This function allows a Water Sprinkler, Tractor of FillingStation command to be sent to the Dummy IoT devices
5767
// via the Orion Context Broker and an IoT Agent.
5868

@@ -102,16 +112,19 @@ function sendCommand(req, res) {
102112
}
103113

104114
debug(JSON.stringify(options));
105-
request(options, (error, response, body) => {
106-
if (error) {
107-
debug(error);
108-
}
109-
if (body) {
110-
debug(body);
111-
}
112-
// Return a status code.
113-
return res.status(response.statusCode).send();
114-
});
115+
return fetch(options.url, {
116+
headers: options.headers,
117+
method: options.method,
118+
body: JSON.stringify(options.body)
119+
})
120+
.then((r) => parse(r).then((data) => ({ status: r.status, body: data })))
121+
.then((data) => {
122+
return res.status(data.status).send(data.body);
123+
})
124+
.catch((e) => {
125+
debug(e);
126+
return res.status(400).send();
127+
});
115128
}
116129

117130
// Ringing the bell and unlocking the door are restricted actions, everything else
@@ -139,44 +152,32 @@ function accessControl(req, res, next) {
139152

140153
// The barn Door is just a switch for the dummy devices
141154
function barnDoor() {
142-
const options = {
155+
return fetch(`${devices}/barndoor`, {
143156
method: 'PUT',
144-
url: `${devices}/barndoor`,
145-
json: { update: true }
146-
};
147-
request(options, (error) => {
148-
if (error) {
149-
debug(error);
150-
}
157+
body: JSON.stringify({ update: true })
158+
}).catch((e) => {
159+
debug(e);
151160
});
152161
}
153162

154163
// Update the state of the weather to simulate changing conditions
155164
function alterWeather(action) {
156-
const options = {
165+
return fetch(`${devices}/weather`, {
157166
method: 'PUT',
158-
url: `${devices}/weather`,
159-
json: { action }
160-
};
161-
request(options, (error) => {
162-
if (error) {
163-
debug(error);
164-
}
167+
body: JSON.stringify({ action })
168+
}).catch((e) => {
169+
debug(e);
165170
});
166171
}
167172

168173
// The temperature Gauge does not accept commands,
169174
// Update the state of the device indirectly
170175
function alterTemperature(id, raise) {
171-
const options = {
176+
return fetch(`${devices}/temperature/${id}`, {
172177
method: 'PUT',
173-
url: `${devices}/temperature/${id}`,
174-
json: { raise }
175-
};
176-
request(options, (error) => {
177-
if (error) {
178-
debug(error);
179-
}
178+
body: JSON.stringify({ raise })
179+
}).catch((e) => {
180+
debug(e);
180181
});
181182
}
182183

app/controllers/ngsi-ld/amending-context.js

Lines changed: 4 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -6,7 +6,6 @@
66
//
77

88
const debug = require('debug')('tutorial:ngsi-ld');
9-
const request = require('request-promise');
109
const jsonld = require('jsonld');
1110

1211
const BASE_PATH = process.env.CONTEXT_BROKER || 'http://localhost:1026/ngsi-ld/v1';
@@ -24,16 +23,11 @@ function translateRequest(req, res) {
2423

2524
const headers = req.headers;
2625
headers.Accept = 'application/json';
27-
28-
const options = {
29-
url: BASE_PATH + req.path,
30-
method: req.method,
26+
return fetch(`${BASE_PATH}${req.path}/?${new URLSearchParams(req.query)}`, {
3127
headers,
32-
qs: req.query,
33-
json: true
34-
};
35-
36-
request(options)
28+
method: req.method
29+
})
30+
.then((r) => r.json().then((data) => ({ status: r.status, body: data })))
3731
.then(async function (cbResponse) {
3832
// Having received a response, the payload is expanded using
3933
// the core context - this forces all attribute ids to be

0 commit comments

Comments
 (0)