diff --git a/lib/database/sthDatabase.js b/lib/database/sthDatabase.js index 196835bb..18db19de 100644 --- a/lib/database/sthDatabase.js +++ b/lib/database/sthDatabase.js @@ -31,7 +31,7 @@ const sthConfig = require(ROOT_PATH + '/lib/configuration/sthConfiguration.js'); const sthUtils = require(ROOT_PATH + '/lib/utils/sthUtils.js'); const sthDatabaseNaming = require(ROOT_PATH + '/lib/database/model/sthDatabaseNaming'); const mongoClient = require('mongodb').MongoClient; -const boom = require('boom'); +const boom = require('@hapi/boom'); const jsoncsv = require('json-csv'); const fs = require('fs'); const path = require('path'); diff --git a/lib/server/handlers/sthGetDataHandler.js b/lib/server/handlers/sthGetDataHandler.js index 7b331d39..99e258f0 100644 --- a/lib/server/handlers/sthGetDataHandler.js +++ b/lib/server/handlers/sthGetDataHandler.js @@ -28,7 +28,7 @@ const sthLogger = require('logops'); const sthConfig = require(ROOT_PATH + '/lib/configuration/sthConfiguration'); const sthServerUtils = require(ROOT_PATH + '/lib/server/utils/sthServerUtils'); const sthDatabase = require(ROOT_PATH + '/lib/database/sthDatabase'); -const boom = require('boom'); +const boom = require('@hapi/boom'); const stream = require('stream'); const fs = require('fs'); const path = require('path'); @@ -39,7 +39,7 @@ const encodeRFC5987 = require('rfc5987-value-chars').encode; * @param {Object} request The request * @param {Function} reply Hapi's reply function */ -function getRawData(request, reply) { +function getRawData(request, reply, replyHandler) { let response; var query = { @@ -70,8 +70,16 @@ function getRawData(request, reply) { ); sthLogger.debug(request.sth.context, 'Responding with 500- Internal error'); const error = boom.internal(message); - error.output.payload.message = message; - reply(error); + //error.output.payload.message = message; + if (reply) { + //response = reply.response({error:error.output.peyload}).type('application/json').code(500); + response = reply + .response(error) + .type('application/json') + .code(500); + } else { + response = replyHandler(error); + } } else { // The collection does not exist, reply with en empty response sthLogger.warn( @@ -90,7 +98,11 @@ function getRawData(request, reply) { request.params.attrName, emptyResponse ); - response = reply(ngsiPayload); + if (reply) { + response = reply.response(ngsiPayload); + } else { + response = replyHandler(ngsiPayload); + } sthServerUtils.addFiwareCorrelator(request, response); if (request.query.count) { sthServerUtils.addFiwareTotalCount(0, response); @@ -116,7 +128,14 @@ function getRawData(request, reply) { // Error when getting the raw data sthLogger.error(request.sth.context, 'Error %j when getting raw data with query %j', err, rawQuery); sthLogger.debug(request.sth.context, 'Responding with 500 - Internal Error'); - response = reply(err); + if (reply) { + response = reply + .response(err) + .type('application/json') + .code(500); + } else { + response = replyHandler(err); + } } else if (!result || !(result.length || result instanceof stream)) { // No raw data available for the request sthLogger.info( @@ -127,22 +146,42 @@ function getRawData(request, reply) { ); sthLogger.debug(request.sth.context, 'Responding with no points'); - response = reply( - sthServerUtils.getNGSIPayload( - request.params.version, - request.params.entityId, - request.params.entityType, - request.params.attrName, - sthServerUtils.getEmptyResponse() - ) - ); + if (reply) { + response = reply.response( + sthServerUtils.getNGSIPayload( + request.params.version, + request.params.entityId, + request.params.entityType, + request.params.attrName, + sthServerUtils.getEmptyResponse() + ) + ); + } else { + response = replyHandler( + sthServerUtils.getNGSIPayload( + request.params.version, + request.params.entityId, + request.params.entityType, + request.params.attrName, + sthServerUtils.getEmptyResponse() + ) + ); + } } else if (result instanceof stream) { sthLogger.debug(request.sth.context, 'Responding with a stream of docs'); - response = reply(new stream.Readable().wrap(result)); + if (reply) { + response = reply.response(new stream.Readable().wrap(result)); + } else { + response = replyHandler(new stream.Readable().wrap(result)); + } } else if (typeof result === 'string') { sthLogger.debug(request.sth.context, "Responding with file '" + result + "'"); fs.readFile(result, function(err, data) { - response = reply(data); + if (reply) { + response = reply.response(data); + } else { + response = replyHandler(data); + } const fileName = result.substring(result.lastIndexOf(path.sep) + 1); response.header( 'Content-Disposition', @@ -164,24 +203,39 @@ function getRawData(request, reply) { }); // readfile } else { sthLogger.debug(request.sth.context, 'Responding with %s docs', result.length); - response = reply( - sthServerUtils.getNGSIPayload( - request.params.version, - request.params.entityId, - request.params.entityType, - request.params.attrName, - result - ) - ); + if (reply) { + response = reply.response( + sthServerUtils.getNGSIPayload( + request.params.version, + request.params.entityId, + request.params.entityType, + request.params.attrName, + result + ) + ); + } else { + response = replyHandler( + sthServerUtils.getNGSIPayload( + request.params.version, + request.params.entityId, + request.params.entityType, + request.params.attrName, + result + ) + ); + } } sthServerUtils.addFiwareCorrelator(request, response); if (request.query.count) { sthLogger.debug(request.sth.context, 'totalCount %j', totalCount); sthServerUtils.addFiwareTotalCount(totalCount, response); } + return response; }); } + return response; }); + return response; } /** @@ -189,7 +243,7 @@ function getRawData(request, reply) { * @param {Object} request The request * @param {Function} reply Hapi's reply function */ -function getAggregatedData(request, reply) { +function getAggregatedData(request, reply, replyHandler) { let response; var query = { @@ -220,8 +274,16 @@ function getAggregatedData(request, reply) { ); sthLogger.debug(request.sth.context, 'Responding with 500- Internal error'); const error = boom.internal(message); - error.output.payload.message = message; - reply(error); + //error.output.payload.message = message; + if (reply) { + response = reply + .response({ error: error.output.peyload }) + .type('application/json') + .code(500); + //response = reply.response(error); + } else { + response = replyHandler(error); + } } else { // The collection does not exist, reply with en empty response sthLogger.warn( @@ -243,7 +305,11 @@ function getAggregatedData(request, reply) { request.params.attrName, emptyResponse ); - response = reply(ngsiPayload); + if (reply) { + response = reply.response(ngsiPayload); + } else { + response = replyHandler(ngsiPayload); + } sthServerUtils.addFiwareCorrelator(request, response); } } else { @@ -274,7 +340,14 @@ function getAggregatedData(request, reply) { aggregatedQuery ); sthLogger.debug(request.sth.context, 'Responding with 500 - Internal Error'); - response = reply(err); + if (reply) { + response = reply + .response(err) + .type('application/json') + .code(500); + } else { + response = replyHandler(err); + } } else if (!result || !result.length) { // No aggregated data available for the request sthLogger.debug( @@ -285,31 +358,58 @@ function getAggregatedData(request, reply) { ); sthLogger.debug(request.sth.context, 'Responding with no points'); - response = reply( - sthServerUtils.getNGSIPayload( - request.params.version, - request.params.entityId, - request.params.entityType, - request.params.attrName, - sthServerUtils.getEmptyResponse() - ) - ); + if (reply) { + response = reply.response( + sthServerUtils.getNGSIPayload( + request.params.version, + request.params.entityId, + request.params.entityType, + request.params.attrName, + sthServerUtils.getEmptyResponse() + ) + ); + } else { + response = replyHandler( + sthServerUtils.getNGSIPayload( + request.params.version, + request.params.entityId, + request.params.entityType, + request.params.attrName, + sthServerUtils.getEmptyResponse() + ) + ); + } } else { sthLogger.debug(request.sth.context, 'Responding with %s docs', result.length); - response = reply( - sthServerUtils.getNGSIPayload( - request.params.version, - request.params.entityId, - request.params.entityType, - request.params.attrName, - result - ) - ); + if (reply) { + response = reply.response( + sthServerUtils.getNGSIPayload( + request.params.version, + request.params.entityId, + request.params.entityType, + request.params.attrName, + result + ) + ); + } else { + response = replyHandler( + sthServerUtils.getNGSIPayload( + request.params.version, + request.params.entityId, + request.params.entityType, + request.params.attrName, + result + ) + ); + } } sthServerUtils.addFiwareCorrelator(request, response); + return response; }); } + return response; }); + return response; } /** @@ -317,7 +417,7 @@ function getAggregatedData(request, reply) { * @param {Object} request The request * @param {Function} reply The reply() function of the hapi server */ -function getDataHandler(request, reply) { +function getDataHandler(request, reply, replyHandler) { request.sth = request.sth || {}; request.sth.context = sthServerUtils.getContext(request); let message; @@ -345,17 +445,25 @@ function getDataHandler(request, reply) { request.method.toUpperCase() + ' ' + request.url.path + ', error=' + message ); error = boom.badRequest(message); - error.output.payload.validation = { - source: 'query', - keys: ['lastN', 'hLimit', 'hOffset', 'filetype', 'aggrMethod', 'aggrPeriod', 'count'] - }; - return reply(error); + // error.output.payload.validation = { + // source: 'query', + // keys: ['lastN', 'hLimit', 'hOffset', 'filetype', 'aggrMethod', 'aggrPeriod', 'count'] + // }; + if (reply) { + return reply + .response({ error: error.output.peyload }) + .type('application/json') + .code(400); + //return reply.response(error); + } else { + return replyHandler(error); + } } } - getRawData(request, reply); + return getRawData(request, reply, replyHandler); } else if (request.query.aggrMethod && request.query.aggrPeriod) { // Aggregated data is requested - getAggregatedData(request, reply); + return getAggregatedData(request, reply, replyHandler); } else { message = 'A combination of the following query params is required: lastN, hLimit and hOffset, ' + @@ -365,12 +473,21 @@ function getDataHandler(request, reply) { request.method.toUpperCase() + ' ' + request.url.path + ', error=' + message ); error = boom.badRequest(message); - error.output.payload.validation = { - source: 'query', - keys: ['lastN', 'hLimit', 'hOffset', 'filetype', 'aggrMethod', 'aggrPeriod', 'count'] - }; - return reply(error); + // error.output.payload.validation = { + // source: 'query', + // keys: ['lastN', 'hLimit', 'hOffset', 'filetype', 'aggrMethod', 'aggrPeriod', 'count'] + // }; + if (reply) { + //return reply.response(error); + return reply + .response({ error: error.output.peyload }) + .type('application/json') + .code(400); + } else { + return replyHandler(error); + } } + return null; } module.exports = getDataHandler; diff --git a/lib/server/handlers/sthGetDataHandlerV2.js b/lib/server/handlers/sthGetDataHandlerV2.js index 0a5dbcaa..dbc5d420 100644 --- a/lib/server/handlers/sthGetDataHandlerV2.js +++ b/lib/server/handlers/sthGetDataHandlerV2.js @@ -42,18 +42,20 @@ function getDataHandler(request, reply) { */ function replyHandler(payload) { if (payload.isBoom) { - return reply({ - error: payload.output.payload.error.replace(/ /, ''), - description: payload.output.payload.message - }).code(payload.output.payload.statusCode); + return reply + .response({ + error: payload.output.payload.error.replace(/ /, ''), + description: payload.output.payload.message + }) + .code(payload.output.payload.statusCode); } - return reply(payload); + return reply.response(payload); } request.params.entityType = request.query.type; request.params.version = 2; - sthGetDataHandlerV1(request, replyHandler); + return sthGetDataHandlerV1(request, null, replyHandler); } module.exports = getDataHandler; diff --git a/lib/server/handlers/sthGetLogLevelHandler.js b/lib/server/handlers/sthGetLogLevelHandler.js index d9b70348..fe09c651 100644 --- a/lib/server/handlers/sthGetLogLevelHandler.js +++ b/lib/server/handlers/sthGetLogLevelHandler.js @@ -53,8 +53,9 @@ function getLogLevelHandler(request, reply) { sthLogger.info(request.sth.context, 'Responding with logging level: ' + level); - const response = reply(getLogLevelResponse(level)); + const response = reply.response(getLogLevelResponse(level)); sthServerUtils.addFiwareCorrelator(request, response); + return response; } module.exports = getLogLevelHandler; diff --git a/lib/server/handlers/sthGetVersionHandler.js b/lib/server/handlers/sthGetVersionHandler.js index 4d0036cd..64c2766f 100644 --- a/lib/server/handlers/sthGetVersionHandler.js +++ b/lib/server/handlers/sthGetVersionHandler.js @@ -31,7 +31,7 @@ const sthUtils = require(ROOT_PATH + '/lib/utils/sthUtils'); */ function getVersionHandler(request, reply) { const message = sthUtils.getVersion(); - return reply(message); + return reply.response(message); } module.exports = getVersionHandler; diff --git a/lib/server/handlers/sthNotFoundHandler.js b/lib/server/handlers/sthNotFoundHandler.js index e342ea9c..70c46353 100644 --- a/lib/server/handlers/sthNotFoundHandler.js +++ b/lib/server/handlers/sthNotFoundHandler.js @@ -41,11 +41,12 @@ function notFoundHandler(request, reply) { '404 - Not Found route for the request: ' + request.method.toUpperCase() + ' ' + request.url.path ); if (request.path.startsWith('/STH/v2')) { - response = reply({ error: 'NotFound', description: 'invalid path' }).code(404); + response = reply.response({ error: 'NotFound', description: 'invalid path' }).code(404); } else { - response = reply({ statusCode: 404, error: 'Not Found' }).code(404); + response = reply.response({ statusCode: 404, error: 'Not Found' }).code(404); } sthServerUtils.addFiwareCorrelator(request, response); + return response; } module.exports = notFoundHandler; diff --git a/lib/server/handlers/sthNotificationHandler.js b/lib/server/handlers/sthNotificationHandler.js index d671f290..40c4eb65 100644 --- a/lib/server/handlers/sthNotificationHandler.js +++ b/lib/server/handlers/sthNotificationHandler.js @@ -28,7 +28,7 @@ const sthLogger = require('logops'); const sthConfig = require(ROOT_PATH + '/lib/configuration/sthConfiguration'); const sthServerUtils = require(ROOT_PATH + '/lib/server/utils/sthServerUtils'); const sthDatabase = require(ROOT_PATH + '/lib/database/sthDatabase'); -const boom = require('boom'); +const boom = require('@hapi/boom'); /** * Returns the total number of attributes to be processed @@ -163,7 +163,7 @@ function storeRawData(data, reply, callback) { // There was an error when getting the collection sthLogger.error(request.sth.context, 'Error when getting the raw data collection for storing:' + err); if (++counterObj.counter === totalTasks) { - response = reply(err); + response = reply.response(err); sthServerUtils.addFiwareCorrelator(request, response); } process.nextTick(callback.bind(null, err)); @@ -195,7 +195,7 @@ function storeRawData(data, reply, callback) { sthLogger.debug(request.sth.context, 'Raw data successfully stored'); } if (++counterObj.counter === totalTasks) { - response = reply(err); + response = reply.response(err); sthServerUtils.addFiwareCorrelator(request, response); } process.nextTick(callback.bind(null, err)); @@ -255,7 +255,7 @@ function storeAggregatedData(data, reply) { // There was an error when getting the collection sthLogger.error(request.sth.context, 'Error when getting the aggregated data collection for storing'); if (++counterObj.counter === totalTasks) { - response = reply(err); + response = reply.response(err); sthServerUtils.addFiwareCorrelator(request, response); } } else { @@ -282,7 +282,7 @@ function storeAggregatedData(data, reply) { sthLogger.debug(request.sth.context, 'Aggregated data successfully stored'); } if (++counterObj.counter === totalTasks) { - response = reply(err); + response = reply.response(err); sthServerUtils.addFiwareCorrelator(request, response); } } @@ -334,13 +334,13 @@ function processAttribute(data, reply) { err = null; } if (++data.counterObj.counter === data.totalTasks) { - reply(err); + reply.response(err); } } else if (isAggregatableValue) { // Store the aggregated data into the database storeAggregatedData(data, reply); } else if (++data.counterObj.counter === data.totalTasks) { - reply(); + reply.response(); } }); } else { @@ -390,7 +390,7 @@ function processNotification(recvTime, request, reply) { ); const error = boom.badRequest(message); error.output.payload.validation = { source: 'payload', keys: ['attributes'] }; - return reply(error); + return reply.response(error); } for (let i = 0; i < contextResponses.length; i++) { diff --git a/lib/server/handlers/sthRemoveDataHandler.js b/lib/server/handlers/sthRemoveDataHandler.js index f1256d30..6352f15b 100644 --- a/lib/server/handlers/sthRemoveDataHandler.js +++ b/lib/server/handlers/sthRemoveDataHandler.js @@ -26,7 +26,7 @@ const sthLogger = require('logops'); const sthConfig = require(ROOT_PATH + '/lib/configuration/sthConfiguration'); const sthServerUtils = require(ROOT_PATH + '/lib/server/utils/sthServerUtils'); const sthDatabase = require(ROOT_PATH + '/lib/database/sthDatabase'); -const boom = require('boom'); +const boom = require('@hapi/boom'); /** * Returns a textual description of the received request and the data included in it @@ -74,7 +74,7 @@ function removeDataHandler(request, reply) { sthLogger.debug(request.sth.context, 'Responding with 500- Internal error'); const error = boom.internal(message); error.output.payload.message = message; - reply(error); + reply.response(error); } else if ( err.name === 'MongoError' && err.message.includes('does not exist. Currently in strict mode') @@ -85,19 +85,19 @@ function removeDataHandler(request, reply) { 'No data associated to the provided ' + getRequestDescription(request) + ' available' ); // Reply with no error - response = reply(); + response = reply.response(); response.code(204); } else { sthLogger.warn(request.sth.context, 'Error when removing the data associated to an entity: ' + err); // Reply with error - response = reply(err); + response = reply.response(err); } } else { sthLogger.debug( request.sth.context, 'Data associated to the provided ' + getRequestDescription(request) + ' successfully removed' ); - response = reply(); + response = reply.response(); response.code(204); } sthServerUtils.addFiwareCorrelator(request, response); diff --git a/lib/server/handlers/sthSetLogLevelHandler.js b/lib/server/handlers/sthSetLogLevelHandler.js index 794989b7..9624246c 100644 --- a/lib/server/handlers/sthSetLogLevelHandler.js +++ b/lib/server/handlers/sthSetLogLevelHandler.js @@ -41,8 +41,9 @@ function setLogLevelHandler(request, reply) { sthLogger.info(request.sth.context, 'Log level set to: ' + level); - const response = reply(); + const response = reply.response(); sthServerUtils.addFiwareCorrelator(request, response); + return response; } module.exports = setLogLevelHandler; diff --git a/lib/server/sthServer.js b/lib/server/sthServer.js index 27152a0d..ab3a4575 100644 --- a/lib/server/sthServer.js +++ b/lib/server/sthServer.js @@ -26,7 +26,7 @@ const ROOT_PATH = require('app-root-path'); const sthLogger = require('logops'); const sthConfig = require(ROOT_PATH + '/lib/configuration/sthConfiguration'); -const sthServerUtils = require(ROOT_PATH + '/lib/server/utils/sthServerUtils'); +// const sthServerUtils = require(ROOT_PATH + '/lib/server/utils/sthServerUtils'); const sthHeaderValidator = require(ROOT_PATH + '/lib/server/validators/sthHeaderValidator'); const sthGetDataHandler = require(ROOT_PATH + '/lib/server/handlers/sthGetDataHandler'); const sthGetDataHandlerV2 = require(ROOT_PATH + '/lib/server/handlers/sthGetDataHandlerV2'); @@ -36,7 +36,7 @@ const sthRemoveDataHandler = require(ROOT_PATH + '/lib/server/handlers/sthRemove const sthGetLogLevelHandler = require(ROOT_PATH + '/lib/server/handlers/sthGetLogLevelHandler'); const sthSetLogLevelHandler = require(ROOT_PATH + '/lib/server/handlers/sthSetLogLevelHandler'); const sthNotFoundHandler = require(ROOT_PATH + '/lib/server/handlers/sthNotFoundHandler'); -const hapi = require('hapi'); +const hapi = require('@hapi/hapi'); const joi = require('joi'); let server; @@ -57,16 +57,21 @@ function doStartServer(host, port, callback) { * @param ngsiVersion NGSI version to use. Anything different from 2 (included undefined) means v1 */ function getNgsiHandlerConfig(ngsiVersion) { - function failActionHandler(request, reply, source, error) { + function failActionHandler(request, reply, error) { + sthLogger.debug('failActionHandler %j', error); // In the case of NGSIv2, this function adapts from the error response format used // by hapi to the one used in NGSIv2 - reply({ error: 'BadRequest', description: error.output.payload.message }).code(400); + const response = reply + .response({ error: 'BadRequest', description: error.output.payload.message }) + .code(400) + .takeover(); + return response; } - const config = { + const options = { validate: { - headers: sthHeaderValidator, - query: { + //headers: sthHeaderValidator, + query: joi.object({ // prettier-ignore lastN: joi.number().integer().greater(-1).optional(), // prettier-ignore @@ -83,52 +88,24 @@ function doStartServer(host, port, callback) { dateTo: joi.date().optional(), filetype: joi.string().optional(), count: joi.boolean().optional() - } + }) } }; if (ngsiVersion === 2) { - config.validate.failAction = failActionHandler; + options.validate.failAction = failActionHandler; // In NGSIv2 type query param is mandatory - config.validate.query.type = joi.string().required(); + options.validate.query.type = joi.string().required(); } - return config; + return options; } - - server = new hapi.Server(); - - server.on('log', function(event, tags) { - if (tags.load) { - sthLogger.warn(sthConfig.LOGGING_CONTEXT.SERVER_LOG, 'event=' + JSON.stringify(event)); - } - }); - - server.on('request-internal', function(request, event, tags) { - if (tags.error) { - processedRequestsWithError++; - if (tags.auth || tags.handler || tags.state || tags.payload || tags.validation) { - sthLogger.warn( - sthServerUtils.getContext(request), - request.method.toUpperCase() + ' ' + request.url.path + ', event=' + JSON.stringify(event) - ); - } else { - sthLogger.error( - sthServerUtils.getContext(request), - request.method.toUpperCase() + ' ' + request.url.path + ', event=' + JSON.stringify(event) - ); - } - } else if (tags.error === undefined && request._isReplied) { - attendedRequests++; - } - }); - if (sthConfig.corsEnabled) { sthLogger.info('CORS is enabled'); - server.connection({ - host, - port, + server = new hapi.Server({ + host: host, + port: port, routes: { cors: { origin: sthConfig.corsOptions.origin, @@ -140,24 +117,49 @@ function doStartServer(host, port, callback) { }); } else { sthLogger.info('CORS is disabled'); - server.connection({ - host, - port + server = new hapi.Server({ + host: host, + port: port }); } + server.events.on('log', function(event, tags) { + if (tags.load) { + sthLogger.warn(sthConfig.LOGGING_CONTEXT.SERVER_LOG, 'event=' + JSON.stringify(event)); + } + }); + + // server.events.on('request-internal', function(request, event, tags) { + // if (tags.error) { + // processedRequestsWithError++; + // if (tags.auth || tags.handler || tags.state || tags.payload || tags.validation) { + // sthLogger.warn( + // sthServerUtils.getContext(request), + // request.method.toUpperCase() + ' ' + request.url.path + ', event=' + JSON.stringify(event) + // ); + // } else { + // sthLogger.error( + // sthServerUtils.getContext(request), + // request.method.toUpperCase() + ' ' + request.url.path + ', event=' + JSON.stringify(event) + // ); + // } + // } else if (tags.error === undefined && request._isReplied) { + // attendedRequests++; + // } + // }); + server.route([ { method: 'GET', path: '/STH/v1/contextEntities/type/{entityType}/id/{entityId}/attributes/{attrName}', handler: sthGetDataHandler, - config: getNgsiHandlerConfig(1) + options: getNgsiHandlerConfig(1) }, { method: 'GET', path: '/STH/v2/entities/{entityId}/attrs/{attrName}', handler: sthGetDataHandlerV2, - config: getNgsiHandlerConfig(2) + options: getNgsiHandlerConfig(2) }, { method: 'GET', @@ -168,9 +170,9 @@ function doStartServer(host, port, callback) { method: 'POST', path: '/notify', handler: sthNotificationHandler, - config: { + options: { validate: { - headers: sthHeaderValidator + headers: sthHeaderValidator // TBD } } }, @@ -178,9 +180,9 @@ function doStartServer(host, port, callback) { method: 'DELETE', path: '/STH/v1/contextEntities', handler: sthRemoveDataHandler, - config: { + options: { validate: { - headers: sthHeaderValidator + headers: sthHeaderValidator // TBD } } }, @@ -188,9 +190,9 @@ function doStartServer(host, port, callback) { method: 'DELETE', path: '/STH/v1/contextEntities/type/{entityType}/id/{entityId}', handler: sthRemoveDataHandler, - config: { + options: { validate: { - headers: sthHeaderValidator + headers: sthHeaderValidator // TBD } } }, @@ -198,9 +200,9 @@ function doStartServer(host, port, callback) { method: 'DELETE', path: '/STH/v1/contextEntities/type/{entityType}/id/{entityId}/attributes/{attrName}', handler: sthRemoveDataHandler, - config: { + options: { validate: { - headers: sthHeaderValidator + headers: sthHeaderValidator // TBD } } }, @@ -208,12 +210,12 @@ function doStartServer(host, port, callback) { method: 'PUT', path: '/admin/log', handler: sthSetLogLevelHandler, - config: { + options: { validate: { - query: { + query: joi.object({ // prettier-ignore level: joi.string().insensitive().valid('FATAL', 'ERROR', 'WARNING', 'INFO', 'DEBUG').required() - } + }) } } }, @@ -224,15 +226,21 @@ function doStartServer(host, port, callback) { }, { method: '*', - path: '/{p*}', + path: '/{any*}', handler: sthNotFoundHandler } ]); - // Start the server - server.start(function(err) { - return callback(err, server); - }); + server + .start() + .then(() => { + sthLogger.info('Server running on %s', server.info.uri); + return callback(null, server); + }) // if needed + .catch((err) => { + sthLogger.error('Server error %s', err); + return callback(err, null); + }); } /** @@ -257,11 +265,18 @@ function startServer(host, port, callback) { function stopServer(callback) { sthLogger.info(sthConfig.LOGGING_CONTEXT.SERVER_STOP, 'Stopping the STH server...'); if (server && server.info && server.info.started) { - server.stop(function(err) { - // Server successfully stopped - sthLogger.info(sthConfig.LOGGING_CONTEXT.SERVER_STOP, 'hapi server successfully stopped'); - return callback(err); - }); + // or use a promise + server + .stop() + .then(() => { + // Server successfully stopped + sthLogger.info(sthConfig.LOGGING_CONTEXT.SERVER_STOP, 'hapi server successfully stopped'); + return callback(null); + }) // if needed + .catch((err) => { + sthLogger.error(sthConfig.LOGGING_CONTEXT.SERVER_STOP, 'hapi server error stopped %s', err); + return callback(err); + }); } else { sthLogger.info(sthConfig.LOGGING_CONTEXT.SERVER_STOP, 'No hapi server running'); return process.nextTick(callback); diff --git a/lib/server/validators/sthHeaderValidator.js b/lib/server/validators/sthHeaderValidator.js index d875bb5d..445d76cf 100644 --- a/lib/server/validators/sthHeaderValidator.js +++ b/lib/server/validators/sthHeaderValidator.js @@ -24,7 +24,7 @@ const ROOT_PATH = require('app-root-path'); const sthLogger = require('logops'); const sthConfig = require(ROOT_PATH + '/lib/configuration/sthConfiguration'); -const boom = require('boom'); +const boom = require('@hapi/boom'); /** * Header validation handler diff --git a/package.json b/package.json index 1d29296f..e972905d 100644 --- a/package.json +++ b/package.json @@ -50,7 +50,7 @@ "proxyquire": "1.7.10", "remark-cli": "~8.0.1", "remark-preset-lint-recommended": "~4.0.1", - "request": "2.88.0", + "request": "2.88.2", "textlint": "~11.7.6", "textlint-filter-rule-comments": "~1.2.2", "textlint-rule-common-misspellings": "~1.0.1", @@ -59,13 +59,13 @@ "watch": "~1.0.2" }, "dependencies": { + "@hapi/hapi": "21.3.2", "app-root-path": "~1.2.1", "async": "~2.0.0-rc.5", - "boom": "7.2.2", + "@hapi/boom": "10.0.1", "bytes-counter": "~1.0.0", "commander": "~2.9.0", "csv-parser": "~1.9.3", - "hapi": "16.7.0", "joi": "14.0.6", "json-csv": "1.5.0", "lodash": "~4.17.5", diff --git a/test/unit/sthGetLogLevelHandler_test.js b/test/unit/sthGetLogLevelHandler_test.js index d3b58651..02334e2c 100644 --- a/test/unit/sthGetLogLevelHandler_test.js +++ b/test/unit/sthGetLogLevelHandler_test.js @@ -27,7 +27,6 @@ const sthConfig = require(ROOT_PATH + '/lib/configuration/sthConfiguration'); const sthDatabaseNaming = require(ROOT_PATH + '/lib/database/model/sthDatabaseNaming'); const sthTestConfig = require(ROOT_PATH + '/test/unit/sthTestConfiguration'); const sthTestHelper = require(ROOT_PATH + '/test/unit/sthTestUtils.js'); -const hapi = require('hapi'); const expect = require('expect.js'); const request = require('request'); @@ -58,8 +57,8 @@ describe('sthGetLogLevelHandler tests', function() { describe('server start', function() { it('should start gracefully', function(done) { sth.sthServer.startServer(sthConfig.STH_HOST, sthConfig.STH_PORT, function(err, server) { - expect(err).to.equal(undefined); - expect(server).to.be.a(hapi.Server); + expect(err).to.equal(null); + expect(server).to.not.equal(null); done(); }); }); diff --git a/test/unit/sth_test.js b/test/unit/sth_test.js index 37295394..92dc0cef 100644 --- a/test/unit/sth_test.js +++ b/test/unit/sth_test.js @@ -27,7 +27,6 @@ const sthTestConfig = require(ROOT_PATH + '/test/unit/sthTestConfiguration'); const sthConfig = require(ROOT_PATH + '/lib/configuration/sthConfiguration'); const sthTestUtils = require(ROOT_PATH + '/test/unit/sthTestUtils.js'); const sthDatabaseNaming = require(ROOT_PATH + '/lib/database/model/sthDatabaseNaming'); -const hapi = require('hapi'); const request = require('request'); const expect = require('expect.js'); @@ -62,7 +61,7 @@ describe('sth tests', function() { it('should start gracefully', function(done) { sth.sthServer.startServer(sthConfig.STH_HOST, sthConfig.STH_PORT, function(err, server) { expect(err).to.equal(null); - expect(server).to.be.a(hapi.Server); + expect(server).to.not.equal(null); done(); }); });