diff --git a/CHANGES_NEXT_RELEASE b/CHANGES_NEXT_RELEASE index 2c045064a..5fbe6929d 100644 --- a/CHANGES_NEXT_RELEASE +++ b/CHANGES_NEXT_RELEASE @@ -2,6 +2,7 @@ Refresh Documentation Add NGSIv2 metadata support to device provisioned attributes Fix: Error message when sending measures with unknown/undefined attribute Add Null check within executeWithSecurity() to avoid crash (#829) +Update NGSI support to use ES6 syntax. (#850) NGSI-LD Command support (#848) Basic NGSI-LD active measures support (#841) Add GeoJSON and DateTime, unitCode and observedAt NGSI-LD support (#843) diff --git a/lib/constants.js b/lib/constants.js index fd274a8e5..75c271cbd 100644 --- a/lib/constants.js +++ b/lib/constants.js @@ -23,8 +23,6 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - const LOCATION_TYPE = 'geo:point'; const LOCATION_DEFAULT = '0, 0'; const DATETIME_TYPE = 'DateTime'; @@ -76,5 +74,5 @@ module.exports = { ORION_ALARM: 'ORION-ALARM', IOTAM_ALARM: 'IOTAM-ALARM', - getInitialValueForType: getInitialValueForType + getInitialValueForType }; diff --git a/lib/errors.js b/lib/errors.js index 506cfd64a..665ca423f 100644 --- a/lib/errors.js +++ b/lib/errors.js @@ -23,127 +23,181 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -module.exports = { - RegistrationError: function(id, type) { +class RegistrationError { + constructor(id, type) { this.name = 'REGISTRATION_ERROR'; this.message = 'Error registering context provider for device: ' + id + ' of type: ' + type; - }, - UnregistrationError: function(id, type) { + } +} +class UnregistrationError { + constructor(id, type) { this.name = 'UNREGISTRATION_ERROR'; this.message = 'Error unregistering context provider for device: ' + id + ' of type: ' + type; - }, - EntityGenericError: function(id, type, details, code) { + } +} +class EntityGenericError { + constructor(id, type, details, code) { this.name = 'ENTITY_GENERIC_ERROR'; this.message = 'Error accesing entity data for device: ' + id + ' of type: ' + type; this.details = details || {}; this.code = code || 200; - }, - EntityNotFound: function(id) { + } +} +class EntityNotFound { + constructor(id) { this.name = 'ENTITY_NOT_FOUND'; this.message = 'The entity with the requested id [' + id + '] was not found.'; this.code = 404; - }, - RegistryNotAvailable: function() { + } +} +class RegistryNotAvailable { + constructor() { this.name = 'REGISTRY_NOT_AVAILABLE'; this.message = 'No device registry is available.'; - }, - InternalDbError: function(msg) { + } +} +class InternalDbError { + constructor(msg) { this.name = 'INTERNAL_DB_ERROR'; this.message = 'An internal DB Error happened: ' + msg; - }, - BadRequest: function(msg) { + } +} +class BadRequest { + constructor(msg) { this.name = 'BAD_REQUEST'; this.message = 'Request error connecting to the Context Broker: ' + msg; this.code = 400; - }, - UnsupportedContentType: function(type) { + } +} +class UnsupportedContentType { + constructor(type) { this.name = 'UNSUPPORTED_CONTENT_TYPE'; this.message = 'Unsupported content type in the context request: ' + type; this.code = 400; - }, - TypeNotFound: function(id, type) { + } +} +class TypeNotFound { + constructor(id, type) { this.name = 'TYPE_NOT_FOUND'; this.message = 'Type : ' + type + ' not found for device with id: ' + id; this.code = 500; - }, - MissingAttributes: function(msg) { + } +} +class MissingAttributes { + constructor(msg) { this.name = 'MISSING_ATTRIBUTES'; this.message = 'The request was not well formed:' + msg; - }, - DeviceNotFound: function(id) { + } +} +class DeviceNotFound { + constructor(id) { this.name = 'DEVICE_NOT_FOUND'; this.message = 'No device was found with id:' + id; this.code = 404; - }, - AttributeNotFound: function(){ + } +} +class AttributeNotFound { + constructor() { this.name = 'ATTRIBUTE_NOT_FOUND'; this.message = 'Some of the attributes does not exist'; this.code = 404; - }, - DuplicateDeviceId: function(id) { + } +} +class DuplicateDeviceId { + constructor(id) { this.name = 'DUPLICATE_DEVICE_ID'; this.message = 'A device with the same pair (Service, DeviceId) was found:' + id; this.code = 409; - }, - DuplicateGroup: function(res, key) { + } +} +class DuplicateGroup { + constructor(res, key) { this.name = 'DUPLICATE_GROUP'; this.message = 'A device configuration already exists for resource ' + res + ' and API Key ' + key; this.code = 409; - }, - SecurityInformationMissing: function(type) { + } +} +class SecurityInformationMissing { + constructor(type) { this.name = 'SECURITY_INFORMATION_MISSING'; this.message = 'Some security information was missing for device type:' + type; - }, - TokenRetrievalError: function(trust, msg) { + } +} +class TokenRetrievalError { + constructor(trust, msg) { this.name = 'TOKEN_RETRIEVAL_ERROR'; this.message = 'An error occurred trying to retrieve a token with trust [' + trust + ']: ' + msg; - }, - AccessForbidden: function(token, service, subservice) { + } +} +class AccessForbidden { + constructor(token, service, subservice) { this.name = 'ACCESS_FORBIDDEN'; - this.message = 'The access to the CB was rejected for service [' + - service + '] subservice [ ' + subservice + ' ] and token [' + token + ']'; - }, - AuthenticationError: function(trust) { + this.message = + 'The access to the CB was rejected for service [' + + service + + '] subservice [ ' + + subservice + + ' ] and token [' + + token + + ']'; + } +} +class AuthenticationError { + constructor(trust) { this.name = 'AUTHENTICATION_ERROR'; this.message = 'The trust configured for the device was rejected: [' + trust + ']'; - }, - BadConfiguration: function(msg) { + } +} +class BadConfiguration { + constructor(msg) { this.name = 'BAD_CONFIGURATION'; this.message = 'The application startup failed due to a bad configuration:' + msg; - }, - MissingHeaders: function(msg) { + } +} +class MissingHeaders { + constructor(msg) { this.name = 'MISSING_HEADERS'; this.message = 'Some headers were missing from the request: ' + msg; this.code = 400; - }, - MismatchedService: function(service, subservice) { + } +} +class MismatchedService { + constructor(service, subservice) { this.name = 'MISMATCHED_SERVICE'; this.message = 'The declared service didn\'t match the stored one in the entity'; this.code = 403; - }, - WrongSyntax: function(msg) { + } +} +class WrongSyntax { + constructor(msg) { this.name = 'WRONG_SYNTAX'; this.message = 'Wrong syntax in request: ' + msg; this.code = 400; - }, - CommandNotFound: function(name) { + } +} +class CommandNotFound { + constructor(name) { this.name = 'COMMAND_NOT_FOUND'; this.message = 'Couldn\'t update the command because no command with the name [' + name + '] was found.'; this.code = 400; - }, - MissingConfigParams: function(missing) { + } +} +class MissingConfigParams { + constructor(missing) { this.name = 'MISSING_CONFIG_PARAMS'; this.message = 'The following mandatory configuration parameters were missing: ' + JSON.stringify(missing); this.code = 400; - }, - NotificationError: function(code) { + } +} +class NotificationError { + constructor(code) { this.name = 'NOTIFICATION_ERROR'; this.message = 'Incoming notification with non-200 status code: ' + code; this.code = 400; - }, - DeviceGroupNotFound: function(fields, values) { + } +} +class DeviceGroupNotFound { + constructor(fields, values) { this.name = 'DEVICE_GROUP_NOT_FOUND'; if (values && fields) { this.message = 'Couldn\t find device group for fields: ' + fields + ' and values: ' + values; @@ -151,35 +205,82 @@ module.exports = { this.message = 'Couldn\t find device group'; } this.code = 404; - }, - GroupNotFound: function(service, subservice) { + } +} +class GroupNotFound { + constructor(service, subservice) { this.name = 'GROUP_NOT_FOUND'; this.message = 'Group not found for service [' + service + '] and subservice [' + subservice + ']'; this.code = 404; - }, - WrongExpressionType: function(type) { + } +} +class WrongExpressionType { + constructor(type) { this.name = 'WRONG_EXPRESSION_TYPE'; this.message = 'Invalid type evaluating expression [' + type + ']'; this.code = 400; - }, - InvalidExpression: function(expression) { + } +} +class InvalidExpression { + constructor(expression) { this.name = 'INVALID_EXPRESSION'; this.message = 'Invalid expression in evaluation [' + expression + ']'; this.code = 400; - }, - BadAnswer: function(statusCode, operation) { + } +} +class BadAnswer { + constructor(statusCode, operation) { this.name = 'BAD_ANSWER'; this.message = 'Invalid statusCode in operation [' + operation + ']'; this.code = 400; - }, - BadTimestamp: function(payload) { + } +} +class BadTimestamp { + constructor(payload) { this.name = 'BAD_TIMESTAMP'; this.message = 'Invalid ISO8601 timestamp [' + payload + ']'; this.code = 400; - }, - BadGeocoordinates: function(payload) { + } +} +class BadGeocoordinates { + constructor(payload) { this.name = 'BAD_GEOCOORDINATES'; this.message = 'Invalid rfc7946 coordinates [' + payload + ']'; this.code = 400; } -}; +} + +module.exports = { + RegistrationError, + UnregistrationError, + EntityGenericError, + EntityNotFound, + RegistryNotAvailable, + InternalDbError, + BadRequest, + UnsupportedContentType, + TypeNotFound, + MissingAttributes, + DeviceNotFound, + AttributeNotFound, + DuplicateDeviceId, + DuplicateGroup, + SecurityInformationMissing, + TokenRetrievalError, + AccessForbidden, + AuthenticationError, + BadConfiguration, + MissingHeaders, + MismatchedService, + WrongSyntax, + CommandNotFound, + MissingConfigParams, + NotificationError, + DeviceGroupNotFound, + GroupNotFound, + WrongExpressionType, + InvalidExpression, + BadAnswer, + BadTimestamp, + BadGeocoordinates +}; \ No newline at end of file diff --git a/lib/services/devices/deviceRegistryMemory.js b/lib/services/devices/deviceRegistryMemory.js index d29fa387f..f90c78c63 100644 --- a/lib/services/devices/deviceRegistryMemory.js +++ b/lib/services/devices/deviceRegistryMemory.js @@ -21,18 +21,18 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -var registeredDevices = {}, - logger = require('logops'), - errors = require('../../errors'), - _ = require('underscore'), - context = { - op: 'IoTAgentNGSI.InMemoryDeviceRegister' - }; +let registeredDevices = {}; +const logger = require('logops'); +const errors = require('../../errors'); +const _ = require('underscore'); +const context = { + op: 'IoTAgentNGSI.InMemoryDeviceRegister' +}; function deepClone(device) { - var initialClone = _.clone(device); + const initialClone = _.clone(device); - for (var i in device) { + for (const i in device) { if (device.hasOwnProperty(i) && Array.isArray(device[i])) { initialClone[i] = device[i].map(_.clone); } @@ -70,9 +70,9 @@ function storeDevice(newDevice, callback) { * @param {String} subservice Subservice inside the service for the removed device. */ function removeDevice(id, service, subservice, callback) { - var services = Object.keys(registeredDevices); + const services = Object.keys(registeredDevices); - for (var i = 0; i < services.length; i++) { + for (let i = 0; i < services.length; i++) { if (registeredDevices[services[i]][id]) { logger.debug(context, 'Removing device with id [%s] from service [%s].', id, services[i]); delete registeredDevices[services[i]][id]; @@ -94,13 +94,11 @@ function getDevicesByService(service, subservice) { return Object.keys(registeredDevices[service]).filter(function filterByService(item) { if (subservice) { return registeredDevices[service][item].subservice === subservice; - } else { - return true; } + return true; }); - } else { - return []; } + return []; } /** @@ -112,12 +110,12 @@ function getDevicesByService(service, subservice) { * @param {Number} offset Number of entries to skip for pagination. */ function listDevices(type, service, subservice, limit, offset, callback) { - var result = [], - skipped = 0, - deviceList = getDevicesByService(service, subservice); + const result = []; + let skipped = 0; + const deviceList = getDevicesByService(service, subservice); - var countNumber = deviceList.length; - for (var i in deviceList) { + let countNumber = deviceList.length; + for (const i in deviceList) { if (registeredDevices[service].hasOwnProperty(deviceList[i])) { if (offset && skipped < parseInt(offset, 10)) { skipped++; @@ -150,10 +148,10 @@ function getDevice(id, service, subservice, callback) { } function getByName(name, service, subservice, callback) { - var devices = _.values(registeredDevices[service]), - device; + const devices = _.values(registeredDevices[service]); + let device; - for (var i = 0; i < devices.length; i++) { + for (let i = 0; i < devices.length; i++) { if (devices[i].name === name) { device = devices[i]; } @@ -178,8 +176,8 @@ function clear(callback) { } function getDevicesByAttribute(name, value, service, subservice, callback) { - var devices, - resultDevices = []; + let devices; + const resultDevices = []; if (service) { devices = _.values(registeredDevices[service]); @@ -187,7 +185,7 @@ function getDevicesByAttribute(name, value, service, subservice, callback) { devices = _.flatten(_.values(registeredDevices).map(_.values)); } - for (var i = 0; i < devices.length; i++) { + for (let i = 0; i < devices.length; i++) { if (devices[i][name] === value) { resultDevices.push(devices[i]); } diff --git a/lib/services/devices/deviceRegistryMongoDB.js b/lib/services/devices/deviceRegistryMongoDB.js index 51486fa9a..a98c2fc4d 100644 --- a/lib/services/devices/deviceRegistryMongoDB.js +++ b/lib/services/devices/deviceRegistryMongoDB.js @@ -21,18 +21,18 @@ * please contact with::daniel.moranjimenez@telefonica.com */ -var logger = require('logops'), - dbService = require('../../model/dbConn'), - config = require('../../commonConfig'), - fillService = require('./../common/domain').fillService, - alarmsInt = require('../common/alarmManagement').intercept, - errors = require('../../errors'), - constants = require('../../constants'), - Device = require('../../model/Device'), - async = require('async'), - context = { - op: 'IoTAgentNGSI.MongoDBDeviceRegister' - }; +const logger = require('logops'); +const dbService = require('../../model/dbConn'); +const config = require('../../commonConfig'); +const fillService = require('./../common/domain').fillService; +const alarmsInt = require('../common/alarmManagement').intercept; +const errors = require('../../errors'); +const constants = require('../../constants'); +const Device = require('../../model/Device'); +const async = require('async'); +const context = { + op: 'IoTAgentNGSI.MongoDBDeviceRegister' +}; /** * Generates a handler for the save device operations. The handler will take the customary error and the saved device @@ -58,31 +58,31 @@ function saveDeviceHandler(callback) { * @param {Object} newDevice Device object to be stored */ function storeDevice(newDevice, callback) { - var deviceObj = new Device.model(), - attributeList = [ - 'id', - 'type', - 'name', - 'service', - 'subservice', - 'lazy', - 'commands', - 'staticAttributes', - 'active', - 'registrationId', - 'internalId', - 'internalAttributes', - 'resource', - 'apikey', - 'protocol', - 'endpoint', - 'transport', - 'polling', - 'timestamp', - 'autoprovision' - ]; - - for (var i = 0; i < attributeList.length; i++) { + const deviceObj = new Device.model(); + const attributeList = [ + 'id', + 'type', + 'name', + 'service', + 'subservice', + 'lazy', + 'commands', + 'staticAttributes', + 'active', + 'registrationId', + 'internalId', + 'internalAttributes', + 'resource', + 'apikey', + 'protocol', + 'endpoint', + 'transport', + 'polling', + 'timestamp', + 'autoprovision' + ]; + + for (let i = 0; i < attributeList.length; i++) { deviceObj[attributeList[i]] = newDevice[attributeList[i]]; } @@ -118,10 +118,10 @@ function storeDevice(newDevice, callback) { * @param {String} subservice Subservice inside the service for the removed device. */ function removeDevice(id, service, subservice, callback) { - var condition = { - id: id, - service: service, - subservice: subservice + const condition = { + id, + service, + subservice }; logger.debug(context, 'Removing device with id [%s]', id); @@ -149,8 +149,8 @@ function removeDevice(id, service, subservice, callback) { * @param {Number} offset Number of entries to skip for pagination. */ function listDevices(type, service, subservice, limit, offset, callback) { - var condition = {}, - query; + const condition = {}; + let query; if (type) { condition.type = type; @@ -193,12 +193,12 @@ function listDevices(type, service, subservice, limit, offset, callback) { * @param {String} subservice Division inside the service (optional). */ function getDeviceById(id, service, subservice, callback) { - var query, - queryParams = { - id: id, - service: service, - subservice: subservice - }; + let query; + const queryParams = { + id, + service, + subservice + }; logger.debug(context, 'Looking for device with id [%s].', id); @@ -238,13 +238,13 @@ function getDevice(id, service, subservice, callback) { } function getByName(name, service, servicepath, callback) { - var query; + let query; logger.debug(context, 'Looking for device with name [%s].', name); query = Device.model.findOne({ - name: name, - service: service, + name, + service, subservice: servicepath }); @@ -300,14 +300,13 @@ function clear(callback) { function itemToObject(i) { if (i.toObject) { return i.toObject(); - } else { - return i; } + return i; } function getDevicesByAttribute(name, value, service, subservice, callback) { - var query, - filter = {}; + let query; + const filter = {}; if (service) { filter.service = service; diff --git a/lib/services/devices/deviceService.js b/lib/services/devices/deviceService.js index 0cfdd7236..b1ca25c8b 100644 --- a/lib/services/devices/deviceService.js +++ b/lib/services/devices/deviceService.js @@ -24,21 +24,19 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var async = require('async'), - apply = async.apply, - intoTrans = require('../common/domain').intoTrans, - groupService = require('../groups/groupService'), - errors = require('../../errors'), - logger = require('logops'), - config = require('../../commonConfig'), - registrationUtils = require('./registrationUtils'), - subscriptions = require('../ngsi/subscriptionService'), - _ = require('underscore'), - context = { - op: 'IoTAgentNGSI.DeviceService' - }; +const async = require('async'); +const apply = async.apply; +const intoTrans = require('../common/domain').intoTrans; +const groupService = require('../groups/groupService'); +const errors = require('../../errors'); +const logger = require('logops'); +const config = require('../../commonConfig'); +const registrationUtils = require('./registrationUtils'); +const subscriptions = require('../ngsi/subscriptionService'); +const _ = require('underscore'); +const context = { + op: 'IoTAgentNGSI.DeviceService' +}; let deviceHandler; @@ -46,15 +44,16 @@ let deviceHandler; * Loads the correct device handler based on the current config. */ function init(){ - if (config.checkNgsiLD()) { - deviceHandler = require('./devices-NGSI-LD'); + if (config.checkNgsiLD()) { + deviceHandler = require('./devices-NGSI-LD'); } else if (config.checkNgsi2()) { - deviceHandler = require('./devices-NGSI-v2'); + deviceHandler = require('./devices-NGSI-v2'); } else { - deviceHandler = require('./devices-NGSI-v1'); + deviceHandler = require('./devices-NGSI-v1'); } } + /** * Creates the initial entity representing the device in the Context Broker. This is important mainly to allow the * rest of the updateContext operations to be performed using an UPDATE action instead of an APPEND one. @@ -98,18 +97,18 @@ function setDefaultAttributeIds(attribute) { */ function mergeArrays(original, newArray) { /* jshint camelcase: false */ - var originalKeys = _.pluck(original, 'object_id'), - newKeys = _.pluck(newArray, 'object_id'), - addedKeys = _.difference(newKeys, originalKeys), - differenceArray = newArray.filter(function(item) { - return item.object_id && addedKeys.indexOf(item.object_id) >= 0; - }), - originalNames = _.pluck(original, 'name'), - newNames = _.pluck(newArray, 'name'), - addedNames = _.difference(newNames, originalNames), - differenceNamesArray = newArray.filter(function(item) { - return addedNames.indexOf(item.name) >= 0 && (!item.object_id || newKeys.indexOf(item.object_id) < 0); - }); + const originalKeys = _.pluck(original, 'object_id'); + const newKeys = _.pluck(newArray, 'object_id'); + const addedKeys = _.difference(newKeys, originalKeys); + const differenceArray = newArray.filter(function(item) { + return item.object_id && addedKeys.indexOf(item.object_id) >= 0; + }); + const originalNames = _.pluck(original, 'name'); + const newNames = _.pluck(newArray, 'name'); + const addedNames = _.difference(newNames, originalNames); + const differenceNamesArray = newArray.filter(function(item) { + return addedNames.indexOf(item.name) >= 0 && (!item.object_id || newKeys.indexOf(item.object_id) < 0); + }); return original.concat(differenceArray).concat(differenceNamesArray); } @@ -124,8 +123,8 @@ function mergeArrays(original, newArray) { */ function mergeDeviceWithConfiguration(fields, defaults, deviceData, configuration, callback) { logger.debug(context, 'deviceData after merge with conf: %j', deviceData); - for (var i = 0; i < fields.length; i++) { - var confField = fields[i] === 'active' ? 'attributes' : fields[i]; + for (let i = 0; i < fields.length; i++) { + const confField = fields[i] === 'active' ? 'attributes' : fields[i]; if (deviceData && deviceData[fields[i]] && ['active', 'lazy', 'commands'].indexOf(fields[i]) >= 0) { deviceData[fields[i]] = deviceData[fields[i]].map(setDefaultAttributeIds); @@ -145,8 +144,12 @@ function mergeDeviceWithConfiguration(fields, defaults, deviceData, configuratio if (deviceData[fields[i]] && configuration && configuration[confField]) { deviceData[fields[i]] = mergeArrays(deviceData[fields[i]], configuration[confField]); - } else if (!deviceData[fields[i]] && configuration && - confField in configuration &&configuration[confField] !== undefined) { + } else if ( + !deviceData[fields[i]] && + configuration && + confField in configuration && + configuration[confField] !== undefined + ) { deviceData[fields[i]] = configuration[confField]; } else if (!deviceData[fields[i]] && (!configuration || !configuration[confField])) { deviceData[fields[i]] = defaults[i]; @@ -168,7 +171,7 @@ function mergeDeviceWithConfiguration(fields, defaults, deviceData, configuratio */ function findConfigurationGroup(deviceObj, callback) { function handlerGroupFind(error, group) { - var effectiveGroup = group; + let effectiveGroup = group; if (!group && config.getConfig().types[deviceObj.type]) { effectiveGroup = config.getConfig().types[deviceObj.type]; @@ -212,8 +215,8 @@ function registerDevice(deviceObj, callback) { } function prepareDeviceData(deviceObj, configuration, callback) { - var deviceData = _.clone(deviceObj), - selectedConfiguration; + const deviceData = _.clone(deviceObj); + let selectedConfiguration; if (!deviceData.type) { if (configuration && configuration.type) { @@ -459,8 +462,8 @@ function getDevicesByAttribute(attributeName, attributeValue, service, subservic */ function checkRegistry(fn) { return function() { - var args = Array.prototype.slice.call(arguments), - callbacks = args.slice(-1); + const args = Array.prototype.slice.call(arguments); + const callbacks = args.slice(-1); if (config.getRegistry()) { fn.apply(null, args); @@ -478,7 +481,7 @@ function findOrCreate(deviceId, group, callback) { if (!error && device) { callback(null, device, group); } else if (error.name === 'DEVICE_NOT_FOUND') { - var newDevice = { + const newDevice = { id: deviceId, service: group.service, subservice: group.subservice, diff --git a/lib/services/devices/devices-NGSI-LD.js b/lib/services/devices/devices-NGSI-LD.js index 1c656d52c..e485823ac 100644 --- a/lib/services/devices/devices-NGSI-LD.js +++ b/lib/services/devices/devices-NGSI-LD.js @@ -23,25 +23,23 @@ * Modified by: Jason Fox - FIWARE Foundation */ -'use strict'; - -var request = require('request'), - async = require('async'), - apply = async.apply, - constants = require('../../constants'), - alarms = require('../common/alarmManagement'), - errors = require('../../errors'), - logger = require('logops'), - config = require('../../commonConfig'), - ngsiLD = require('../ngsi/entities-NGSI-LD'), - utils = require('../northBound/restUtils'), - moment = require('moment'), - _ = require('underscore'), - registrationUtils = require('./registrationUtils'), - NGSIv2 = require('./devices-NGSI-v2'), - context = { - op: 'IoTAgentNGSI.Devices-LD' - }; +const request = require('request'); +const async = require('async'); +const apply = async.apply; +const constants = require('../../constants'); +const alarms = require('../common/alarmManagement'); +const errors = require('../../errors'); +const logger = require('logops'); +const config = require('../../commonConfig'); +const ngsiLD = require('../ngsi/entities-NGSI-LD'); +const utils = require('../northBound/restUtils'); +const moment = require('moment'); +const _ = require('underscore'); +const registrationUtils = require('./registrationUtils'); +const NGSIv2 = require('./devices-NGSI-v2'); +const context = { + op: 'IoTAgentNGSI.Devices-LD' +}; /** * Concats or merges two JSON objects. @@ -50,7 +48,7 @@ var request = require('request'), * @param {Object} json2 JSON object to be merged. */ function jsonConcat(json1, json2) { - for (var key in json2) { + for (const key in json2) { if (json2.hasOwnProperty(key)) { json1[key] = json2[key]; } @@ -78,12 +76,12 @@ function createInitialEntityHandlerNgsiLD(deviceData, newDevice, callback) { alarms.raise(constants.ORION_ALARM, error); callback(error); - } else if (response && response.statusCode === 204 ) { + } else if (response && response.statusCode === 204) { alarms.release(constants.ORION_ALARM); logger.debug(context, 'Initial entity created successfully.'); callback(null, newDevice); } else { - var errorObj; + let errorObj; logger.error( context, @@ -100,7 +98,7 @@ function createInitialEntityHandlerNgsiLD(deviceData, newDevice, callback) { } /** - * Creates the response handler for the update entity request using NGSI-LD. + * Creates the response handler for the update entity request using NGSI-LD. * This handler basically deals with the errors * that could have been rised during the communication with the Context Broker. * @@ -125,7 +123,7 @@ function updateEntityHandlerNgsiLD(deviceData, updatedDevice, callback) { logger.debug(context, 'Entity updated successfully.'); callback(null, updatedDevice); } else { - var errorObj; + let errorObj; logger.error( context, @@ -149,7 +147,7 @@ function updateEntityHandlerNgsiLD(deviceData, updatedDevice, callback) { * @param {Object} newDevice Device object that will be stored in the database. */ function createInitialEntityNgsiLD(deviceData, newDevice, callback) { - var json = { + let json = { id: String(deviceData.name), type: deviceData.type }; @@ -158,9 +156,10 @@ function createInitialEntityNgsiLD(deviceData, newDevice, callback) { jsonConcat(json, NGSIv2.formatAttributes(deviceData.staticAttributes, true)); jsonConcat(json, NGSIv2.formatCommands(deviceData.commands)); - if (('timestamp' in deviceData && deviceData.timestamp !== undefined ? - deviceData.timestamp : config.getConfig().timestamp) && - !utils.isTimestampedNgsi2(json)) { + if ( + ('timestamp' in deviceData && deviceData.timestamp !== undefined ? + deviceData.timestamp : config.getConfig().timestamp) && !utils.isTimestampedNgsi2(json) + ) { logger.debug(context, 'config.timestamp %s %s', deviceData.timestamp, config.getConfig().timestamp); json[constants.TIMESTAMP_ATTRIBUTE] = { @@ -171,7 +170,7 @@ function createInitialEntityNgsiLD(deviceData, newDevice, callback) { json = ngsiLD.formatAsNGSILD(json); - var options = { + const options = { url: config.getConfig().contextBroker.url + '/ngsi-ld/v1/entityOperations/upsert/', method: 'POST', json: [json], @@ -190,8 +189,6 @@ function createInitialEntityNgsiLD(deviceData, newDevice, callback) { options.url = 'http://' + deviceData.cbHost + '/ngsi-ld/v1/entityOperations/upsert/'; } - //console.error(JSON.stringify(options, null, 4)); - logger.debug(context, 'deviceData: %j', deviceData); logger.debug(context, 'Creating initial entity in the Context Broker:\n %s', JSON.stringify(options, null, 4)); utils.executeWithSecurity(options, newDevice, createInitialEntityHandlerNgsiLD(deviceData, newDevice, callback)); @@ -204,7 +201,7 @@ function createInitialEntityNgsiLD(deviceData, newDevice, callback) { * @param {Object} updatedDevice Device object that will be stored in the database. */ function updateEntityNgsiLD(deviceData, updatedDevice, callback) { - var options = { + const options = { url: config.getConfig().contextBroker.url + '/ngsi-ld/v1/entityOperations/upsert/', method: 'POST', json: {}, @@ -231,9 +228,11 @@ function updateEntityNgsiLD(deviceData, updatedDevice, callback) { jsonConcat(options.json, NGSIv2.formatAttributes(deviceData.staticAttributes, true)); jsonConcat(options.json, NGSIv2.formatCommands(deviceData.commands)); - if (('timestamp' in deviceData && deviceData.timestamp !== undefined ? - deviceData.timestamp : config.getConfig().timestamp) && - !utils.isTimestampedNgsi2(options.json)) { + if ( + ('timestamp' in deviceData && deviceData.timestamp !== undefined ? + deviceData.timestamp : config.getConfig().timestamp) && + !utils.isTimestampedNgsi2(options.json) + ) { options.json[constants.TIMESTAMP_ATTRIBUTE] = { type: constants.TIMESTAMP_TYPE_NGSI2, value: moment() @@ -242,11 +241,8 @@ function updateEntityNgsiLD(deviceData, updatedDevice, callback) { options.json.id = String(deviceData.name); options.json.type = deviceData.type; - options.json = [ngsiLD.formatAsNGSILD(options.json)]; - // console.error(JSON.stringify(options.json, null, 4)) - // FIXME: maybe there is be a better way to theck options.json = {} if (Object.keys(options.json).length === 0 && options.json.constructor === Object) { logger.debug(context, 'Skip updating entity in the Context Broker (no actual attribute change)'); @@ -302,7 +298,10 @@ function updateRegisterDeviceNgsiLD(deviceObj, callback) { } function getAttributeDifference(oldArray, newArray) { - var oldActiveKeys, newActiveKeys, updateKeys, result; + let oldActiveKeys; + let newActiveKeys; + let updateKeys; + let result; if (oldArray && newArray) { newActiveKeys = _.pluck(newArray, 'name'); @@ -323,7 +322,7 @@ function updateRegisterDeviceNgsiLD(deviceObj, callback) { } function extractDeviceDifference(newDevice, oldDevice, callback) { - var deviceData = { + const deviceData = { id: oldDevice.id, name: oldDevice.name, type: oldDevice.type, diff --git a/lib/services/devices/devices-NGSI-v1.js b/lib/services/devices/devices-NGSI-v1.js index 6faa29534..4bd19aef8 100644 --- a/lib/services/devices/devices-NGSI-v1.js +++ b/lib/services/devices/devices-NGSI-v1.js @@ -25,22 +25,22 @@ * Modified by: Jason Fox - FIWARE Foundation */ -var async = require('async'), - apply = async.apply, - uuid = require('uuid'), - constants = require('../../constants'), - domain = require('domain'), - alarms = require('../common/alarmManagement'), - errors = require('../../errors'), - logger = require('logops'), - config = require('../../commonConfig'), - ngsiUtils = require('./../ngsi/ngsiUtils'), - registrationUtils = require('./registrationUtils'), - _ = require('underscore'), - utils = require('../northBound/restUtils'), - context = { - op: 'IoTAgentNGSI.Devices-v1' - }; +const async = require('async'); +const apply = async.apply; +const uuid = require('uuid'); +const constants = require('../../constants'); +const domain = require('domain'); +const alarms = require('../common/alarmManagement'); +const errors = require('../../errors'); +const logger = require('logops'); +const config = require('../../commonConfig'); +const ngsiUtils = require('./../ngsi/ngsiUtils'); +const registrationUtils = require('./registrationUtils'); +const _ = require('underscore'); +const utils = require('../northBound/restUtils'); +const context = { + op: 'IoTAgentNGSI.Devices-v1' +}; /** * Creates the response handler for the initial entity creation request NGSIv1. @@ -64,7 +64,7 @@ function createInitialEntityHandlerNgsi1(deviceData, newDevice, callback) { callback(error); } else if (response && body && response.statusCode === 200) { - var errorField = ngsiUtils.getErrorField(body); + const errorField = ngsiUtils.getErrorField(body); if (errorField) { logger.error(context, 'Update error connecting to the Context Broker: %j', errorField); @@ -75,7 +75,7 @@ function createInitialEntityHandlerNgsi1(deviceData, newDevice, callback) { callback(null, newDevice); } } else { - var errorObj; + let errorObj; logger.error( context, @@ -100,13 +100,13 @@ function createInitialEntityHandlerNgsi1(deviceData, newDevice, callback) { * @param {Object} newDevice Device object that will be stored in the database. */ function createInitialEntityNgsi1(deviceData, newDevice, callback) { - var cbHost = config.getConfig().contextBroker.url; + let cbHost = config.getConfig().contextBroker.url; if (deviceData.cbHost && deviceData.cbHost.indexOf('://') !== -1) { cbHost = deviceData.cbHost; } else if (deviceData.cbHost && deviceData.cbHost.indexOf('://') === -1) { cbHost = 'http://' + deviceData.cbHost; } - var options = { + const options = { url: cbHost + '/v1/updateContext', method: 'POST', json: { @@ -128,10 +128,10 @@ function createInitialEntityNgsi1(deviceData, newDevice, callback) { }; function formatAttributes(originalVector) { - var attributeList = []; + const attributeList = []; if (originalVector && originalVector.length) { - for (var i = 0; i < originalVector.length; i++) { + for (let i = 0; i < originalVector.length; i++) { // (#628) check if attribute has entity_name: // In that case attribute should not be appear in current entity /*jshint camelcase: false */ @@ -149,10 +149,10 @@ function createInitialEntityNgsi1(deviceData, newDevice, callback) { } function formatCommands(originalVector) { - var attributeList = []; + const attributeList = []; if (originalVector && originalVector.length) { - for (var i = 0; i < originalVector.length; i++) { + for (let i = 0; i < originalVector.length; i++) { attributeList.push({ name: originalVector[i].name + constants.COMMAND_STATUS_SUFIX, type: constants.COMMAND_STATUS, @@ -175,9 +175,11 @@ function createInitialEntityNgsi1(deviceData, newDevice, callback) { formatCommands(deviceData.commands) ); - if (('timestamp' in deviceData && deviceData.timestamp !== undefined ? + if ( + ('timestamp' in deviceData && deviceData.timestamp !== undefined ? deviceData.timestamp : config.getConfig().timestamp) && - !utils.isTimestamped(options.json)) { + !utils.isTimestamped(options.json) + ) { options.json.contextElements[0].attributes.push({ name: constants.TIMESTAMP_ATTRIBUTE, type: constants.TIMESTAMP_TYPE, @@ -234,7 +236,10 @@ function updateRegisterDeviceNgsi1(deviceObj, callback) { } function getAttributeDifference(oldArray, newArray) { - var oldActiveKeys, newActiveKeys, updateKeys, result; + let oldActiveKeys; + let newActiveKeys; + let updateKeys; + let result; if (oldArray && newArray) { newActiveKeys = _.pluck(newArray, 'name'); @@ -255,7 +260,7 @@ function updateRegisterDeviceNgsi1(deviceObj, callback) { } function extractDeviceDifference(newDevice, oldDevice, callback) { - var deviceData = { + const deviceData = { id: oldDevice.id, name: oldDevice.name, type: oldDevice.type, diff --git a/lib/services/devices/devices-NGSI-v2.js b/lib/services/devices/devices-NGSI-v2.js index 8caec1e1a..92584a21e 100644 --- a/lib/services/devices/devices-NGSI-v2.js +++ b/lib/services/devices/devices-NGSI-v2.js @@ -25,25 +25,23 @@ * Modified by: Jason Fox - FIWARE Foundation */ -'use strict'; - -var request = require('request'), - async = require('async'), - apply = async.apply, - uuid = require('uuid'), - constants = require('../../constants'), - domain = require('domain'), - alarms = require('../common/alarmManagement'), - errors = require('../../errors'), - logger = require('logops'), - config = require('../../commonConfig'), - registrationUtils = require('./registrationUtils'), - _ = require('underscore'), - utils = require('../northBound/restUtils'), - moment = require('moment'), - context = { - op: 'IoTAgentNGSI.Devices-v2' - }; +const request = require('request'); +const async = require('async'); +const apply = async.apply; +const uuid = require('uuid'); +const constants = require('../../constants'); +const domain = require('domain'); +const alarms = require('../common/alarmManagement'); +const errors = require('../../errors'); +const logger = require('logops'); +const config = require('../../commonConfig'); +const registrationUtils = require('./registrationUtils'); +const _ = require('underscore'); +const utils = require('../northBound/restUtils'); +const moment = require('moment'); +const context = { + op: 'IoTAgentNGSI.Devices-v2' +}; /** * Concats or merges two JSON objects. @@ -52,7 +50,7 @@ var request = require('request'), * @param {Object} json2 JSON object to be merged. */ function jsonConcat(json1, json2) { - for (var key in json2) { + for (const key in json2) { if (json2.hasOwnProperty(key)) { json1[key] = json2[key]; } @@ -85,7 +83,7 @@ function createInitialEntityHandlerNgsi2(deviceData, newDevice, callback) { logger.debug(context, 'Initial entity created successfully.'); callback(null, newDevice); } else { - var errorObj; + let errorObj; logger.error( context, @@ -126,7 +124,7 @@ function updateEntityHandlerNgsi2(deviceData, updatedDevice, callback) { logger.debug(context, 'Entity updated successfully.'); callback(null, updatedDevice); } else { - var errorObj; + let errorObj; logger.error( context, @@ -150,10 +148,10 @@ function updateEntityHandlerNgsi2(deviceData, updatedDevice, callback) { * @return {Object} List of device's attributes formatted in NGSIv2. */ function formatAttributesNgsi2(originalVector, staticAtts) { - var attributeList = {}; + const attributeList = {}; if (originalVector && originalVector.length) { - for (var i = 0; i < originalVector.length; i++) { + for (let i = 0; i < originalVector.length; i++) { // (#628) check if attribute has entity_name: // In that case attribute should not be appear in current entity /*jshint camelcase: false */ @@ -187,10 +185,10 @@ function formatAttributesNgsi2(originalVector, staticAtts) { * @return {Object} List of device's commands formatted in NGSIv2. */ function formatCommandsNgsi2(originalVector) { - var attributeList = {}; + const attributeList = {}; if (originalVector && originalVector.length) { - for (var i = 0; i < originalVector.length; i++) { + for (let i = 0; i < originalVector.length; i++) { attributeList[originalVector[i].name + constants.COMMAND_STATUS_SUFIX] = { type: constants.COMMAND_STATUS, value: 'UNKNOWN' @@ -213,7 +211,7 @@ function formatCommandsNgsi2(originalVector) { * @param {Object} newDevice Device object that will be stored in the database. */ function createInitialEntityNgsi2(deviceData, newDevice, callback) { - var options = { + const options = { url: config.getConfig().contextBroker.url + '/v2/entities?options=upsert', method: 'POST', json: { @@ -238,9 +236,11 @@ function createInitialEntityNgsi2(deviceData, newDevice, callback) { jsonConcat(options.json, formatCommandsNgsi2(deviceData.commands)); logger.debug(context, 'deviceData: %j', deviceData); - if (('timestamp' in deviceData && deviceData.timestamp !== undefined ? + if ( + ('timestamp' in deviceData && deviceData.timestamp !== undefined ? deviceData.timestamp : config.getConfig().timestamp) && - !utils.isTimestampedNgsi2(options.json)) { + !utils.isTimestampedNgsi2(options.json) + ) { logger.debug(context, 'config.timestamp %s %s', deviceData.timestamp, config.getConfig().timestamp); options.json[constants.TIMESTAMP_ATTRIBUTE] = { type: constants.TIMESTAMP_TYPE_NGSI2, @@ -258,7 +258,7 @@ function createInitialEntityNgsi2(deviceData, newDevice, callback) { * @param {Object} updatedDevice Device object that will be stored in the database. */ function updateEntityNgsi2(deviceData, updatedDevice, callback) { - var options = { + const options = { url: config.getConfig().contextBroker.url + '/v2/entities/' + String(deviceData.name) + '/attrs', method: 'POST', json: {}, @@ -283,9 +283,11 @@ function updateEntityNgsi2(deviceData, updatedDevice, callback) { jsonConcat(options.json, formatAttributesNgsi2(deviceData.staticAttributes, true)); jsonConcat(options.json, formatCommandsNgsi2(deviceData.commands)); - if (('timestamp' in deviceData && deviceData.timestamp !== undefined ? + if ( + ('timestamp' in deviceData && deviceData.timestamp !== undefined ? deviceData.timestamp : config.getConfig().timestamp) && - !utils.isTimestampedNgsi2(options.json)) { + !utils.isTimestampedNgsi2(options.json) + ) { options.json[constants.TIMESTAMP_ATTRIBUTE] = { type: constants.TIMESTAMP_TYPE_NGSI2, value: moment() @@ -347,7 +349,10 @@ function updateRegisterDeviceNgsi2(deviceObj, callback) { } function getAttributeDifference(oldArray, newArray) { - var oldActiveKeys, newActiveKeys, updateKeys, result; + let oldActiveKeys; + let newActiveKeys; + let updateKeys; + let result; if (oldArray && newArray) { newActiveKeys = _.pluck(newArray, 'name'); @@ -368,7 +373,7 @@ function updateRegisterDeviceNgsi2(deviceObj, callback) { } function extractDeviceDifference(newDevice, oldDevice, callback) { - var deviceData = { + const deviceData = { id: oldDevice.id, name: oldDevice.name, type: oldDevice.type, diff --git a/lib/services/devices/registrationUtils.js b/lib/services/devices/registrationUtils.js index 41913dbe1..7d83581f5 100644 --- a/lib/services/devices/registrationUtils.js +++ b/lib/services/devices/registrationUtils.js @@ -24,19 +24,17 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var errors = require('../../errors'), - logger = require('logops'), - _ = require('underscore'), - intoTrans = require('../common/domain').intoTrans, - config = require('../../commonConfig'), - ngsiUtils = require('./../ngsi/ngsiUtils'), - context = { - op: 'IoTAgentNGSI.Registration' - }, - async = require('async'), - utils = require('../northBound/restUtils'); +const errors = require('../../errors'); +const logger = require('logops'); +const _ = require('underscore'); +const intoTrans = require('../common/domain').intoTrans; +const config = require('../../commonConfig'); +const ngsiUtils = require('./../ngsi/ngsiUtils'); +const context = { + op: 'IoTAgentNGSI.Registration' +}; +const async = require('async'); +const utils = require('../northBound/restUtils'); const NGSI_LD_URN = 'urn:ngsi-ld:'; @@ -54,7 +52,7 @@ function createRegistrationHandler(unregister, deviceData, callback) { logger.error(context, 'ORION-002: Connection error sending registrations to the Context Broker: %s', error); callback(error); } else if (response && body && response.statusCode === 200) { - var errorField = ngsiUtils.getErrorField(body); + const errorField = ngsiUtils.getErrorField(body); if (errorField) { logger.error(context, 'Registration error connecting to the Context Broker: %j', errorField); @@ -64,7 +62,7 @@ function createRegistrationHandler(unregister, deviceData, callback) { callback(null, body); } } else { - var errorObj; + let errorObj; logger.error(context, 'ORION-003: Protocol error connecting to the Context Broker: %j', errorObj); @@ -104,7 +102,7 @@ function createRegistrationHandlerNgsiLD(unregister, deviceData, callback) { logger.error(context, 'Registration error connecting to the Context Broker: %j', response.statusCode); callback(new errors.BadRequest(JSON.stringify(response.statusCode))); } else { - var errorObj; + let errorObj; logger.error(context, 'ORION-003: Protocol error connecting to the Context Broker: %j', errorObj); @@ -144,7 +142,7 @@ function createRegistrationHandlerNgsi2(unregister, deviceData, callback) { logger.error(context, 'Registration error connecting to the Context Broker: %j', response.statusCode); callback(new errors.BadRequest(JSON.stringify(response.statusCode))); } else { - var errorObj; + let errorObj; logger.error(context, 'ORION-003: Protocol error connecting to the Context Broker: %j', errorObj); @@ -170,14 +168,14 @@ function createRegistrationHandlerNgsi2(unregister, deviceData, callback) { * @param {Object} deviceData Object containing all the deviceData needed to send the registration. */ function sendRegistrationsNgsi1(unregister, deviceData, callback) { - var cbHost = config.getConfig().contextBroker.url; + let cbHost = config.getConfig().contextBroker.url; if (deviceData.cbHost && deviceData.cbHost.indexOf('://') !== -1) { cbHost = deviceData.cbHost; } else if (deviceData.cbHost && deviceData.cbHost.indexOf('://') === -1) { cbHost = 'http://' + deviceData.cbHost; } - var options = { + const options = { url: cbHost + '/NGSI9/registerContext', method: 'POST', json: { @@ -203,10 +201,10 @@ function sendRegistrationsNgsi1(unregister, deviceData, callback) { }; function formatAttributes(originalVector) { - var attributeList = []; + const attributeList = []; if (originalVector && originalVector.length) { - for (var i = 0; i < originalVector.length; i++) { + for (let i = 0; i < originalVector.length; i++) { attributeList.push({ name: originalVector[i].name, type: originalVector[i].type @@ -218,7 +216,7 @@ function sendRegistrationsNgsi1(unregister, deviceData, callback) { } function mergeWithSameName(old, current) { - var keys = _.pluck(old, 'name'); + const keys = _.pluck(old, 'name'); if (keys.indexOf(current.name) < 0) { old.push(current); @@ -252,13 +250,13 @@ function sendRegistrationsNgsi1(unregister, deviceData, callback) { * @param {Object} deviceData Object containing all the deviceData needed to send the registration. */ function sendUnregistrationsNgsi2(deviceData, callback) { - var cbHost = config.getConfig().contextBroker.url; + let cbHost = config.getConfig().contextBroker.url; if (deviceData.cbHost && deviceData.cbHost.indexOf('://') !== -1) { cbHost = deviceData.cbHost; } else if (deviceData.cbHost && deviceData.cbHost.indexOf('://') === -1) { cbHost = 'http://' + deviceData.cbHost; } - var options = { + const options = { url: cbHost + '/v2/registrations/' + deviceData.registrationId, method: 'DELETE', json: true, @@ -293,13 +291,13 @@ function sendUnregistrationsNgsi2(deviceData, callback) { * @param {Object} deviceData Object containing all the deviceData needed to send the registration. */ function sendUnregistrationsNgsiLD(deviceData, callback) { - var cbHost = config.getConfig().contextBroker.url; + let cbHost = config.getConfig().contextBroker.url; if (deviceData.cbHost && deviceData.cbHost.indexOf('://') !== -1) { cbHost = deviceData.cbHost; } else if (deviceData.cbHost && deviceData.cbHost.indexOf('://') === -1) { cbHost = 'http://' + deviceData.cbHost; } - var options = { + const options = { url: cbHost + '/ngsi-ld/v1/csourceRegistrations/' + deviceData.registrationId, method: 'DELETE', json: true, @@ -307,7 +305,7 @@ function sendUnregistrationsNgsiLD(deviceData, callback) { 'fiware-service': deviceData.service, 'fiware-servicepath': deviceData.subservice, 'NGSILD-Tenant': deviceData.service, - 'NGSILD-Path': deviceData.subservice, + 'NGSILD-Path': deviceData.subservice } }; if (deviceData.cbHost && deviceData.cbHost.indexOf('://') !== -1) { @@ -326,8 +324,6 @@ function sendUnregistrationsNgsiLD(deviceData, callback) { ); } - //console.error(JSON.stringify(options.json, null, 4)); - logger.debug(context, 'No Context Provider registrations found for unregister'); return callback(null, deviceData); } @@ -340,10 +336,10 @@ function sendUnregistrationsNgsiLD(deviceData, callback) { */ function sendRegistrationsNgsi2(unregister, deviceData, callback) { function formatAttributes(originalVector) { - var attributeList = []; + const attributeList = []; if (originalVector && originalVector.length) { - for (var i = 0; i < originalVector.length; i++) { + for (let i = 0; i < originalVector.length; i++) { attributeList.push(originalVector[i].name); } } @@ -363,7 +359,7 @@ function sendRegistrationsNgsi2(unregister, deviceData, callback) { // this function should use the new API. This is just a temporary solution which implies deleting the // registration and creating a new one. function updateRegistrationNgsi2(deviceData, callback) { - var functions = []; + const functions = []; function removeRegistrationId(deviceData, unregistrationResult, callback) { delete deviceData.registrationId; @@ -383,13 +379,13 @@ function sendRegistrationsNgsi2(unregister, deviceData, callback) { return updateRegistrationNgsi2(deviceData, callback); } - var cbHost = config.getConfig().contextBroker.url; + let cbHost = config.getConfig().contextBroker.url; if (deviceData.cbHost && deviceData.cbHost.indexOf('://') !== -1) { cbHost = deviceData.cbHost; } else if (deviceData.cbHost && deviceData.cbHost.indexOf('://') === -1) { cbHost = 'http://' + deviceData.cbHost; } - var options = { + const options = { url: cbHost + '/v2/registrations', method: 'POST', json: { @@ -442,9 +438,9 @@ function sendRegistrationsNgsiLD(unregister, deviceData, callback) { return sendUnregistrationsNgsiLD(deviceData, callback); } - var properties = []; - var lazy = deviceData.lazy || []; - var commands = deviceData.commands || []; + const properties = []; + const lazy = deviceData.lazy || []; + const commands = deviceData.commands || []; lazy.forEach((element) => { properties.push(element.name); @@ -453,7 +449,6 @@ function sendRegistrationsNgsiLD(unregister, deviceData, callback) { properties.push(element.name); }); - if (properties.length === 0) { logger.debug( context, @@ -462,7 +457,7 @@ function sendRegistrationsNgsiLD(unregister, deviceData, callback) { return callback(null, deviceData); } - var cbHost = config.getConfig().contextBroker.url; + let cbHost = config.getConfig().contextBroker.url; if (deviceData.cbHost && deviceData.cbHost.indexOf('://') !== -1) { cbHost = deviceData.cbHost; @@ -470,11 +465,10 @@ function sendRegistrationsNgsiLD(unregister, deviceData, callback) { cbHost = 'http://' + deviceData.cbHost; } - - var id = String(deviceData.name); + let id = String(deviceData.name); id = id.startsWith(NGSI_LD_URN) ? id : NGSI_LD_URN + deviceData.type + ':' + id; - var options = { + const options = { url: cbHost + '/ngsi-ld/v1/csourceRegistrations/', method: 'POST', json: { @@ -482,7 +476,7 @@ function sendRegistrationsNgsiLD(unregister, deviceData, callback) { information: [ { entities: [{ type: deviceData.type, id }], - properties: properties + properties } ], endpoint: config.getConfig().providerUrl, @@ -531,7 +525,7 @@ function sendRegistrations(unregister, deviceData, callback) { * */ function processContextRegistration(deviceData, body, callback) { - var newDevice = _.clone(deviceData); + const newDevice = _.clone(deviceData); if (body) { newDevice.registrationId = body.registrationId; diff --git a/lib/services/ngsi/entities-NGSI-LD.js b/lib/services/ngsi/entities-NGSI-LD.js index 642a436ae..7bd9b45f6 100644 --- a/lib/services/ngsi/entities-NGSI-LD.js +++ b/lib/services/ngsi/entities-NGSI-LD.js @@ -23,25 +23,23 @@ * Modified by: Jason Fox - FIWARE Foundation */ -'use strict'; - -var request = require('request'), - statsService = require('./../stats/statsRegistry'), - async = require('async'), - apply = async.apply, - alarms = require('../common/alarmManagement'), - errors = require('../../errors'), - utils = require('../northBound/restUtils'), - config = require('../../commonConfig'), - constants = require('../../constants'), - moment = require('moment-timezone'), - logger = require('logops'), - _ = require('underscore'), - context = { - op: 'IoTAgentNGSI.Entities-LD' - }, - NGSIv2 = require('./entities-NGSI-v2'), - NGSIUtils = require('./ngsiUtils'); +const request = require('request'); +const statsService = require('./../stats/statsRegistry'); +const async = require('async'); +const apply = async.apply; +const alarms = require('../common/alarmManagement'); +const errors = require('../../errors'); +const utils = require('../northBound/restUtils'); +const config = require('../../commonConfig'); +const constants = require('../../constants'); +const moment = require('moment-timezone'); +const logger = require('logops'); +const _ = require('underscore'); +const context = { + op: 'IoTAgentNGSI.Entities-LD' +}; +const NGSIv2 = require('./entities-NGSI-v2'); +const NGSIUtils = require('./ngsiUtils'); const NGSI_LD_NULL = { '@type': 'Intangible', '@value': null }; const NGSI_LD_URN = 'urn:ngsi-ld:'; @@ -61,7 +59,7 @@ function valueOfOrNull(value) { * @return {Array} Array of Lat/Lngs for use as GeoJSON */ function splitLngLat(value) { - var lngLats = typeof value === 'string' || value instanceof String ? value.split(',') : value; + const lngLats = typeof value === 'string' || value instanceof String ? value.split(',') : value; lngLats.forEach((element, index, lngLats) => { if (Array.isArray(element)) { lngLats[index] = splitLngLat(element); @@ -79,7 +77,7 @@ function splitLngLat(value) { * @return {Array} split pairs of GeoJSON coordinates */ function getLngLats(value) { - var lngLats = _.flatten(splitLngLat(value)); + const lngLats = _.flatten(splitLngLat(value)); if (lngLats.length === 2) { return lngLats; } @@ -88,8 +86,8 @@ function getLngLats(value) { logger.error(context, 'Bad attribute value type.' + 'Expecting geo-coordinates. Received:%s', value); throw Error(); } - var arr = []; - for (var i = 0, len = lngLats.length; i < len; i = i + 2) { + const arr = []; + for (let i = 0, len = lngLats.length; i < len; i = i + 2) { arr.push([lngLats[i], lngLats[i + 1]]); } return arr; @@ -106,7 +104,7 @@ function getLngLats(value) { */ function convertNGSIv2ToLD(attr) { - var obj = { type: 'Property', value: attr.value }; + const obj = { type: 'Property', value: attr.value }; switch (attr.type.toLowerCase()) { // Properties case 'property': @@ -226,7 +224,7 @@ function convertNGSIv2ToLD(attr) { */ function formatAsNGSILD(json) { - var obj = { '@context': config.getConfig().contextBroker.jsonLdContext }; + const obj = { '@context': config.getConfig().contextBroker.jsonLdContext }; Object.keys(json).forEach(function(key) { switch (key) { case 'id': @@ -265,7 +263,7 @@ function formatAsNGSILD(json) { */ function generateNGSILDOperationHandler(operationName, entityName, typeInformation, token, options, callback) { return function(error, response, body) { - var bodyAsString = body ? JSON.stringify(body, null, 4) : ''; + const bodyAsString = body ? JSON.stringify(body, null, 4) : ''; if (error) { logger.error(context, 'Error found executing ' + operationName + ' action in Context Broker: %s', error); @@ -280,26 +278,21 @@ function generateNGSILDOperationHandler(operationName, entityName, typeInformati ); callback(new errors.BadRequest(body.orionError.details)); - } else if (response && operationName === 'update' && - (response.statusCode === 200 ||response.statusCode === 204)) { + } else if ( + response && + operationName === 'update' && + (response.statusCode === 200 || response.statusCode === 204) + ) { logger.debug(context, 'Received the following response from the CB: Value updated successfully\n'); alarms.release(constants.ORION_ALARM); callback(null, body); } else if (response && operationName === 'query' && body !== undefined && response.statusCode === 200) { - logger.debug( - context, - 'Received the following response from the CB:\n\n%s\n\n', - bodyAsString - ); + logger.debug(context, 'Received the following response from the CB:\n\n%s\n\n', bodyAsString); logger.debug(context, 'Value queried successfully'); alarms.release(constants.ORION_ALARM); callback(null, body); } else if (response && operationName === 'query' && response.statusCode === 204) { - logger.debug( - context, - 'Received the following response from the CB:\n\n%s\n\n', - bodyAsString - ); + logger.debug(context, 'Received the following response from the CB:\n\n%s\n\n', bodyAsString); logger.error( context, @@ -319,17 +312,16 @@ function generateNGSILDOperationHandler(operationName, entityName, typeInformati ) ); } else if (response && body && response.statusCode === 404) { - logger.debug( - context, - 'Received the following response from the CB:\n\n%s\n\n', - bodyAsString - ); + logger.debug(context, 'Received the following response from the CB:\n\n%s\n\n', bodyAsString); logger.error(context, 'Operation ' + operationName + ' error connecting to the Context Broker: %j', body); - var errorField = NGSIUtils.getErrorField(body); - if (response.statusCode && response.statusCode === 404 && - errorField.details.includes(typeInformation.type)) { + const errorField = NGSIUtils.getErrorField(body); + if ( + response.statusCode && + response.statusCode === 404 && + errorField.details.includes(typeInformation.type) + ) { callback(new errors.DeviceNotFound(entityName)); } else if (errorField.code && errorField.code === '404') { callback(new errors.AttributeNotFound()); @@ -357,13 +349,13 @@ function generateNGSILDOperationHandler(operationName, entityName, typeInformati * @param {String} token User token to identify against the PEP Proxies (optional). */ function sendQueryValueNgsiLD(entityName, attributes, typeInformation, token, callback) { - var url = '/ngsi-ld/v1/entities/urn:ngsi-ld:' + typeInformation.type + ':' + entityName; + let url = '/ngsi-ld/v1/entities/urn:ngsi-ld:' + typeInformation.type + ':' + entityName; - if (attributes && attributes.length > 0) { + if (attributes && attributes.length > 0) { url = url + '?attrs=' + attributes.join(','); - } + } - var options = NGSIUtils.createRequestObject(url, typeInformation, token); + const options = NGSIUtils.createRequestObject(url, typeInformation, token); options.method = 'GET'; options.json = true; @@ -388,7 +380,7 @@ function sendQueryValueNgsiLD(entityName, attributes, typeInformation, token, ca } /** - * Makes an update in the Device's entity in the context broker, with the values given in the 'attributes' array. + * Makes an update in the Device's entity in the context broker, with the values given in the 'attributes' array. * This array should comply to the NGSI-LD's attribute format. * * @param {String} entityName Name of the entity to register. @@ -397,7 +389,7 @@ function sendQueryValueNgsiLD(entityName, attributes, typeInformation, token, ca * @param {String} token User token to identify against the PEP Proxies (optional). */ function sendUpdateValueNgsiLD(entityName, attributes, typeInformation, token, callback) { - var payload = {}; + let payload = {}; /*var url = '/ngsi-ld/v1/entities/' + entityName + '/attrs'; @@ -405,9 +397,9 @@ function sendUpdateValueNgsiLD(entityName, attributes, typeInformation, token, c url += '?type=' + typeInformation.type; }*/ - var url = '/ngsi-ld/v1/entityOperations/upsert/'; + const url = '/ngsi-ld/v1/entityOperations/upsert/'; - var options = NGSIUtils.createRequestObject(url, typeInformation, token); + const options = NGSIUtils.createRequestObject(url, typeInformation, token); options.method = 'POST'; if (typeInformation && typeInformation.staticAttributes) { @@ -422,13 +414,13 @@ function sendUpdateValueNgsiLD(entityName, attributes, typeInformation, token, c payload.id = entityName; payload.type = typeInformation.type; - for (var i = 0; i < attributes.length; i++) { + for (let i = 0; i < attributes.length; i++) { if (attributes[i].name && attributes[i].type) { payload[attributes[i].name] = { value: attributes[i].value, type: attributes[i].type }; - var metadata = NGSIUtils.getMetaData(typeInformation, attributes[i].name, attributes[i].metadata); + const metadata = NGSIUtils.getMetaData(typeInformation, attributes[i].name, attributes[i].metadata); if (metadata) { payload[attributes[i].name].metadata = metadata; } @@ -451,8 +443,8 @@ function sendUpdateValueNgsiLD(entityName, attributes, typeInformation, token, c if (result) { // The payload has been transformed by multientity plugin. It is not a JSON object but an Array. if (result instanceof Array) { - if ('timestamp' in typeInformation && typeInformation.timestamp !== undefined ? - typeInformation.timestamp : config.getConfig().timestamp) { + if ('timestamp' in typeInformation && typeInformation.timestamp !== undefined ? + typeInformation.timestamp : config.getConfig().timestamp) { // jshint maxdepth:5 if (!utils.isTimestampedNgsi2(result)) { options.json = NGSIv2.addTimestamp(result, typeInformation.timezone); @@ -470,8 +462,8 @@ function sendUpdateValueNgsiLD(entityName, attributes, typeInformation, token, c delete result.type; options.json = result; logger.debug(context, 'typeInformation: %j', typeInformation); - if ('timestamp' in typeInformation && typeInformation.timestamp !== undefined ? - typeInformation.timestamp : config.getConfig().timestamp) { + if ('timestamp' in typeInformation && typeInformation.timestamp !== undefined ? + typeInformation.timestamp : config.getConfig().timestamp) { if (!utils.isTimestampedNgsi2(options.json)) { options.json = NGSIv2.addTimestamp(options.json, typeInformation.timezone); } else if (!utils.IsValidTimestampedNgsi2(options.json)) { @@ -489,9 +481,9 @@ function sendUpdateValueNgsiLD(entityName, attributes, typeInformation, token, c // Purge object_id from entities before sent to CB // object_id was added by createNgsi2Entity to allow multientity // with duplicate attribute names. - var att; + let att; if (options.json) { - for (var entity = 0; entity < options.json.length; entity++) { + for (let entity = 0; entity < options.json.length; entity++) { for (att in options.json[entity]) { /*jshint camelcase: false */ if (options.json[entity][att].object_id) { @@ -535,8 +527,6 @@ function sendUpdateValueNgsiLD(entityName, attributes, typeInformation, token, c JSON.stringify(options, null, 4) ); - //console.error(JSON.stringify(options, null, 4)); - request( options, generateNGSILDOperationHandler('update', entityName, typeInformation, token, options, callback) diff --git a/lib/services/ngsi/entities-NGSI-v1.js b/lib/services/ngsi/entities-NGSI-v1.js index 467751baf..6948dedcd 100644 --- a/lib/services/ngsi/entities-NGSI-v1.js +++ b/lib/services/ngsi/entities-NGSI-v1.js @@ -25,23 +25,21 @@ * Modified by: Jason Fox - FIWARE Foundation */ -'use strict'; - -var request = require('request'), - statsService = require('./../stats/statsRegistry'), - async = require('async'), - apply = async.apply, - alarms = require('../common/alarmManagement'), - errors = require('../../errors'), - utils = require('../northBound/restUtils'), - config = require('../../commonConfig'), - constants = require('../../constants'), - moment = require('moment-timezone'), - logger = require('logops'), - context = { - op: 'IoTAgentNGSI.Entities-v1' - }, - ngsiUtils = require('./ngsiUtils'); +const request = require('request'); +const statsService = require('./../stats/statsRegistry'); +const async = require('async'); +const apply = async.apply; +const alarms = require('../common/alarmManagement'); +const errors = require('../../errors'); +const utils = require('../northBound/restUtils'); +const config = require('../../commonConfig'); +const constants = require('../../constants'); +const moment = require('moment-timezone'); +const logger = require('logops'); +const context = { + op: 'IoTAgentNGSI.Entities-v1' +}; +const ngsiUtils = require('./ngsiUtils'); /** * Generate an operation handler for NGSI-based operations (query and update). The handler takes care of identifiying @@ -73,7 +71,7 @@ function generateNGSIOperationHandler(operationName, entityName, typeInformation callback(new errors.BadRequest(body.orionError.details)); } else if (response && body && response.statusCode === 200) { - var errorField = ngsiUtils.getErrorField(body); + const errorField = ngsiUtils.getErrorField(body); logger.debug( context, @@ -127,7 +125,7 @@ function generateNGSIOperationHandler(operationName, entityName, typeInformation } function addTimestamp(payload, timezone) { - var timestamp = { + const timestamp = { name: constants.TIMESTAMP_ATTRIBUTE, type: constants.TIMESTAMP_TYPE }; @@ -141,15 +139,17 @@ function addTimestamp(payload, timezone) { } function addMetadata(attribute) { - var timestampFound = false; + let timestampFound = false; if (!attribute.metadatas) { attribute.metadatas = []; } - for (var i = 0; i < attribute.metadatas.length; i++) { - if ( attribute.metadatas[i].type === constants.TIMESTAMP_TYPE && - attribute.metadatas[i].name === constants.TIMESTAMP_ATTRIBUTE) { + for (let i = 0; i < attribute.metadatas.length; i++) { + if ( + attribute.metadatas[i].type === constants.TIMESTAMP_TYPE && + attribute.metadatas[i].name === constants.TIMESTAMP_ATTRIBUTE + ) { attribute.metadatas[i].value = timestamp.value; timestampFound = true; break; @@ -178,7 +178,7 @@ function addTimestamp(payload, timezone) { * @param {String} token User token to identify against the PEP Proxies (optional). */ function sendQueryValueNgsi1(entityName, attributes, typeInformation, token, callback) { - var options = ngsiUtils.createRequestObject('/v1/queryContext', typeInformation, token); + const options = ngsiUtils.createRequestObject('/v1/queryContext', typeInformation, token); if (!typeInformation || !typeInformation.type) { callback(new errors.TypeNotFound(null, entityName)); @@ -193,7 +193,7 @@ function sendQueryValueNgsi1(entityName, attributes, typeInformation, token, cal id: entityName } ], - attributes: attributes + attributes }; logger.debug(context, 'Querying values of the device in the Context Broker at [%s]', options.url); @@ -221,8 +221,8 @@ function sendQueryValueNgsi1(entityName, attributes, typeInformation, token, cal * @param {String} token User token to identify against the PEP Proxies (optional). */ function sendUpdateValueNgsi1(entityName, attributes, typeInformation, token, callback) { - var options = ngsiUtils.createRequestObject('/v1/updateContext', typeInformation, token), - payload; + const options = ngsiUtils.createRequestObject('/v1/updateContext', typeInformation, token); + let payload; if (typeInformation && typeInformation.staticAttributes) { attributes = attributes.concat(typeInformation.staticAttributes); @@ -239,15 +239,15 @@ function sendUpdateValueNgsi1(entityName, attributes, typeInformation, token, ca type: typeInformation.type, isPattern: 'false', id: entityName, - attributes: attributes + attributes } ] }; - if ('autoprovision' in typeInformation && + if ( + 'autoprovision' in typeInformation && /* jshint -W101 */ typeInformation.autoprovision === undefined ? - typeInformation.autoprovision === true : - config.getConfig().appendMode === true) { + typeInformation.autoprovision === true : config.getConfig().appendMode === true ) { payload.updateAction = 'APPEND'; } else { payload.updateAction = 'UPDATE'; @@ -267,8 +267,8 @@ function sendUpdateValueNgsi1(entityName, attributes, typeInformation, token, ca options.json = payload; } - if ('timestamp' in typeInformation && typeInformation.timestamp !== undefined ? - typeInformation.timestamp : config.getConfig().timestamp) { + if ('timestamp' in typeInformation && typeInformation.timestamp !== undefined ? + typeInformation.timestamp : config.getConfig().timestamp ) { if (!utils.isTimestamped(options.json)) { options.json = addTimestamp(options.json, typeInformation.timezone); } else if (!utils.IsValidTimestamped(options.json)) { @@ -285,8 +285,6 @@ function sendUpdateValueNgsi1(entityName, attributes, typeInformation, token, ca JSON.stringify(options, null, 4) ); - //console.error(JSON.stringify(options.json, null, 4)); - request( options, generateNGSIOperationHandler('update', entityName, typeInformation, token, options, callback) diff --git a/lib/services/ngsi/entities-NGSI-v2.js b/lib/services/ngsi/entities-NGSI-v2.js index c6986f597..6234b4319 100644 --- a/lib/services/ngsi/entities-NGSI-v2.js +++ b/lib/services/ngsi/entities-NGSI-v2.js @@ -25,27 +25,25 @@ * Modified by: Jason Fox - FIWARE Foundation */ -'use strict'; - -var request = require('request'), - statsService = require('./../stats/statsRegistry'), - async = require('async'), - apply = async.apply, - alarms = require('../common/alarmManagement'), - errors = require('../../errors'), - utils = require('../northBound/restUtils'), - config = require('../../commonConfig'), - constants = require('../../constants'), - moment = require('moment-timezone'), - logger = require('logops'), - context = { - op: 'IoTAgentNGSI.Entities-v2' - }, - NGSIUtils = require('./ngsiUtils'); +const request = require('request'); +const statsService = require('./../stats/statsRegistry'); +const async = require('async'); +const apply = async.apply; +const alarms = require('../common/alarmManagement'); +const errors = require('../../errors'); +const utils = require('../northBound/restUtils'); +const config = require('../../commonConfig'); +const constants = require('../../constants'); +const moment = require('moment-timezone'); +const logger = require('logops'); +const context = { + op: 'IoTAgentNGSI.Entities-v2' +}; +const NGSIUtils = require('./ngsiUtils'); function addTimestampNgsi2(payload, timezone) { function addTimestampEntity(entity, timezone) { - var timestamp = { + const timestamp = { type: constants.TIMESTAMP_TYPE_NGSI2 }; @@ -58,16 +56,18 @@ function addTimestampNgsi2(payload, timezone) { } function addMetadata(attribute) { - var timestampFound = false; + let timestampFound = false; if (!attribute.metadata) { attribute.metadata = {}; } - for (var i = 0; i < attribute.metadata.length; i++) { + for (let i = 0; i < attribute.metadata.length; i++) { if (attribute.metadata[i] === constants.TIMESTAMP_ATTRIBUTE) { - if (attribute.metadata[constants.TIMESTAMP_ATTRIBUTE].type === constants.TIMESTAMP_TYPE_NGSI2 && - attribute.metadata[constants.TIMESTAMP_ATTRIBUTE].value === timestamp.value) { + if ( + attribute.metadata[constants.TIMESTAMP_ATTRIBUTE].type === constants.TIMESTAMP_TYPE_NGSI2 && + attribute.metadata[constants.TIMESTAMP_ATTRIBUTE].value === timestamp.value + ) { timestampFound = true; break; } @@ -80,8 +80,8 @@ function addTimestampNgsi2(payload, timezone) { return attribute; } - var keyCount = 0; - for (var key in entity) { + let keyCount = 0; + for (const key in entity) { if (entity.hasOwnProperty(key) && key !== 'id' && key !== 'type') { addMetadata(entity[key]); keyCount += 1; @@ -97,16 +97,15 @@ function addTimestampNgsi2(payload, timezone) { } if (payload instanceof Array) { - for (var i = 0; i < payload.length; i++) { + for (let i = 0; i < payload.length; i++) { if (!utils.isTimestampedNgsi2(payload[i])) { payload[i] = addTimestampEntity(payload[i], timezone); } } return payload; - } else { - return addTimestampEntity(payload, timezone); } + return addTimestampEntity(payload, timezone); } /** @@ -184,9 +183,12 @@ function generateNGSI2OperationHandler(operationName, entityName, typeInformatio logger.error(context, 'Operation ' + operationName + ' error connecting to the Context Broker: %j', body); - var errorField = NGSIUtils.getErrorField(body); - if (response.statusCode && response.statusCode === 404 && - errorField.details.includes(typeInformation.type)) { + const errorField = NGSIUtils.getErrorField(body); + if ( + response.statusCode && + response.statusCode === 404 && + errorField.details.includes(typeInformation.type) + ) { callback(new errors.DeviceNotFound(entityName)); } else if (errorField.code && errorField.code === '404') { callback(new errors.AttributeNotFound()); @@ -214,12 +216,12 @@ function generateNGSI2OperationHandler(operationName, entityName, typeInformatio * @param {String} token User token to identify against the PEP Proxies (optional). */ function sendQueryValueNgsi2(entityName, attributes, typeInformation, token, callback) { - var url = '/v2/entities/' + entityName + '/attrs'; + let url = '/v2/entities/' + entityName + '/attrs'; if (attributes && attributes.length > 0) { - var attributesQueryParam = ''; + let attributesQueryParam = ''; - for (var i = 0; i < attributes.length; i++) { + for (let i = 0; i < attributes.length; i++) { attributesQueryParam = attributesQueryParam + attributes[i]; if (i < attributes.length - 1) { attributesQueryParam = attributesQueryParam + ','; @@ -237,7 +239,7 @@ function sendQueryValueNgsi2(entityName, attributes, typeInformation, token, cal } } - var options = NGSIUtils.createRequestObject(url, typeInformation, token); + const options = NGSIUtils.createRequestObject(url, typeInformation, token); options.method = 'GET'; options.json = true; @@ -271,15 +273,15 @@ function sendQueryValueNgsi2(entityName, attributes, typeInformation, token, cal * @param {String} token User token to identify against the PEP Proxies (optional). */ function sendUpdateValueNgsi2(entityName, attributes, typeInformation, token, callback) { - var payload = {}; + let payload = {}; - var url = '/v2/entities/' + entityName + '/attrs'; + let url = '/v2/entities/' + entityName + '/attrs'; if (typeInformation.type) { url += '?type=' + typeInformation.type; } - var options = NGSIUtils.createRequestObject(url, typeInformation, token); + let options = NGSIUtils.createRequestObject(url, typeInformation, token); if (typeInformation && typeInformation.staticAttributes) { attributes = attributes.concat(typeInformation.staticAttributes); @@ -293,13 +295,13 @@ function sendUpdateValueNgsi2(entityName, attributes, typeInformation, token, ca payload.id = entityName; payload.type = typeInformation.type; - for (var i = 0; i < attributes.length; i++) { + for (let i = 0; i < attributes.length; i++) { if (attributes[i].name && attributes[i].type) { payload[attributes[i].name] = { value: attributes[i].value, type: attributes[i].type }; - var metadata = NGSIUtils.getMetaData(typeInformation, attributes[i].name, attributes[i].metadata); + const metadata = NGSIUtils.getMetaData(typeInformation, attributes[i].name, attributes[i].metadata); if (metadata) { payload[attributes[i].name].metadata = metadata; } @@ -324,7 +326,7 @@ function sendUpdateValueNgsi2(entityName, attributes, typeInformation, token, ca if (result instanceof Array) { options = NGSIUtils.createRequestObject('/v2/op/update', typeInformation, token); - if ('timestamp' in typeInformation && typeInformation.timestamp !== undefined ? + if ('timestamp' in typeInformation && typeInformation.timestamp !== undefined ? typeInformation.timestamp : config.getConfig().timestamp) { // jshint maxdepth:5 if (!utils.isTimestampedNgsi2(result)) { @@ -346,7 +348,7 @@ function sendUpdateValueNgsi2(entityName, attributes, typeInformation, token, ca delete result.type; options.json = result; logger.debug(context, 'typeInformation: %j', typeInformation); - if ('timestamp' in typeInformation && typeInformation.timestamp !== undefined ? + if ('timestamp' in typeInformation && typeInformation.timestamp !== undefined ? typeInformation.timestamp : config.getConfig().timestamp) { if (!utils.isTimestampedNgsi2(options.json)) { options.json = addTimestampNgsi2(options.json, typeInformation.timezone); @@ -365,9 +367,9 @@ function sendUpdateValueNgsi2(entityName, attributes, typeInformation, token, ca // Purge object_id from entities before sent to CB // object_id was added by createNgsi2Entity to allow multientity // with duplicate attribute names. - var att; + let att; if (options.json.entities) { - for (var entity = 0; entity < options.json.entities.length; entity++) { + for (let entity = 0; entity < options.json.entities.length; entity++) { for (att in options.json.entities[entity]) { /*jshint camelcase: false */ if (options.json.entities[entity][att].object_id) { diff --git a/lib/services/ngsi/ngsiService.js b/lib/services/ngsi/ngsiService.js index 13f5bc0ff..413e96ad5 100644 --- a/lib/services/ngsi/ngsiService.js +++ b/lib/services/ngsi/ngsiService.js @@ -24,23 +24,21 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var async = require('async'), - apply = async.apply, - intoTrans = require('../common/domain').intoTrans, - errors = require('../../errors'), - config = require('../../commonConfig'), - constants = require('../../constants'), - logger = require('logops'), - ngsiUtils = require('./ngsiUtils'), - _ = require('underscore'), - context = { - op: 'IoTAgentNGSI.NGSIService' - }; +const async = require('async'); +const apply = async.apply; +const intoTrans = require('../common/domain').intoTrans; +const errors = require('../../errors'); +const config = require('../../commonConfig'); +const constants = require('../../constants'); +const logger = require('logops'); +const ngsiUtils = require('./ngsiUtils'); +const _ = require('underscore'); +const context = { + op: 'IoTAgentNGSI.NGSIService' +}; -var entityHandler; +let entityHandler; /** * Loads the correct ngsiService handler based on the current config. @@ -95,7 +93,7 @@ function sendQueryValue(entityName, attributes, typeInformation, token, callback function updateTrust(deviceGroup, deviceInformation, trust, response, callback) { if (deviceGroup && response && response.body && !config.getConfig().authentication.permanentToken) { - var body = JSON.parse(response.body); + const body = JSON.parse(response.body); /* jshint camelcase: false */ if (body && body.refresh_token) { deviceGroup.trust = body.refresh_token; @@ -130,7 +128,7 @@ function executeWithDeviceInformation(operationFunction) { deviceInformation ); config.getGroupRegistry().getType(type, function(error, deviceGroup) { - var typeInformation; + let typeInformation; if (error) { logger.debug(context, 'error %j in get group device', error); } @@ -158,7 +156,7 @@ function executeWithDeviceInformation(operationFunction) { } if (config.getConfig().authentication && config.getConfig().authentication.enabled) { - var security = config.getSecurityService(); + const security = config.getSecurityService(); if (typeInformation && typeInformation.trust) { async.waterfall( [ @@ -202,20 +200,20 @@ function setCommandResult( callback ) { config.getGroupRegistry().get(resource, apikey, function(error, deviceGroup) { - var typeInformation, - commandInfo, - attributes = [ - { - name: commandName + constants.COMMAND_STATUS_SUFIX, - type: constants.COMMAND_STATUS, - value: status - }, - { - name: commandName + constants.COMMAND_RESULT_SUFIX, - type: constants.COMMAND_RESULT, - value: commandResult - } - ]; + let typeInformation; + let commandInfo; + const attributes = [ + { + name: commandName + constants.COMMAND_STATUS_SUFIX, + type: constants.COMMAND_STATUS, + value: status + }, + { + name: commandName + constants.COMMAND_RESULT_SUFIX, + type: constants.COMMAND_RESULT, + value: commandResult + } + ]; if (!callback) { callback = deviceInformation; diff --git a/lib/services/ngsi/ngsiUtils.js b/lib/services/ngsi/ngsiUtils.js index 402300674..f7bfde617 100644 --- a/lib/services/ngsi/ngsiUtils.js +++ b/lib/services/ngsi/ngsiUtils.js @@ -20,20 +20,19 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::[contacto@tid.es] */ -'use strict'; /*jshint unused:false*/ -var async = require('async'), - errors = require('../../errors'), - logger = require('logops'), - intoTrans = require('../common/domain').intoTrans, - context = { - op: 'IoTAgentNGSI.NGSIUtils' - }, - _ = require('underscore'), - config = require('../../commonConfig'), - updateMiddleware = [], - queryMiddleware = []; +const async = require('async'); +const errors = require('../../errors'); +const logger = require('logops'); +const intoTrans = require('../common/domain').intoTrans; +const context = { + op: 'IoTAgentNGSI.NGSIUtils' +}; +const _ = require('underscore'); +const config = require('../../commonConfig'); +const updateMiddleware = []; +const queryMiddleware = []; /** * Determines if a value is of type float * @@ -55,9 +54,13 @@ function castJsonNativeAttributes(payload) { return payload; } - for (var key in payload) { - if (payload.hasOwnProperty(key) && payload[key].value && - payload[key].type && typeof payload[key].value === 'string') { + for (const key in payload) { + if ( + payload.hasOwnProperty(key) && + payload[key].value && + payload[key].type && + typeof payload[key].value === 'string' + ) { if (payload[key].type === 'Number' && isFloat(payload[key].value)) { payload[key].value = Number.parseFloat(payload[key].value); } else if (payload[key].type === 'Number' && Number.parseInt(payload[key].value)) { @@ -68,7 +71,7 @@ function castJsonNativeAttributes(payload) { payload[key].value = null; } else if (payload[key].type === 'Array' || payload[key].type === 'Object') { try { - var parsedValue = JSON.parse(payload[key].value); + const parsedValue = JSON.parse(payload[key].value); payload[key].value = parsedValue; } catch (e) { logger.error( @@ -92,15 +95,13 @@ function castJsonNativeAttributes(payload) { * @return {Object} Containing all the information of the request but the payload.c */ function createRequestObject(url, typeInformation, token) { - var cbHost = config.getConfig().contextBroker.url, - options, - serviceContext = {}, - headers = { - 'fiware-service': config.getConfig().service, - 'fiware-servicepath': config.getConfig().subservice - }; - - + let cbHost = config.getConfig().contextBroker.url; + let options; + const serviceContext = {}; + const headers = { + 'fiware-service': config.getConfig().service, + 'fiware-servicepath': config.getConfig().subservice + }; if (config.getConfig().authentication && config.getConfig().authentication.enabled) { headers[config.getConfig().authentication.header] = token; @@ -127,13 +128,13 @@ function createRequestObject(url, typeInformation, token) { if (config.checkNgsiLD()) { headers['Content-Type'] = 'application/ld+json'; headers['NGSILD-Tenant'] = headers['fiware-service']; - headers['NGSILD-Path'] = headers['fiware-servicepath']; + headers['NGSILD-Path'] = headers['fiware-servicepath']; } options = { url: cbHost + url, method: 'POST', - headers: headers + headers }; return intoTrans(serviceContext, function() { @@ -151,7 +152,7 @@ function applyMiddlewares(middlewareCollection, entity, typeInformation, callbac } if (middlewareCollection && middlewareCollection.length > 0) { - var middlewareList = _.clone(middlewareCollection); + const middlewareList = _.clone(middlewareCollection); middlewareList.unshift(emptyMiddleware); middlewareList.push(endMiddleware); @@ -167,7 +168,7 @@ function getMetaData(typeInformation, name, metadata) { return metadata; } - var i; + let i; if (typeInformation.active) { for (i = 0; i < typeInformation.active.length; i++) { /* jshint camelcase: false */ @@ -193,10 +194,10 @@ function getMetaData(typeInformation, name, metadata) { * @return {Number|*} */ function getErrorField(body) { - var errorField = body.errorCode || body.orionError; + let errorField = body.errorCode || body.orionError; if (body && body.contextResponses) { - for (var i in body.contextResponses) { + for (const i in body.contextResponses) { if (body.contextResponses[i].statusCode && body.contextResponses[i].statusCode.code !== '200') { errorField = body.contextResponses[i].statusCode; } diff --git a/lib/services/ngsi/subscription-NGSI-LD.js b/lib/services/ngsi/subscription-NGSI-LD.js index f16e60e75..a142e2108 100644 --- a/lib/services/ngsi/subscription-NGSI-LD.js +++ b/lib/services/ngsi/subscription-NGSI-LD.js @@ -23,13 +23,13 @@ * Modified by: Jason Fox - FIWARE Foundation */ -var errors = require('../../errors'), - logger = require('logops'), - config = require('../../commonConfig'), - utils = require('../northBound/restUtils'), - context = { - op: 'IoTAgentNGSI.Subscription-LD' - }; +const errors = require('../../errors'); +const logger = require('logops'); +const config = require('../../commonConfig'); +const utils = require('../northBound/restUtils'); +const context = { + op: 'IoTAgentNGSI.Subscription-LD' +}; /** * Generate a new subscription request handler using NGSI-LD, based on the device and triggers given to the function. @@ -85,7 +85,7 @@ function createSubscriptionHandlerNgsiLD(device, triggers, store, callback) { device.subscriptions.push({ id: response.headers.location.substr(response.headers.location.lastIndexOf('/') + 1), - triggers: triggers + triggers }); config.getRegistry().update(device, callback); @@ -105,7 +105,7 @@ function createSubscriptionHandlerNgsiLD(device, triggers, store, callback) { * @param {Object} content Array with the names of the attributes to retrieve in the notification. */ function subscribeNgsiLD(device, triggers, content, callback) { - var options = { + const options = { method: 'POST', headers: { 'fiware-service': device.service @@ -129,7 +129,7 @@ function subscribeNgsiLD(device, triggers, content, callback) { } }; - var store = true; + let store = true; if (content) { store = false; @@ -206,7 +206,7 @@ function createUnsubscribeHandlerNgsiLD(device, id, callback) { * @param {String} id ID of the subscription to remove. */ function unsubscribeNgsiLD(device, id, callback) { - var options = { + const options = { method: 'DELETE', headers: { 'fiware-service': device.service, diff --git a/lib/services/ngsi/subscription-NGSI-v1.js b/lib/services/ngsi/subscription-NGSI-v1.js index 4ccc19414..59ee21e9e 100644 --- a/lib/services/ngsi/subscription-NGSI-v1.js +++ b/lib/services/ngsi/subscription-NGSI-v1.js @@ -25,13 +25,13 @@ * Modified by: Jason Fox - FIWARE Foundation */ -var errors = require('../../errors'), - logger = require('logops'), - config = require('../../commonConfig'), - utils = require('../northBound/restUtils'), - context = { - op: 'IoTAgentNGSI.Subscription-v1' - }; +const errors = require('../../errors'); +const logger = require('logops'); +const config = require('../../commonConfig'); +const utils = require('../northBound/restUtils'); +const context = { + op: 'IoTAgentNGSI.Subscription-v1' +}; /** * Generate a new subscription request handler using NGSIv1, based on the device and triggers given to the function. @@ -87,7 +87,7 @@ function createSubscriptionHandlerNgsi1(device, triggers, store, callback) { device.subscriptions.push({ id: body.subscribeResponse.subscriptionId, - triggers: triggers + triggers }); config.getRegistry().update(device, callback); @@ -107,31 +107,31 @@ function createSubscriptionHandlerNgsi1(device, triggers, store, callback) { * @param {Object} content Array with the names of the attributes to retrieve in the notification. */ function subscribeNgsi1(device, triggers, content, callback) { - var options = { - method: 'POST', - headers: { - 'fiware-service': device.service, - 'fiware-servicepath': device.subservice - }, - json: { - entities: [ - { - type: device.type, - isPattern: 'false', - id: device.name - } - ], - reference: config.getConfig().providerUrl + '/notify', - duration: config.getConfig().deviceRegistrationDuration || 'P100Y', - notifyConditions: [ - { - type: 'ONCHANGE', - condValues: triggers - } - ] - } + const options = { + method: 'POST', + headers: { + 'fiware-service': device.service, + 'fiware-servicepath': device.subservice }, - store = true; + json: { + entities: [ + { + type: device.type, + isPattern: 'false', + id: device.name + } + ], + reference: config.getConfig().providerUrl + '/notify', + duration: config.getConfig().deviceRegistrationDuration || 'P100Y', + notifyConditions: [ + { + type: 'ONCHANGE', + condValues: triggers + } + ] + } + }; + let store = true; if (content) { options.json.attributes = content; @@ -209,7 +209,7 @@ function createUnsubscribeHandlerNgsi1(device, id, callback) { * @param {String} id ID of the subscription to remove. */ function unsubscribeNgsi1(device, id, callback) { - var options = { + const options = { method: 'POST', headers: { 'fiware-service': device.service, diff --git a/lib/services/ngsi/subscription-NGSI-v2.js b/lib/services/ngsi/subscription-NGSI-v2.js index 25dcaea22..1da9b1aa6 100644 --- a/lib/services/ngsi/subscription-NGSI-v2.js +++ b/lib/services/ngsi/subscription-NGSI-v2.js @@ -25,13 +25,13 @@ * Modified by: Jason Fox - FIWARE Foundation */ -var errors = require('../../errors'), - logger = require('logops'), - config = require('../../commonConfig'), - utils = require('../northBound/restUtils'), - context = { - op: 'IoTAgentNGSI.Subscription-v2' - }; +const errors = require('../../errors'); +const logger = require('logops'); +const config = require('../../commonConfig'); +const utils = require('../northBound/restUtils'); +const context = { + op: 'IoTAgentNGSI.Subscription-v2' +}; /** * Generate a new subscription request handler using NGSIv2, based on the device and triggers given to the function. @@ -87,7 +87,7 @@ function createSubscriptionHandlerNgsi2(device, triggers, store, callback) { device.subscriptions.push({ id: response.headers.location.substr(response.headers.location.lastIndexOf('/') + 1), - triggers: triggers + triggers }); config.getRegistry().update(device, callback); @@ -107,7 +107,7 @@ function createSubscriptionHandlerNgsi2(device, triggers, store, callback) { * @param {Object} content Array with the names of the attributes to retrieve in the notification. */ function subscribeNgsi2(device, triggers, content, callback) { - var options = { + const options = { method: 'POST', headers: { 'fiware-service': device.service, @@ -136,7 +136,7 @@ function subscribeNgsi2(device, triggers, content, callback) { } }; - var store = true; + let store = true; if (content) { store = false; @@ -213,7 +213,7 @@ function createUnsubscribeHandlerNgsi2(device, id, callback) { * @param {String} id ID of the subscription to remove. */ function unsubscribeNgsi2(device, id, callback) { - var options = { + const options = { method: 'DELETE', headers: { 'fiware-service': device.service, diff --git a/lib/services/ngsi/subscriptionService.js b/lib/services/ngsi/subscriptionService.js index f8f09b884..4adbea442 100644 --- a/lib/services/ngsi/subscriptionService.js +++ b/lib/services/ngsi/subscriptionService.js @@ -24,16 +24,13 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var intoTrans = require('../common/domain').intoTrans, - context = { - op: 'IoTAgentNGSI.SubscriptionService' - }, - config = require('../../commonConfig'); - -var subscriptionHandler; +const intoTrans = require('../common/domain').intoTrans; +const context = { + op: 'IoTAgentNGSI.SubscriptionService' +}; +const config = require('../../commonConfig'); +let subscriptionHandler; /** * Loads the correct subscription handler based on the current config. diff --git a/lib/services/northBound/contextServer-NGSI-LD.js b/lib/services/northBound/contextServer-NGSI-LD.js index 7273f09c2..0d2f3fd3b 100644 --- a/lib/services/northBound/contextServer-NGSI-LD.js +++ b/lib/services/northBound/contextServer-NGSI-LD.js @@ -22,21 +22,20 @@ * * Modified by: Jason Fox - FIWARE Foundation */ -'use strict'; - -var async = require('async'), - apply = async.apply, - logger = require('logops'), - errors = require('../../errors'), - deviceService = require('../devices/deviceService'), - middlewares = require('../common/genericMiddleware'), - _ = require('underscore'), - context = { - op: 'IoTAgentNGSI.ContextServer-LD' - }, - updateContextTemplateNgsiLD = require('../../templates/updateContextNgsiLD.json'), - notificationTemplateNgsiLD = require('../../templates/notificationTemplateNgsiLD.json'), - contextServerUtils = require('./contextServerUtils'); + +const async = require('async'); +const apply = async.apply; +const logger = require('logops'); +const errors = require('../../errors'); +const deviceService = require('../devices/deviceService'); +const middlewares = require('../common/genericMiddleware'); +const _ = require('underscore'); +const context = { + op: 'IoTAgentNGSI.ContextServer-LD' +}; +const updateContextTemplateNgsiLD = require('../../templates/updateContextNgsiLD.json'); +const notificationTemplateNgsiLD = require('../../templates/notificationTemplateNgsiLD.json'); +const contextServerUtils = require('./contextServerUtils'); const updatePaths = ['/ngsi-ld/v1/entities/:entity/attrs/:attr']; const queryPaths = ['/ngsi-ld/v1/entities/:entity']; @@ -49,10 +48,10 @@ const queryPaths = ['/ngsi-ld/v1/entities/:entity']; * @param {Object} contextElement Context Element whose actions will be extracted. */ function generateUpdateActionsNgsiLD(req, contextElement, callback) { - var entityId; - var entityType; - var attribute = req.params.attr; - var value = req.body.value; + let entityId; + let entityType; + const attribute = req.params.attr; + const value = req.body.value; if (contextElement.id && contextElement.type) { entityId = contextElement.id; @@ -62,12 +61,12 @@ function generateUpdateActionsNgsiLD(req, contextElement, callback) { } function splitUpdates(device, callback) { - var attributes = [], - commands = [], - found; + const attributes = []; + const commands = []; + let found; if (device.commands) { - for (var j in device.commands) { + for (const j in device.commands) { if (attribute === device.commands[j].name) { commands.push({ type: device.commands[j].type, @@ -90,7 +89,7 @@ function generateUpdateActionsNgsiLD(req, contextElement, callback) { } function createActionsArray(attributes, commands, device, callback) { - var updateActions = []; + const updateActions = []; if (!entityType) { entityType = device.type; @@ -151,31 +150,31 @@ function generateUpdateActionsNgsiLD(req, contextElement, callback) { callback(null, updateActions); } - deviceService.getDeviceByName(entityId, - contextServerUtils.getLDTenant(req), - contextServerUtils.getLDPath(req), function( - error, - deviceObj - ) { - if (error) { - callback(error); - } else { - async.waterfall( - [ - apply(deviceService.findConfigurationGroup, deviceObj), - apply( - deviceService.mergeDeviceWithConfiguration, - ['lazy', 'internalAttributes', 'active', 'staticAttributes', 'commands', 'subscriptions'], - [null, null, [], [], [], [], []], - deviceObj - ), - splitUpdates, - createActionsArray - ], - callback - ); + deviceService.getDeviceByName( + entityId, + contextServerUtils.getLDTenant(req), + contextServerUtils.getLDPath(req), + function(error, deviceObj) { + if (error) { + callback(error); + } else { + async.waterfall( + [ + apply(deviceService.findConfigurationGroup, deviceObj), + apply( + deviceService.mergeDeviceWithConfiguration, + ['lazy', 'internalAttributes', 'active', 'staticAttributes', 'commands', 'subscriptions'], + [null, null, [], [], [], [], []], + deviceObj + ), + splitUpdates, + createActionsArray + ], + callback + ); + } } - }); + ); } /** Express middleware to manage incoming update requests using NGSI-LD. @@ -191,7 +190,7 @@ function handleUpdateNgsiLD(req, res, next) { if (contextServerUtils.updateHandler || contextServerUtils.commandHandler) { logger.debug(context, 'Handling LD update from [%s]', req.get('host')); if (req.body) { - logger.debug(context, JSON.stringify(req.body , null, 4)); + logger.debug(context, JSON.stringify(req.body, null, 4)); } async.waterfall( @@ -199,7 +198,6 @@ function handleUpdateNgsiLD(req, res, next) { function(error, result) { if (error) { logger.debug(context, 'There was an error handling the update action: %s.', error); - //console.error(JSON.stringify(error)); next(error); } else { logger.debug(context, 'Update action from [%s] handled successfully.', req.get('host')); @@ -210,7 +208,7 @@ function handleUpdateNgsiLD(req, res, next) { } else { logger.error(context, 'Tried to handle an update request before the update handler was established.'); - var errorNotFound = new Error({ + const errorNotFound = new Error({ message: 'Update handler not found' }); next(errorNotFound); @@ -228,19 +226,19 @@ function handleUpdateNgsiLD(req, res, next) { * @param {Array} attributes List of attributes to read. */ function defaultQueryHandlerNgsiLD(id, type, service, subservice, attributes, callback) { - var contextElement = { - type: type, - id: id + const contextElement = { + type, + id }; deviceService.getDeviceByName(id, service, subservice, function(error, ngsiDevice) { if (error) { callback(error); } else { - for (var i = 0; i < attributes.length; i++) { - var lazyAttribute = _.findWhere(ngsiDevice.lazy, { name: attributes[i] }), - command = _.findWhere(ngsiDevice.commands, { name: attributes[i] }), - attributeType; + for (let i = 0; i < attributes.length; i++) { + const lazyAttribute = _.findWhere(ngsiDevice.lazy, { name: attributes[i] }); + const command = _.findWhere(ngsiDevice.commands, { name: attributes[i] }); + var attributeType; if (command) { attributeType = command.type; @@ -278,14 +276,14 @@ function handleQueryNgsiLD(req, res, next) { } if (device.staticAttributes) { - var selectedAttributes = []; + let selectedAttributes = []; if (attributes === undefined || attributes.length === 0) { selectedAttributes = device.staticAttributes; } else { selectedAttributes = device.staticAttributes.filter(inAttributes); } - for (var att in selectedAttributes) { + for (const att in selectedAttributes) { contextElement[selectedAttributes[att].name] = { type: selectedAttributes[att].type, value: selectedAttributes[att].value @@ -302,7 +300,7 @@ function handleQueryNgsiLD(req, res, next) { callback(null, attributes); } else if (device.lazy) { logger.debug(context, 'Handling stored set of attributes: %j', attributes); - var results = device.lazy.map(getName); + const results = device.lazy.map(getName); callback(null, results); } else { logger.debug(context, 'Couldn\'t find any attributes. Handling with null reference'); @@ -311,8 +309,8 @@ function handleQueryNgsiLD(req, res, next) { } function finishQueryForDevice(attributes, contextEntity, actualHandler, device, callback) { - var contextId = contextEntity.id; - var contextType = contextEntity.type; + let contextId = contextEntity.id; + let contextType = contextEntity.type; if (!contextId) { contextId = device.id; } @@ -322,23 +320,23 @@ function handleQueryNgsiLD(req, res, next) { } deviceService.findConfigurationGroup(device, function(error, group) { - var executeCompleteAttributes = apply(completeAttributes, attributes, group), - executeQueryHandler = apply( - actualHandler, - contextId, - contextType, - contextServerUtils.getLDTenant(req), - contextServerUtils.getLDPath(req) - ), - executeAddStaticAttributes = apply(addStaticAttributes, attributes, group); + const executeCompleteAttributes = apply(completeAttributes, attributes, group); + const executeQueryHandler = apply( + actualHandler, + contextId, + contextType, + contextServerUtils.getLDTenant(req), + contextServerUtils.getLDPath(req) + ); + const executeAddStaticAttributes = apply(addStaticAttributes, attributes, group); async.waterfall([executeCompleteAttributes, executeQueryHandler, executeAddStaticAttributes], callback); }); } function createQueryRequest(attributes, contextEntity, callback) { - var actualHandler; - var getFunction; + let actualHandler; + let getFunction; if (contextServerUtils.queryHandler) { actualHandler = contextServerUtils.queryHandler; @@ -373,9 +371,8 @@ function handleQueryNgsiLD(req, res, next) { if (innerDevice.count) { if (innerDevice.count === 0) { return callback(null, []); - } else { - deviceList = innerDevice.devices; } + deviceList = innerDevice.devices; } else { deviceList = [innerDevice]; } @@ -409,19 +406,16 @@ function handleQueryNgsiLD(req, res, next) { logger.debug(context, 'Handling query from [%s]', req.get('host')); if (req.body) { - logger.debug(context, JSON.stringify(req.body , null, 4)); + logger.debug(context, JSON.stringify(req.body, null, 4)); } - - const nss = req.params.entity.replace('urn:ngsi-ld:', ''); + + const nss = req.params.entity.replace('urn:ngsi-ld:', ''); const contextEntity = { id: req.params.entity, type: nss.substring(0, nss.indexOf(':')) - }; - createQueryRequest( - req.query.attrs ? req.query.attrs.split(',') : null, - contextEntity, handleQueryContextRequests); + createQueryRequest(req.query.attrs ? req.query.attrs.split(',') : null, contextEntity, handleQueryContextRequests); } /** @@ -432,7 +426,7 @@ function handleQueryNgsiLD(req, res, next) { * @param {Object} res Response that will be sent. */ function queryErrorHandlingNgsiLD(error, req, res, next) { - var code = 500; + let code = 500; logger.debug(context, 'Query NGSI-LD error [%s] handling request: %s', error.name, error.message); @@ -455,11 +449,11 @@ function queryErrorHandlingNgsiLD(error, req, res, next) { function handleNotificationNgsiLD(req, res, next) { function extractInformation(dataElement, callback) { - var atts = []; - for (var key in dataElement) { + const atts = []; + for (const key in dataElement) { if (dataElement.hasOwnProperty(key)) { if (key !== 'id' && key !== 'type') { - var att = {}; + const att = {}; att.type = dataElement[key].type; att.value = dataElement[key].value; att.name = key; @@ -483,10 +477,10 @@ function handleNotificationNgsiLD(req, res, next) { function applyNotificationMiddlewares(device, values, callback) { if (contextServerUtils.notificationMiddlewares.length > 0) { - var firstMiddleware = contextServerUtils.notificationMiddlewares.slice(0, 1)[0], - rest = contextServerUtils.notificationMiddlewares.slice(1), - startMiddleware = apply(firstMiddleware, device, values), - composedMiddlewares = [startMiddleware].concat(rest); + const firstMiddleware = contextServerUtils.notificationMiddlewares.slice(0, 1)[0]; + const rest = contextServerUtils.notificationMiddlewares.slice(1); + const startMiddleware = apply(firstMiddleware, device, values); + const composedMiddlewares = [startMiddleware].concat(rest); async.waterfall(composedMiddlewares, callback); } else { @@ -518,7 +512,7 @@ function handleNotificationNgsiLD(req, res, next) { logger.debug(context, 'Handling notification from [%s]', req.get('host')); async.map(req.body.data, createNotificationHandler, handleNotificationRequests); } else { - var errorNotFound = new Error({ + const errorNotFound = new Error({ message: 'Notification handler not found' }); @@ -536,7 +530,7 @@ function handleNotificationNgsiLD(req, res, next) { * @param {Object} res Response that will be sent. */ function updateErrorHandlingNgsiLD(error, req, res, next) { - var code = 500; + let code = 500; logger.debug(context, 'Update NGSI-LD error [%s] handing request: %s', error.name, error.message); @@ -559,7 +553,7 @@ function loadContextRoutesNGSILD(router) { // In a more evolved implementation, more endpoints could be added to queryPathsNgsi2 // according to http://fiware.github.io/specifications/ngsiv2/stable. - var i; + let i; logger.info(context, 'Loading NGSI-LD Context server routes'); for (i = 0; i < updatePaths.length; i++) { diff --git a/lib/services/northBound/contextServer-NGSI-v1.js b/lib/services/northBound/contextServer-NGSI-v1.js index b13b0a98d..9bd55391e 100644 --- a/lib/services/northBound/contextServer-NGSI-v1.js +++ b/lib/services/northBound/contextServer-NGSI-v1.js @@ -23,22 +23,21 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation * Modified by: Jason Fox - FIWARE Foundation */ -'use strict'; - -var async = require('async'), - apply = async.apply, - logger = require('logops'), - errors = require('../../errors'), - deviceService = require('../devices/deviceService'), - middlewares = require('../common/genericMiddleware'), - _ = require('underscore'), - context = { - op: 'IoTAgentNGSI.ContextServer-v1' - }, - updateContextTemplateNgsi1 = require('../../templates/updateContextNgsi1.json'), - queryContextTemplate = require('../../templates/queryContext.json'), - notificationTemplateNgsi1 = require('../../templates/notificationTemplateNgsi1.json'), - contextServerUtils = require('./contextServerUtils'); + +const async = require('async'); +const apply = async.apply; +const logger = require('logops'); +const errors = require('../../errors'); +const deviceService = require('../devices/deviceService'); +const middlewares = require('../common/genericMiddleware'); +const _ = require('underscore'); +const context = { + op: 'IoTAgentNGSI.ContextServer-v1' +}; +const updateContextTemplateNgsi1 = require('../../templates/updateContextNgsi1.json'); +const queryContextTemplate = require('../../templates/queryContext.json'); +const notificationTemplateNgsi1 = require('../../templates/notificationTemplateNgsi1.json'); +const contextServerUtils = require('./contextServerUtils'); const updatePaths = ['/v1/updateContext', '/NGSI10/updateContext', '//updateContext']; const queryPaths = ['/v1/queryContext', '/NGSI10/queryContext', '//queryContext']; @@ -52,13 +51,13 @@ const queryPaths = ['/v1/queryContext', '/NGSI10/queryContext', '//queryContext' */ function generateUpdateActionsNgsi1(req, contextElement, callback) { function splitUpdates(device, callback) { - var attributes = [], - commands = [], - found; + let attributes = []; + const commands = []; + let found; if (device.commands) { - attributeLoop: for (var i in contextElement.attributes) { - for (var j in device.commands) { + attributeLoop: for (const i in contextElement.attributes) { + for (const j in device.commands) { if (contextElement.attributes[i].name === device.commands[j].name) { commands.push(contextElement.attributes[i]); found = true; @@ -76,7 +75,7 @@ function generateUpdateActionsNgsi1(req, contextElement, callback) { } function createActionsArray(attributes, commands, device, callback) { - var updateActions = []; + const updateActions = []; if (contextServerUtils.updateHandler) { updateActions.push( @@ -173,7 +172,7 @@ function handleUpdateNgsi1(req, res, next) { if (contextServerUtils.updateHandler || contextServerUtils.commandHandler) { logger.debug(context, 'Handling v1 update from [%s]', req.get('host')); if (req.body) { - logger.debug(context, JSON.stringify(req.body , null, 4)); + logger.debug(context, JSON.stringify(req.body, null, 4)); } async.waterfall( @@ -196,7 +195,7 @@ function handleUpdateNgsi1(req, res, next) { } else { logger.error(context, 'Tried to handle an update request before the update handler was stablished.'); - var errorNotFound = new Error({ + const errorNotFound = new Error({ message: 'Update handler not found' }); next(errorNotFound); @@ -214,10 +213,10 @@ function handleUpdateNgsi1(req, res, next) { * @param {Array} attributes List of attributes to read. */ function defaultQueryHandlerNgsi1(id, type, service, subservice, attributes, callback) { - var contextElement = { - type: type, + const contextElement = { + type, isPattern: false, - id: id, + id, attributes: [] }; @@ -225,10 +224,10 @@ function defaultQueryHandlerNgsi1(id, type, service, subservice, attributes, cal if (error) { callback(error); } else { - for (var i = 0; i < attributes.length; i++) { - var lazyAttribute = _.findWhere(ngsiDevice.lazy, { name: attributes[i] }), - command = _.findWhere(ngsiDevice.commands, { name: attributes[i] }), - attributeType; + for (let i = 0; i < attributes.length; i++) { + const lazyAttribute = _.findWhere(ngsiDevice.lazy, { name: attributes[i] }); + const command = _.findWhere(ngsiDevice.commands, { name: attributes[i] }); + var attributeType; if (command) { attributeType = command.type; @@ -266,7 +265,7 @@ function handleQueryNgsi1(req, res, next) { } if (device.staticAttributes) { - var selectedAttributes = device.staticAttributes.filter(inAttributes); + const selectedAttributes = device.staticAttributes.filter(inAttributes); if (selectedAttributes.length > 0) { if (contextElement.attributes) { @@ -294,7 +293,7 @@ function handleQueryNgsi1(req, res, next) { } function createQueryRequests(attributes, contextEntity, callback) { - var actualHandler; + let actualHandler; if (contextServerUtils.queryHandler) { actualHandler = contextServerUtils.queryHandler; @@ -313,15 +312,15 @@ function handleQueryNgsi1(req, res, next) { deviceService.findConfigurationGroup ], function handleFindDevice(error, device) { - var executeCompleteAttributes = apply(completeAttributes, attributes, device), - executeQueryHandler = apply( - actualHandler, - contextEntity.id, - contextEntity.type, - req.headers['fiware-service'], - req.headers['fiware-servicepath'] - ), - executeAddStaticAttributes = apply(addStaticAttributes, attributes, device); + const executeCompleteAttributes = apply(completeAttributes, attributes, device); + const executeQueryHandler = apply( + actualHandler, + contextEntity.id, + contextEntity.type, + req.headers['fiware-service'], + req.headers['fiware-servicepath'] + ); + const executeAddStaticAttributes = apply(addStaticAttributes, attributes, device); callback( error, @@ -343,7 +342,7 @@ function handleQueryNgsi1(req, res, next) { logger.debug(context, 'Handling query from [%s]', req.get('host')); if (req.body) { - logger.debug(context, JSON.stringify(req.body , null, 4)); + logger.debug(context, JSON.stringify(req.body, null, 4)); } async.waterfall( @@ -384,10 +383,10 @@ function handleNotificationNgsi1(req, res, next) { function applyNotificationMiddlewares(device, values, callback) { if (contextServerUtils.notificationMiddlewares.length > 0) { - var firstMiddleware = contextServerUtils.notificationMiddlewares.slice(0, 1)[0], - rest = contextServerUtils.notificationMiddlewares.slice(1), - startMiddleware = apply(firstMiddleware, device, values), - composedMiddlewares = [startMiddleware].concat(rest); + const firstMiddleware = contextServerUtils.notificationMiddlewares.slice(0, 1)[0]; + const rest = contextServerUtils.notificationMiddlewares.slice(1); + const startMiddleware = apply(firstMiddleware, device, values); + const composedMiddlewares = [startMiddleware].concat(rest); async.waterfall(composedMiddlewares, callback); } else { @@ -421,7 +420,7 @@ function handleNotificationNgsi1(req, res, next) { async.map(req.body.contextResponses, createNotificationHandler, handleNotificationRequests); } else { - var errorNotFound = new Error({ + const errorNotFound = new Error({ message: 'Notification handler not found' }); @@ -439,7 +438,7 @@ function handleNotificationNgsi1(req, res, next) { * @param {Object} res Response that will be sent. */ function queryErrorHandlingNgsi1(error, req, res, next) { - var code = 500; + let code = 500; logger.debug(context, 'Query NGSIv1 error [%s] handling request: %s', error.name, error.message); @@ -449,7 +448,7 @@ function queryErrorHandlingNgsi1(error, req, res, next) { res.status(code).json({ errorCode: { - code: code, + code, reasonPhrase: error.name, details: error.message.replace(/[<>\"\'=;\(\)]/g, '') } @@ -464,7 +463,7 @@ function queryErrorHandlingNgsi1(error, req, res, next) { * @param {Object} res Response that will be sent. */ function updateErrorHandlingNgsi1(error, req, res, next) { - var code = 500; + let code = 500; logger.debug(context, 'Update NGSIv1 error [%s] handing request: %s', error.name, error.message); @@ -477,7 +476,7 @@ function updateErrorHandlingNgsi1(error, req, res, next) { { contextElement: req.body, statusCode: { - code: code, + code, reasonPhrase: error.name, details: error.message.replace(/[<>\"\'=;\(\)]/g, '') } @@ -495,7 +494,7 @@ function loadContextRoutesNGSIv1(router) { // In a more evolved implementation, more endpoints could be added to queryPathsNgsi2 // according to http://fiware.github.io/specifications/ngsiv2/stable. - var i; + let i; logger.info(context, 'Loading NGSI-v1 Context server routes'); for (i = 0; i < updatePaths.length; i++) { router.post(updatePaths[i], [ diff --git a/lib/services/northBound/contextServer-NGSI-v2.js b/lib/services/northBound/contextServer-NGSI-v2.js index b9006fe46..f63bbd079 100644 --- a/lib/services/northBound/contextServer-NGSI-v2.js +++ b/lib/services/northBound/contextServer-NGSI-v2.js @@ -23,21 +23,20 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation * Modified by: Jason Fox - FIWARE Foundation */ -'use strict'; - -var async = require('async'), - apply = async.apply, - logger = require('logops'), - errors = require('../../errors'), - deviceService = require('../devices/deviceService'), - middlewares = require('../common/genericMiddleware'), - _ = require('underscore'), - context = { - op: 'IoTAgentNGSI.ContextServer-v2' - }, - updateContextTemplateNgsi2 = require('../../templates/updateContextNgsi2.json'), - notificationTemplateNgsi2 = require('../../templates/notificationTemplateNgsi2.json'), - contextServerUtils = require('./contextServerUtils'); + +const async = require('async'); +const apply = async.apply; +const logger = require('logops'); +const errors = require('../../errors'); +const deviceService = require('../devices/deviceService'); +const middlewares = require('../common/genericMiddleware'); +const _ = require('underscore'); +const context = { + op: 'IoTAgentNGSI.ContextServer-v2' +}; +const updateContextTemplateNgsi2 = require('../../templates/updateContextNgsi2.json'); +const notificationTemplateNgsi2 = require('../../templates/notificationTemplateNgsi2.json'); +const contextServerUtils = require('./contextServerUtils'); const updatePaths = ['/v2/op/update', '//op/update']; const queryPaths = ['/v2/op/query', '//op/query']; @@ -49,8 +48,8 @@ const queryPaths = ['/v2/op/query', '//op/query']; * @param {Object} contextElement Context Element whose actions will be extracted. */ function generateUpdateActionsNgsi2(req, contextElement, callback) { - var entityId; - var entityType; + let entityId; + let entityType; if (contextElement.id && contextElement.type) { entityId = contextElement.id; @@ -60,15 +59,15 @@ function generateUpdateActionsNgsi2(req, contextElement, callback) { } function splitUpdates(device, callback) { - var attributes = [], - commands = [], - found, - newAtt, - i; + const attributes = []; + const commands = []; + let found; + let newAtt; + let i; if (device.commands) { attributeLoop: for (i in contextElement) { - for (var j in device.commands) { + for (const j in device.commands) { if (i === device.commands[j].name) { newAtt = {}; newAtt[i] = contextElement[i]; @@ -94,7 +93,7 @@ function generateUpdateActionsNgsi2(req, contextElement, callback) { } function createActionsArray(attributes, commands, device, callback) { - var updateActions = []; + const updateActions = []; if (!entityType) { entityType = device.type; @@ -193,7 +192,7 @@ function handleUpdateNgsi2(req, res, next) { if (contextServerUtils.updateHandler || contextServerUtils.commandHandler) { logger.debug(context, 'Handling v2 update from [%s]', req.get('host')); if (req.body) { - logger.debug(context, JSON.stringify(req.body , null, 4)); + logger.debug(context, JSON.stringify(req.body, null, 4)); } async.waterfall( @@ -212,7 +211,7 @@ function handleUpdateNgsi2(req, res, next) { } else { logger.error(context, 'Tried to handle an update request before the update handler was stablished.'); - var errorNotFound = new Error({ + const errorNotFound = new Error({ message: 'Update handler not found' }); next(errorNotFound); @@ -230,19 +229,19 @@ function handleUpdateNgsi2(req, res, next) { * @param {Array} attributes List of attributes to read. */ function defaultQueryHandlerNgsi2(id, type, service, subservice, attributes, callback) { - var contextElement = { - type: type, - id: id + const contextElement = { + type, + id }; deviceService.getDeviceByName(id, service, subservice, function(error, ngsiDevice) { if (error) { callback(error); } else { - for (var i = 0; i < attributes.length; i++) { - var lazyAttribute = _.findWhere(ngsiDevice.lazy, { name: attributes[i] }), - command = _.findWhere(ngsiDevice.commands, { name: attributes[i] }), - attributeType; + for (let i = 0; i < attributes.length; i++) { + const lazyAttribute = _.findWhere(ngsiDevice.lazy, { name: attributes[i] }); + const command = _.findWhere(ngsiDevice.commands, { name: attributes[i] }); + var attributeType; if (command) { attributeType = command.type; @@ -271,11 +270,11 @@ function defaultQueryHandlerNgsi2(id, type, service, subservice, attributes, cal */ function handleNotificationNgsi2(req, res, next) { function extractInformation(dataElement, callback) { - var atts = []; - for (var key in dataElement) { + const atts = []; + for (const key in dataElement) { if (dataElement.hasOwnProperty(key)) { if (key !== 'id' && key !== 'type') { - var att = {}; + const att = {}; att.type = dataElement[key].type; att.value = dataElement[key].value; att.name = key; @@ -299,10 +298,10 @@ function handleNotificationNgsi2(req, res, next) { function applyNotificationMiddlewares(device, values, callback) { if (contextServerUtils.notificationMiddlewares.length > 0) { - var firstMiddleware = contextServerUtils.notificationMiddlewares.slice(0, 1)[0], - rest = contextServerUtils.notificationMiddlewares.slice(1), - startMiddleware = apply(firstMiddleware, device, values), - composedMiddlewares = [startMiddleware].concat(rest); + const firstMiddleware = contextServerUtils.notificationMiddlewares.slice(0, 1)[0]; + const rest = contextServerUtils.notificationMiddlewares.slice(1); + const startMiddleware = apply(firstMiddleware, device, values); + const composedMiddlewares = [startMiddleware].concat(rest); async.waterfall(composedMiddlewares, callback); } else { @@ -334,7 +333,7 @@ function handleNotificationNgsi2(req, res, next) { logger.debug(context, 'Handling notification from [%s]', req.get('host')); async.map(req.body.data, createNotificationHandler, handleNotificationRequests); } else { - var errorNotFound = new Error({ + const errorNotFound = new Error({ message: 'Notification handler not found' }); @@ -352,7 +351,7 @@ function handleNotificationNgsi2(req, res, next) { * @param {Object} res Response that will be sent. */ function queryErrorHandlingNgsi2(error, req, res, next) { - var code = 500; + let code = 500; logger.debug(context, 'Query NGSIv2 error [%s] handling request: %s', error.name, error.message); @@ -374,7 +373,7 @@ function queryErrorHandlingNgsi2(error, req, res, next) { * @param {Object} res Response that will be sent. */ function updateErrorHandlingNgsi2(error, req, res, next) { - var code = 500; + let code = 500; logger.debug(context, 'Update NGSIv2 error [%s] handing request: %s', error.name, error.message); @@ -402,14 +401,14 @@ function handleQueryNgsi2(req, res, next) { } if (device.staticAttributes) { - var selectedAttributes = []; + let selectedAttributes = []; if (attributes === undefined || attributes.length === 0) { selectedAttributes = device.staticAttributes; } else { selectedAttributes = device.staticAttributes.filter(inAttributes); } - for (var att in selectedAttributes) { + for (const att in selectedAttributes) { contextElement[selectedAttributes[att].name] = { type: selectedAttributes[att].type, value: selectedAttributes[att].value @@ -426,7 +425,7 @@ function handleQueryNgsi2(req, res, next) { callback(null, attributes); } else if (device.lazy) { logger.debug(context, 'Handling stored set of attributes: %j', attributes); - var results = device.lazy.map(getName); + const results = device.lazy.map(getName); callback(null, results); } else { logger.debug(context, 'Couldn\'t find any attributes. Handling with null reference'); @@ -435,8 +434,8 @@ function handleQueryNgsi2(req, res, next) { } function finishQueryForDevice(attributes, contextEntity, actualHandler, device, callback) { - var contextId = contextEntity.id; - var contextType = contextEntity.type; + let contextId = contextEntity.id; + let contextType = contextEntity.type; if (!contextId) { contextId = device.id; } @@ -446,23 +445,23 @@ function handleQueryNgsi2(req, res, next) { } deviceService.findConfigurationGroup(device, function(error, group) { - var executeCompleteAttributes = apply(completeAttributes, attributes, group), - executeQueryHandler = apply( - actualHandler, - contextId, - contextType, - req.headers['fiware-service'], - req.headers['fiware-servicepath'] - ), - executeAddStaticAttributes = apply(addStaticAttributes, attributes, group); + const executeCompleteAttributes = apply(completeAttributes, attributes, group); + const executeQueryHandler = apply( + actualHandler, + contextId, + contextType, + req.headers['fiware-service'], + req.headers['fiware-servicepath'] + ); + const executeAddStaticAttributes = apply(addStaticAttributes, attributes, group); async.waterfall([executeCompleteAttributes, executeQueryHandler, executeAddStaticAttributes], callback); }); } function createQueryRequest(attributes, contextEntity, callback) { - var actualHandler; - var getFunction; + let actualHandler; + let getFunction; if (contextServerUtils.queryHandler) { actualHandler = contextServerUtils.queryHandler; @@ -497,9 +496,8 @@ function handleQueryNgsi2(req, res, next) { if (innerDevice.count) { if (innerDevice.count === 0) { return callback(null, []); - } else { - deviceList = innerDevice.devices; } + deviceList = innerDevice.devices; } else { deviceList = [innerDevice]; } @@ -533,9 +531,9 @@ function handleQueryNgsi2(req, res, next) { logger.debug(context, 'Handling query from [%s]', req.get('host')); if (req.body) { - logger.debug(context, JSON.stringify(req.body , null, 4)); + logger.debug(context, JSON.stringify(req.body, null, 4)); } - var contextEntity = {}; + const contextEntity = {}; // At the present moment, IOTA supports query request with one entity and without patterns. This is aligned // with the utilization cases in combination with ContextBroker. Other cases are returned as error @@ -555,7 +553,7 @@ function handleQueryNgsi2(req, res, next) { contextEntity.id = req.body.entities[0].id; contextEntity.type = req.body.entities[0].type; - var queryAtts = req.body.attrs; + const queryAtts = req.body.attrs; createQueryRequest(queryAtts, contextEntity, handleQueryContextRequests); } @@ -568,7 +566,7 @@ function loadContextRoutesNGSIv2(router) { // In a more evolved implementation, more endpoints could be added to queryPathsNgsi2 // according to http://fiware.github.io/specifications/ngsiv2/stable. - var i; + let i; logger.info(context, 'Loading NGSI-v2 Context server routes'); for (i = 0; i < updatePaths.length; i++) { router.post(updatePaths[i], [ diff --git a/lib/services/northBound/contextServer.js b/lib/services/northBound/contextServer.js index 9a560c3d1..7dfc13303 100644 --- a/lib/services/northBound/contextServer.js +++ b/lib/services/northBound/contextServer.js @@ -23,16 +23,16 @@ * Modified by: Daniel Calvo - ATOS Research & Innovation * Modified by: Jason Fox - FIWARE Foundation */ -'use strict'; + +const intoTrans = require('../common/domain').intoTrans; +const config = require('../../commonConfig'); +const context = { + op: 'IoTAgentNGSI.ContextServer' +}; +const contextServerUtils = require('./contextServerUtils'); -var intoTrans = require('../common/domain').intoTrans, - config = require('../../commonConfig'), - context = { - op: 'IoTAgentNGSI.ContextServer' - }, - contextServerUtils = require('./contextServerUtils'); -var contextServerHandler; +let contextServerHandler; /** * Loads the correct context server handler based on the current config. diff --git a/lib/services/northBound/contextServerUtils.js b/lib/services/northBound/contextServerUtils.js index d711cd7ce..2ca3ef933 100644 --- a/lib/services/northBound/contextServerUtils.js +++ b/lib/services/northBound/contextServerUtils.js @@ -24,17 +24,16 @@ * Modified by: Jason Fox - FIWARE Foundation */ - var async = require('async'), - apply = async.apply, - logger = require('logops'), - constants = require('../../constants'), - config = require('../../commonConfig'), - ngsi = require('../ngsi/ngsiService'), - commands = require('../commands/commandService'), - context = { - op: 'IoTAgentNGSI.ContextServerUtils' - }; - +const async = require('async'); +const apply = async.apply; +const logger = require('logops'); +const constants = require('../../constants'); +const config = require('../../commonConfig'); +const ngsi = require('../ngsi/ngsiService'); +const commands = require('../commands/commandService'); +const context = { + op: 'IoTAgentNGSI.ContextServerUtils' +}; /** * Returns the Current Tenant defined for the NGSI-LD Broker. Tenant is based on the request @@ -45,14 +44,13 @@ * @param {Object} req Request that was handled in first place. * @return {String} The Tenant decribed in the request headers */ -function getLDTenant(req){ - if (req.headers['NGSILD-Tenant']){ +function getLDTenant(req) { + if (req.headers['NGSILD-Tenant']) { return req.headers['NGSILD-Tenant']; - } else if (req.headers['fiware-service']){ + } else if (req.headers['fiware-service']) { return req.headers['fiware-service']; - } else { - return config.getConfig().contextBroker.fallbackTenant; } + return config.getConfig().contextBroker.fallbackTenant; } /** @@ -62,16 +60,14 @@ function getLDTenant(req){ * obliged to offer service headers - this is still being defined in the NGSI-LD specifications. */ function getLDPath(req) { - if (req.headers['NGSILD-Path']){ + if (req.headers['NGSILD-Path']) { return req.headers['NGSILD-Path']; - } else if (req.headers['fiware-servicepath']){ + } else if (req.headers['fiware-servicepath']) { return req.headers['fiware-servicepath']; - } else { - return config.getConfig().contextBroker.fallbackPath; } + return config.getConfig().contextBroker.fallbackPath; } - /** * Create the response for an UpdateContext operation, based on the results of the individual updates. The signature * retains the results object for homogeinity with the createQuery* version. @@ -82,12 +78,12 @@ function getLDPath(req) { * @return {{contextResponses: Array}} */ function createUpdateResponse(req, res, results) { - var result = { + const result = { contextResponses: [] }; - for (var i = 0; i < req.body.contextElements.length; i++) { - var contextResponse = { + for (let i = 0; i < req.body.contextElements.length; i++) { + const contextResponse = { contextElement: { attributes: req.body.contextElements[i].attributes, id: req.body.contextElements[i].id, @@ -100,7 +96,7 @@ function createUpdateResponse(req, res, results) { } }; - for (var j = 0; j < contextResponse.contextElement.attributes.length; j++) { + for (let j = 0; j < contextResponse.contextElement.attributes.length; j++) { contextResponse.contextElement.attributes[i].value = ''; } @@ -122,12 +118,12 @@ function createUpdateResponse(req, res, results) { * @return {{contextResponses: Array}} */ function createQueryResponse(req, res, results) { - var result = { + const result = { contextResponses: [] }; - for (var i = 0; i < results.length; i++) { - var contextResponse = { + for (let i = 0; i < results.length; i++) { + const contextResponse = { contextElement: results[i], statusCode: { code: 200, @@ -157,13 +153,13 @@ function createQueryResponse(req, res, results) { * @param {Array} attributes List of attributes to update with their types and values. */ function executeUpdateSideEffects(device, id, type, service, subservice, attributes, callback) { - var sideEffects = []; + const sideEffects = []; if (device.commands) { - for (var i = 0; i < device.commands.length; i++) { - for (var j = 0; j < attributes.length; j++) { + for (let i = 0; i < device.commands.length; i++) { + for (let j = 0; j < attributes.length; j++) { if (device.commands[i].name === attributes[j].name) { - var newAttributes = [ + const newAttributes = [ { name: device.commands[i].name + '_status', type: constants.COMMAND_STATUS, diff --git a/lib/services/northBound/northboundServer.js b/lib/services/northBound/northboundServer.js index 2a80aea59..858f3e3bb 100644 --- a/lib/services/northBound/northboundServer.js +++ b/lib/services/northBound/northboundServer.js @@ -20,28 +20,27 @@ * For those usages not covered by the GNU Affero General Public License * please contact with::daniel.moranjimenez@telefonica.com */ -'use strict'; - -var http = require('http'), - async = require('async'), - express = require('express'), - packageInformation = require('../../../package.json'), - northboundServer, - contextServer = require('./contextServer'), - domainUtils = require('../common/domain'), - middlewares = require('../common/genericMiddleware'), - intoTrans = domainUtils.intoTrans, - deviceProvisioning = require('./deviceProvisioningServer'), - groupProvisioning = require('./deviceGroupAdministrationServer'), - logger = require('logops'), - context = { - op: 'IoTAgentNGSI.NorthboundServer' - }, - bodyParser = require('body-parser'); + +const http = require('http'); +const async = require('async'); +const express = require('express'); +const packageInformation = require('../../../package.json'); +let northboundServer; +const contextServer = require('./contextServer'); +const domainUtils = require('../common/domain'); +const middlewares = require('../common/genericMiddleware'); +const intoTrans = domainUtils.intoTrans; +const deviceProvisioning = require('./deviceProvisioningServer'); +const groupProvisioning = require('./deviceGroupAdministrationServer'); +const logger = require('logops'); +const context = { + op: 'IoTAgentNGSI.NorthboundServer' +}; +const bodyParser = require('body-parser'); function start(config, callback) { - var baseRoot = '/', - iotaInformation; + let baseRoot = '/'; + let iotaInformation; northboundServer = { server: null, @@ -69,7 +68,7 @@ function start(config, callback) { iotaInformation = { libVersion: packageInformation.version, port: config.server.port, - baseRoot: baseRoot + baseRoot }; if (config.iotaVersion) { @@ -106,11 +105,7 @@ function stop(callback) { } function clear(callback) { - async.series([ - deviceProvisioning.clear, - groupProvisioning.clear, - contextServer.clear - ], callback); + async.series([deviceProvisioning.clear, groupProvisioning.clear, contextServer.clear], callback); } exports.setUpdateHandler = intoTrans(context, contextServer.setUpdateHandler); @@ -118,7 +113,7 @@ exports.setQueryHandler = intoTrans(context, contextServer.setQueryHandler); exports.setCommandHandler = intoTrans(context, contextServer.setCommandHandler); exports.setNotificationHandler = intoTrans(context, contextServer.setNotificationHandler); exports.setConfigurationHandler = intoTrans(context, groupProvisioning.setConfigurationHandler); -exports.setRemoveConfigurationHandler = intoTrans (context, groupProvisioning.setRemoveConfigurationHandler); +exports.setRemoveConfigurationHandler = intoTrans(context, groupProvisioning.setRemoveConfigurationHandler); exports.setProvisioningHandler = intoTrans(context, deviceProvisioning.setProvisioningHandler); exports.setRemoveDeviceHandler = intoTrans(context, deviceProvisioning.setRemoveDeviceHandler); exports.addDeviceProvisionMiddleware = deviceProvisioning.addDeviceProvisionMiddleware; diff --git a/lib/services/northBound/restUtils.js b/lib/services/northBound/restUtils.js index 376292c25..86d4e19be 100644 --- a/lib/services/northBound/restUtils.js +++ b/lib/services/northBound/restUtils.js @@ -22,25 +22,23 @@ * * Modified by: Daniel Calvo - ATOS Research & Innovation */ -'use strict'; - -var logger = require('logops'), - errors = require('../../errors'), - constants = require('../../constants'), - intoTrans = require('../common/domain').intoTrans, - revalidator = require('revalidator'), - moment = require('moment'), - context = { - op: 'IoTAgentNGSI.RestUtils' - }, - _ = require('underscore'), - request = require('request'), - async = require('async'), - apply = async.apply, - constants = require('../../constants'), - ngsiService = require('../ngsi/ngsiService'), - config = require('../../commonConfig'); +const logger = require('logops'); +const errors = require('../../errors'); +var constants = require('../../constants'); +const intoTrans = require('../common/domain').intoTrans; +const revalidator = require('revalidator'); +const moment = require('moment'); +const context = { + op: 'IoTAgentNGSI.RestUtils' +}; +const _ = require('underscore'); +const request = require('request'); +const async = require('async'); +const apply = async.apply; +var constants = require('../../constants'); +const ngsiService = require('../ngsi/ngsiService'); +const config = require('../../commonConfig'); /** * Checks all the mandatory attributes in the selected array are present in the presented body object. @@ -49,12 +47,12 @@ var logger = require('logops'), * @param {Object} body Body whose attributes are going to be checked. */ function checkMandatoryQueryParams(mandatoryAttributes, body, callback) { - var missing = []; + const missing = []; - for (var p in mandatoryAttributes) { - var found = false; + for (const p in mandatoryAttributes) { + let found = false; - for (var i in body) { + for (const i in body) { if (body.hasOwnProperty(i)) { if (i === mandatoryAttributes[p]) { found = true; @@ -68,7 +66,7 @@ function checkMandatoryQueryParams(mandatoryAttributes, body, callback) { } if (missing.length !== 0) { - var error = new errors.MissingAttributes('Missing attributes: ' + JSON.stringify(missing)); + const error = new errors.MissingAttributes('Missing attributes: ' + JSON.stringify(missing)); error.code = '400'; callback(error); @@ -88,10 +86,10 @@ function checkMandatoryQueryParams(mandatoryAttributes, body, callback) { */ function checkRequestAttributes(attribute, mandatoryAttributes) { return function headerChecker(req, res, next) { - var headerKeys = _.keys(req[attribute]), - missing = []; + const headerKeys = _.keys(req[attribute]); + const missing = []; - for (var i = 0; i < mandatoryAttributes.length; i++) { + for (let i = 0; i < mandatoryAttributes.length; i++) { if (headerKeys.indexOf(mandatoryAttributes[i]) < 0) { missing.push(mandatoryAttributes[i]); } @@ -113,7 +111,7 @@ function checkRequestAttributes(attribute, mandatoryAttributes) { */ function checkBody(template) { return function bodyMiddleware(req, res, next) { - var errorList = revalidator.validate(req.body, template); + const errorList = revalidator.validate(req.body, template); if (errorList.valid) { next(); @@ -131,9 +129,11 @@ function checkBody(template) { * @return {Boolean} true if timestamp attributes are valid ISO8601. false if not. */ function IsValidTimestamped(payload) { - for (var i in payload.contextElements[0].attributes) { - if (payload.contextElements[0].attributes[i].name === constants.TIMESTAMP_ATTRIBUTE && - ! moment(payload.contextElements[0].attributes[i].value, moment.ISO_8601).isValid()) { + for (const i in payload.contextElements[0].attributes) { + if ( + payload.contextElements[0].attributes[i].name === constants.TIMESTAMP_ATTRIBUTE && + !moment(payload.contextElements[0].attributes[i].value, moment.ISO_8601).isValid() + ) { return false; } } @@ -149,10 +149,9 @@ function IsValidTimestamped(payload) { */ function IsValidTimestampedNgsi2(payload) { function isValidTimestampedNgsi2Entity(entity) { - for (var i in entity) { + for (const i in entity) { if (entity.hasOwnProperty(i)) { - if (i === constants.TIMESTAMP_ATTRIBUTE && - ! moment(entity[i].value, moment.ISO_8601).isValid()) { + if (i === constants.TIMESTAMP_ATTRIBUTE && !moment(entity[i].value, moment.ISO_8601).isValid()) { return false; } } @@ -162,16 +161,15 @@ function IsValidTimestampedNgsi2(payload) { } if (payload instanceof Array) { - for (var i = 0; i < payload.length; i++) { + for (let i = 0; i < payload.length; i++) { if (!isValidTimestampedNgsi2Entity(payload[i])) { return false; } } return true; - } else { - return isValidTimestampedNgsi2Entity(payload); } + return isValidTimestampedNgsi2Entity(payload); } /** @@ -181,7 +179,7 @@ function IsValidTimestampedNgsi2(payload) { * @return {Boolean} true if timestamp attributes are included. false if not. */ function isTimestamped(payload) { - for (var i in payload.contextElements[0].attributes) { + for (const i in payload.contextElements[0].attributes) { if (payload.contextElements[0].attributes[i].name === constants.TIMESTAMP_ATTRIBUTE) { return true; } @@ -197,9 +195,8 @@ function isTimestamped(payload) { * @return {Boolean} true if timestamp attributes are included. false if not. */ function isTimestampedNgsi2(payload) { - function isTimestampedNgsi2Entity(entity) { - for (var i in entity) { + for (const i in entity) { if (entity.hasOwnProperty(i)) { if (i === constants.TIMESTAMP_ATTRIBUTE) { return true; @@ -211,19 +208,17 @@ function isTimestampedNgsi2(payload) { } if (payload instanceof Array) { - for (var i = 0; i < payload.length; i++) { + for (let i = 0; i < payload.length; i++) { if (!isTimestampedNgsi2Entity(payload[i])) { return false; } } return true; - } else { - return isTimestampedNgsi2Entity(payload); } + return isTimestampedNgsi2Entity(payload); } - /** * Executes a request operation using security information if available * @@ -231,50 +226,48 @@ function isTimestampedNgsi2(payload) { * @param {String} deviceData Device data. */ function executeWithSecurity(requestOptions, deviceData, callback) { - logger.debug(context, 'executeWithSecurity'); - config.getGroupRegistry().getType(deviceData.type, function(error, deviceGroup) { - var typeInformation; - if (error) { - logger.debug(context, 'error %j in get group device', error); - } + logger.debug(context, 'executeWithSecurity'); + config.getGroupRegistry().getType(deviceData.type, function(error, deviceGroup) { + let typeInformation; + if (error) { + logger.debug(context, 'error %j in get group device', error); + } - if (deviceGroup) { - typeInformation = deviceGroup; - } else { - typeInformation = config.getConfig().types[deviceData.type]; - } + if (deviceGroup) { + typeInformation = deviceGroup; + } else { + typeInformation = config.getConfig().types[deviceData.type]; + } - if (config.getConfig().authentication && config.getConfig().authentication.enabled) { - var security = config.getSecurityService(); - if (typeInformation && typeInformation.trust) { - async.waterfall([ + if (config.getConfig().authentication && config.getConfig().authentication.enabled) { + const security = config.getSecurityService(); + if (typeInformation && typeInformation.trust) { + async.waterfall( + [ apply(security.auth, typeInformation.trust), apply(ngsiService.updateTrust, deviceGroup, null, typeInformation.trust), apply(security.getToken, typeInformation.trust) - ], function(error, token) { + ], + function(error, token) { if (error) { callback(new errors.SecurityInformationMissing(typeInformation.type)); - } - else { - - //console.error(JSON.stringify(requestOptions, null, 4)); - + } else { requestOptions.headers[config.getConfig().authentication.header] = token; request(requestOptions, callback); } - }); - } else { - callback(new errors.SecurityInformationMissing( - typeInformation ? typeInformation.type : deviceData.type)); - } + } + ); } else { - request(requestOptions, callback); + callback( + new errors.SecurityInformationMissing(typeInformation ? typeInformation.type : deviceData.type) + ); } - }); + } else { + request(requestOptions, callback); + } + }); } - - exports.executeWithSecurity = executeWithSecurity; exports.checkMandatoryQueryParams = intoTrans(context, checkMandatoryQueryParams); exports.checkRequestAttributes = intoTrans(context, checkRequestAttributes); diff --git a/test/tools/utils.js b/test/tools/utils.js index db6c74ac5..bb4b8dfba 100644 --- a/test/tools/utils.js +++ b/test/tools/utils.js @@ -27,8 +27,6 @@ var fs = require('fs'); function readExampleFile(name, raw) { - - let text = null; try { text = fs.readFileSync(name, 'UTF8'); @@ -37,11 +35,6 @@ function readExampleFile(name, raw) { console.error(JSON.stringify(e)); } - //if(!raw){ - // console.error(name); - // console.error(JSON.stringify(JSON.parse(text), null, 4)); - //} - return raw ? text : JSON.parse(text); }