From 74014bf796474e47340d8b1c53c6b802450b479b Mon Sep 17 00:00:00 2001 From: Stefan Genov Date: Sat, 22 Jan 2022 17:55:40 +0200 Subject: [PATCH 1/2] [develop] Housekeeping progress --- UPDATELOG.md | 5 + package.json | 2 +- server/components/big_map/big_map.js | 43 ++-- .../body_parsers/form_body_parser.js | 18 +- .../body_parsers/json_body_parser.js | 18 +- .../body_parsers/multipart_data_parser.js | 70 +++--- .../body_parsers/raw_body_parser.js | 16 +- .../components/cache-control/cache_control.js | 72 +++--- server/components/caching/data_server.js | 218 +++++++++--------- server/components/caching/data_server_map.js | 124 ++++++---- server/components/error/error_handler.js | 62 ++--- .../file_streams/abstract_file_stream.js | 10 +- .../file_streams/audio_file_stream.js | 10 +- .../file_streams/file_stream_handler.js | 8 +- .../file_streams/image_file_stream.js | 28 +-- .../file_streams/text_file_stream.js | 36 +-- .../file_streams/video_file_stream.js | 8 +- server/components/helpers/unique_id.js | 7 +- server/components/logger/components/log.js | 42 ++-- server/components/logger/components/logger.js | 56 ++--- .../components/transport_types/console.js | 14 +- .../logger/components/transport_types/file.js | 24 +- .../transport_types/formatters/colorize.js | 4 +- .../formatters/json_formatter.js | 6 +- .../formatters/plain_formatter.js | 6 +- .../processors/color_processor.js | 6 +- .../processors/new_line_processor.js | 5 +- .../processors/stack_processor.js | 4 +- .../processors/timestamp_processor.js | 26 +-- .../components/transport_types/transport.js | 33 ++- server/components/logger/loggur.js | 28 +-- server/components/mime_type/mime_type.js | 15 +- .../components/mime_type/mime_types_data.js | 6 +- server/components/rate_limiter/bucket.js | 86 +++---- server/components/routing/route.js | 29 ++- server/components/routing/router.js | 56 ++--- server/components/routing/router_cache.js | 26 +-- .../security/content_security_policy.js | 102 +++----- .../security/content_type_options.js | 14 +- server/components/security/expect_ct.js | 28 +-- .../http_strict_transport_security.js | 28 +-- server/components/session/session.js | 60 +++-- .../default_templating_engine.js | 10 +- .../experimental_templating_engine.js | 12 +- .../validation/validation_attribute.js | 8 +- .../validation/validation_handler.js | 4 +- .../validation/validation_result.js | 16 +- .../components/validation/validation_rules.js | 80 +++---- server/event_request.js | 44 ++-- .../available_plugins/body_parser_plugin.js | 8 +- .../available_plugins/cache_control_plugin.js | 2 +- .../plugins/available_plugins/cors_plugin.js | 8 +- .../available_plugins/data_server_plugin.js | 2 +- .../plugins/available_plugins/env_plugin.js | 2 +- .../plugins/available_plugins/etag_plugin.js | 26 +-- .../file_stream_handler_plugin.js | 12 +- .../available_plugins/logger_plugin.js | 4 +- .../available_plugins/rate_limits_plugin.js | 22 +- .../response_cache_plugin.js | 6 +- .../available_plugins/session_plugin.js | 2 +- .../static_resources_plugin.js | 8 +- .../templating_engine_plugin.js | 8 +- .../available_plugins/timeout_plugin.js | 4 +- .../available_plugins/validation_plugin.js | 10 +- server/plugins/plugin_interface.js | 8 +- server/plugins/plugin_manager.js | 10 +- server/server.js | 10 +- server/tester/mock.js | 6 +- server/tester/mocker.js | 4 +- server/tester/tester.js | 18 +- .../multipart_data_parser_test.js | 2 +- .../file_streams/image_file_stream_test.js | 14 +- .../file_streams/text_file_stream_test.js | 14 +- .../components/helpers/unique_id_test.js | 10 +- .../processors/timestamp_processor_test.js | 2 +- tests/server/components/logger/loggur_test.js | 4 +- .../components/mime_type/mime_type_test.js | 6 +- tests/server/components/routing/route_test.js | 8 +- tests/test_bootstrap.js | 4 +- tests/test_helper.js | 20 +- 80 files changed, 898 insertions(+), 999 deletions(-) diff --git a/UPDATELOG.md b/UPDATELOG.md index 741a0b37..83431772 100644 --- a/UPDATELOG.md +++ b/UPDATELOG.md @@ -1,3 +1,8 @@ +34.0.0 +* Housekeeping, more work done on JSDoc +* Improvements to file streams. Implemented MimeTypes in image file stream +* Changed the default makeId length to 32 + 33.5.0 * Housekeeping, work done on JSDoc diff --git a/package.json b/package.json index ebf5fc03..307d3cfe 100644 --- a/package.json +++ b/package.json @@ -61,7 +61,7 @@ "test": "nyc --reporter=lcov --reporter=text-summary node --unhandled-rejections=strict test.js --debug", "deploy": "npm run test && npm publish" }, - "version": "33.5.0", + "version": "34.0.0", "devDependencies": { "nyc": "^15.1.0" } diff --git a/server/components/big_map/big_map.js b/server/components/big_map/big_map.js index 961bb98c..79996377 100644 --- a/server/components/big_map/big_map.js +++ b/server/components/big_map/big_map.js @@ -8,15 +8,15 @@ class BigMap { } /** - * @brief Sets the value for the given key + * @brief Sets the value for the given key * - * @details This function will create a new Map as is needed - * A new map will be created every 8,000,000 keys + * @details This function will create a new Map as is needed + * A new map will be created every 8,000,000 keys * - * @property {*} key - the key to set - * @property {*} value - the value to set + * @param {*} key - the key to set + * @param {*} value - the value to set * - * @return * + * @return * */ set( key, value ) { let mapToSet = null; @@ -37,11 +37,11 @@ class BigMap { } /** - * @brief Gets a value given a key + * @brief Gets a value given a key * - * @property {*} key - the key to get + * @param {*} key - the key to get * - * @return {*} - element that was set + * @return {*} - element that was set */ get( key ) { const map = this._findMapWithKey( key ); @@ -53,13 +53,13 @@ class BigMap { } /** - * @brief Deletes a value given a key + * @brief Deletes a value given a key * - * @details This will remove the Map if it becomes empty when the key is deleted + * @details This will remove the Map if it becomes empty when the key is deleted * - * @property {*} key - the key of the value to delete + * @param {*} key - the key of the value to delete * - * @return * - The value that was deleted + * @return * - The value that was deleted */ delete( key ) { const map = this._findMapWithKey( key ); @@ -76,11 +76,11 @@ class BigMap { } /** - * @brief Checks if a key exists + * @brief Checks if a key exists * - * @property {*} key - the key to check if exists + * @param {*} key - the key to check if exists * - * @return {Boolean} - a flag whether the key exists + * @return {Boolean} - a flag whether the key exists */ has( key ) { return typeof this._findMapWithKey( key ) !== 'undefined'; @@ -114,8 +114,8 @@ class BigMap { } /** - * @property {Function} callbackFn - function that will be called - * @property {*} thisArg - this argument to bind to + * @param {Function} callbackFn - function that will be called + * @param {*} thisArg - this argument to bind to */ forEach ( callbackFn, thisArg ) { if ( thisArg ) @@ -193,13 +193,12 @@ class BigMap { } /** - * @brief Finds which map exactly has the given key and returns it - * - * @property {*} key + * @brief Finds which map exactly has the given key and returns it * * @private + * @param {*} key * - * @return {Map} + * @return {Map} */ _findMapWithKey( key ) { for ( let index = this.maps.length - 1; index >= 0; index-- ) { diff --git a/server/components/body_parsers/form_body_parser.js b/server/components/body_parsers/form_body_parser.js index 288c8033..2fd145a1 100644 --- a/server/components/body_parsers/form_body_parser.js +++ b/server/components/body_parsers/form_body_parser.js @@ -15,9 +15,9 @@ const CONTENT_TYPE_HEADER = 'content-type'; */ class FormBodyParser extends EventEmitter { /** - * @property {Object} options - * @property {Number} options.maxPayloadLength - The max size of the body to be parsed - * @property {Boolean} options.strict - Whether the received payload must match the content-length + * @param {Object} options + * @param {Number} options.maxPayloadLength - The max size of the body to be parsed + * @param {Boolean} options.strict - Whether the received payload must match the content-length */ constructor( options = {} ) { super(); @@ -34,11 +34,11 @@ class FormBodyParser extends EventEmitter { } /** - * @brief Returns true if the current body parser supports teh given request + * @brief Returns true if the current body parser supports teh given request * - * @property {EventRequest} event - The current EventRequest + * @param {EventRequest} event - The current EventRequest * - * @return {Boolean} - Returns Boolean if the `content-type` is supported + * @return {Boolean} - Returns Boolean if the `content-type` is supported */ supports( event ) { const contentType = event.getRequestHeader( CONTENT_TYPE_HEADER ); @@ -46,12 +46,12 @@ class FormBodyParser extends EventEmitter { } /** - * @brief Parses the request + * @brief Parses the request * * @async - * @property {EventRequest} event + * @param {EventRequest} event * - * @return {Promise} + * @return {Promise} */ parse( event ) { return new Promise(( resolve, reject ) => { diff --git a/server/components/body_parsers/json_body_parser.js b/server/components/body_parsers/json_body_parser.js index 4f731adb..cc924195 100644 --- a/server/components/body_parsers/json_body_parser.js +++ b/server/components/body_parsers/json_body_parser.js @@ -15,9 +15,9 @@ const CONTENT_TYPE_HEADER = 'content-type'; */ class JsonBodyParser extends EventEmitter { /** - * @property {Object} [options={}] - * @property {Number} options.maxPayloadLength - The max size of the body to be parsed - * @property {Boolean} options.strict - Whether the received payload must match the content-length + * @param {Object} [options={}] + * @param {Number} options.maxPayloadLength - The max size of the body to be parsed + * @param {Boolean} options.strict - Whether the received payload must match the content-length */ constructor( options = {} ) { super(); @@ -34,11 +34,11 @@ class JsonBodyParser extends EventEmitter { } /** - * @brief Returns a boolean if the current body parser supports the request + * @brief Returns a boolean if the current body parser supports the request * - * @property {EventRequest} event + * @param {EventRequest} event * - * @return {Boolean} + * @return {Boolean} */ supports( event ) { const contentType = event.getRequestHeader( CONTENT_TYPE_HEADER ); @@ -46,12 +46,12 @@ class JsonBodyParser extends EventEmitter { } /** - * @brief Parses the request + * @brief Parses the request * * @async - * @property {EventRequest} event + * @param {EventRequest} event * - * @return {Promise} + * @return {Promise} */ parse( event ) { return new Promise(( resolve, reject ) => { diff --git a/server/components/body_parsers/multipart_data_parser.js b/server/components/body_parsers/multipart_data_parser.js index b0adba74..99571368 100644 --- a/server/components/body_parsers/multipart_data_parser.js +++ b/server/components/body_parsers/multipart_data_parser.js @@ -46,10 +46,10 @@ const ERROR_INVALID_METADATA = 'app.er.bodyParser.multipart.invalidMetadata' */ class MultipartDataParser extends EventEmitter { /** - * @property {Object} [options={}] - * @property {Number} options.maxPayload - Maximum payload in bytes to parse if set to 0 means infinite - * @property {String} options.tempDir - The directory where to keep the uploaded files before moving - * @property {String} options.cleanUpItemsTimeoutMS - After what time should the files be deleted if any. Defaults to 100 + * @param {Object} [options={}] + * @param {Number} options.maxPayload - Maximum payload in bytes to parse if set to 0 means infinite + * @param {String} options.tempDir - The directory where to keep the uploaded files before moving + * @param {String} options.cleanUpItemsTimeoutMS - After what time should the files be deleted if any. Defaults to 100 */ constructor( options = {} ) { super(); @@ -112,9 +112,9 @@ class MultipartDataParser extends EventEmitter { } /** - * @brief Upgrades the given data part and adds it DATA_TYPE_FILE properties + * @brief Upgrades the given data part and adds it DATA_TYPE_FILE properties * - * @property {Object} part + * @param {Object} part */ upgradeToFileTypePart( part ) { part.file = null; @@ -123,9 +123,9 @@ class MultipartDataParser extends EventEmitter { } /** - * @brief Upgrades the given data part and adds it DATA_TYPE_PARAMETER properties + * @brief Upgrades the given data part and adds it DATA_TYPE_PARAMETER properties * - * @property {Object} part + * @param {Object} part */ upgradeToParameterTypePart( part ) { part.type = DATA_TYPE_PARAMETER; @@ -172,9 +172,9 @@ class MultipartDataParser extends EventEmitter { } /** - * @brief Determines the OS line end and sets it for future use + * @brief Determines the OS line end and sets it for future use * - * @property {Buffer} chunk + * @param {Buffer} chunk */ determineEOL( chunk ) { const data = chunk.toString( DEFAULT_BUFFER_ENCODING ); @@ -189,9 +189,9 @@ class MultipartDataParser extends EventEmitter { } /** - * @brief Callback called when data is received by the server + * @brief Callback called when data is received by the server * - * @property {Buffer} chunk + * @param {Buffer} chunk */ onDataReceivedCallback( chunk ) { try { @@ -203,10 +203,10 @@ class MultipartDataParser extends EventEmitter { } /** - * @brief Flushes the given buffer to the part.file stream + * @brief Flushes the given buffer to the part.file stream * - * @property {Object} part - * @property {Buffer} buffer + * @param {Object} part + * @param {Buffer} buffer */ flushBuffer( part, buffer ) { if ( part.type === DATA_TYPE_PARAMETER ) @@ -220,9 +220,9 @@ class MultipartDataParser extends EventEmitter { } /** - * @brief Extracts chunk data as they come in + * @brief Extracts chunk data as they come in * - * @property {Buffer} chunk + * @param {Buffer} chunk */ extractChunkData( chunk ) { let boundaryOffset = 0; @@ -390,20 +390,20 @@ class MultipartDataParser extends EventEmitter { } /** - * @brief Emits an event with an error + * @brief Emits an event with an error * - * @property {String} message - The message to throw + * @param {String} message - The message to throw */ handleError( message ) { throw new Error( message ); } /** - * @brief Return if the current body type is supported by the current body parser + * @brief Return if the current body type is supported by the current body parser * - * @property {EventRequest} event + * @param {EventRequest} event * - * @return {Boolean} + * @return {Boolean} */ supports( event ) { const contentType = event.getRequestHeader( CONTENT_TYPE_HEADER ); @@ -411,13 +411,13 @@ class MultipartDataParser extends EventEmitter { } /** - * @brief Get header data from event + * @brief Get header data from event * - * @details Will return false on error + * @details Will return false on error * - * @property {Object} headers - The headers object to extract the needed headers from + * @param {Object} headers - The headers object to extract the needed headers from * - * @return {Object|Boolean} + * @return {Object|Boolean} */ static getHeaderData( headers ) { const contentType = typeof headers[CONTENT_TYPE_HEADER] === 'string' @@ -443,12 +443,12 @@ class MultipartDataParser extends EventEmitter { } /** - * @brief Parses the body + * @brief Parses the body * * @async - * @property {EventRequest} event + * @param {EventRequest} event * - * @return {Promise} + * @return {Promise} */ parse( event ) { return new Promise(( resolve, reject ) => { @@ -488,11 +488,11 @@ class MultipartDataParser extends EventEmitter { } /** - * @brief Integrity check the event header data and payload length + * @brief Integrity check the event header data and payload length * - * @brief Returns an error and header data in the callback + * @brief Returns an error and header data in the callback * - * @property {Function} callback + * @param {Function} callback */ integrityCheck( callback ) { let headerData = MultipartDataParser.getHeaderData( this.event.headers ); @@ -528,12 +528,12 @@ class MultipartDataParser extends EventEmitter { } /** - * @brief Extracted for testing purposes + * @brief Extracted for testing purposes * * @private - * @details I can't simulate an error when unlinking so this test is ignored for now + * @details I can't simulate an error when unlinking so this test is ignored for now * - * @property {String} absFilePath - path of the file to remove + * @param {String} absFilePath - path of the file to remove */ _removeFile( absFilePath ) { /* istanbul ignore next */ diff --git a/server/components/body_parsers/raw_body_parser.js b/server/components/body_parsers/raw_body_parser.js index e83c2598..ccb8b581 100644 --- a/server/components/body_parsers/raw_body_parser.js +++ b/server/components/body_parsers/raw_body_parser.js @@ -8,8 +8,8 @@ const { EventEmitter } = require( 'events' ); */ class RawBodyParser extends EventEmitter { /** - * @property {Object} [options={}] - * @property {Number} options.maxPayloadLength - The max size of the body to be parsed + * @param {Object} [options={}] + * @param {Number} options.maxPayloadLength - The max size of the body to be parsed */ constructor( options = {} ) { super(); @@ -22,22 +22,22 @@ class RawBodyParser extends EventEmitter { } /** - * @brief Returns a boolean if the current body parser supports the request + * @brief Returns a boolean if the current body parser supports the request * - * @property {EventRequest} event + * @param {EventRequest} event * - * @return {Boolean} + * @return {Boolean} */ supports( event ) { return true; } /** - * @brief Parses the request + * @brief Parses the request * - * @property {EventRequest} event + * @param {EventRequest} event * - * @return {Promise} + * @return {Promise} */ parse( event ) { return new Promise(( resolve ) => { diff --git a/server/components/cache-control/cache_control.js b/server/components/cache-control/cache_control.js index d58643b9..3496a665 100644 --- a/server/components/cache-control/cache_control.js +++ b/server/components/cache-control/cache_control.js @@ -14,15 +14,15 @@ class CacheControl { } /** - * @brief Parses the options passed and sets the correct attributes + * @brief Parses the options passed and sets the correct attributes * * @private - * @property {Object} [options={}] - * @property {Boolean} options.static - flag should set a bunch of rules meant for static resources - * @property {Boolean} options.cacheControl - flag should set cache control - * @property {Boolean} options.revalidation - flag should set revalidation directive - * @property {Boolean} options.other - flag should set other directive - * @property {Boolean} options.expirationDirectives - CacheControl.addExpirationDirective + * @param {Object} [options={}] + * @param {Boolean} options.static - flag should set a bunch of rules meant for static resources + * @param {Boolean} options.cacheControl - flag should set cache control + * @param {Boolean} options.revalidation - flag should set revalidation directive + * @param {Boolean} options.other - flag should set other directive + * @param {Boolean} options.expirationDirectives - CacheControl.addExpirationDirective */ _configure( options = {} ) { if ( options.static === true ) @@ -54,11 +54,11 @@ class CacheControl { } /** - * @brief Sets the Cache Control directive + * @brief Sets the Cache Control directive * - * @details This function checks from an array of possible values and if nothing matches, does not set anything. + * @details This function checks from an array of possible values and if nothing matches, does not set anything. * - * @property {String} directive + * @param {String} directive */ setCacheControl( directive ) { if ( AVAILABLE_CACHE_CONTROL.indexOf( directive ) === -1 ) @@ -68,13 +68,13 @@ class CacheControl { } /** - * @brief Adds an expiration directive + * @brief Adds an expiration directive * - * @details This function checks from an array of possible values and if nothing matches, does not set anything. - * This function will check if time is a Number and if it is not it will not set anything + * @details This function checks from an array of possible values and if nothing matches, does not set anything. + * This function will check if time is a Number and if it is not it will not set anything * - * @property {String} directive - * @property {Number} time + * @param {String} directive + * @param {Number} time */ addExpirationDirective( directive, time ) { if ( AVAILABLE_EXPIRATION_DIRECTIVES.indexOf( directive ) === -1 || typeof time !== 'number' ) @@ -87,11 +87,11 @@ class CacheControl { } /** - * @brief Sets the revalidation directive + * @brief Sets the revalidation directive * - * @details This function checks from an array of possible values and if nothing matches, does not set anything. + * @details This function checks from an array of possible values and if nothing matches, does not set anything. * - * @property {String} directive + * @param {String} directive */ setRevalidationDirective( directive ) { if ( AVAILABLE_REVALIDATION_DIRECTIVES.indexOf( directive ) === -1 ) @@ -101,11 +101,11 @@ class CacheControl { } /** - * @brief Sets the other directive + * @brief Sets the other directive * - * @details This function checks from an array of possible values and if nothing matches, does not set anything. + * @details This function checks from an array of possible values and if nothing matches, does not set anything. * - * @property {String} directive + * @param {String} directive */ setOtherDirective( directive ) { if ( AVAILABLE_OTHER_DIRECTIVES.indexOf( directive ) === -1 ) @@ -115,15 +115,15 @@ class CacheControl { } /** - * @brief Appends to the header + * @brief Appends to the header * - * @details This will check if a comma needs to be added + * @details This will check if a comma needs to be added * * @private - * @property {String} header - * @property {String} value + * @param {String} header + * @param {String} value * - * @return {String} + * @return {String} */ _append( header, value ) { if ( header !== '' ) @@ -134,19 +134,19 @@ class CacheControl { } /** - * @brief Builds the cache control header + * @brief Builds the cache control header * - * @details This function will build the cache control header and clean up the builder, so it can be reused again - * You can pass another options object that will be validated via _configure as long as it is not empty + * @details This function will build the cache control header and clean up the builder, so it can be reused again + * You can pass another options object that will be validated via _configure as long as it is not empty * - * @property {Object} [options={}] - * @property {Boolean} options.static - flag should set a bunch of rules meant for static resources - * @property {Boolean} options.cacheControl - flag should set cache control - * @property {Boolean} options.revalidation - flag should set revalidation directive - * @property {Boolean} options.other - flag should set other directive - * @property {Boolean} options.expirationDirectives - CacheControl.addExpirationDirective + * @param {Object} [options={}] + * @param {Boolean} options.static - flag should set a bunch of rules meant for static resources + * @param {Boolean} options.cacheControl - flag should set cache control + * @param {Boolean} options.revalidation - flag should set revalidation directive + * @param {Boolean} options.other - flag should set other directive + * @param {Boolean} options.expirationDirectives - CacheControl.addExpirationDirective * - * @return {String} + * @return {String} */ build( options = {} ) { if ( Object.keys( options ).length !== 0 ) diff --git a/server/components/caching/data_server.js b/server/components/caching/data_server.js index a39ecb76..e2d2fc29 100644 --- a/server/components/caching/data_server.js +++ b/server/components/caching/data_server.js @@ -38,17 +38,17 @@ class DataServer extends EventEmitter { } /** - * @brief Configures the DataServer. + * @brief Configures the DataServer. * - * @details This is intentionally separated from the constructor so that it could be overwritten in any other implementations of the caching. + * @details This is intentionally separated from the constructor so that it could be overwritten in any other implementations of the caching. * * @private - * @property {Object} options - * @property {Number} options.defaultTtl - Default time to live for resources set to the data server - * @property {String} options.persistPath - Path to persist the data - * @property {Number} options.persistInterval - Time in seconds to persist data - * @property {Number} options.gcInterval - Time in seconds to garbage collect data in the DataServer - * @property {Number} options.persist - Flag whether data should be persisted + * @param {Object} options + * @param {Number} options.defaultTtl - Default time to live for resources set to the data server + * @param {String} options.persistPath - Path to persist the data + * @param {Number} options.persistInterval - Time in seconds to persist data + * @param {Number} options.gcInterval - Time in seconds to garbage collect data in the DataServer + * @param {Boolean} options.persist - Flag whether data should be persisted */ _configure( options ) { this.defaultTtl = typeof options.ttl === 'number' @@ -131,13 +131,13 @@ class DataServer extends EventEmitter { } /** - * @brief Gets the value from the server + * @brief Gets the value from the server * * @async - * @property {String} key - * @property {Object} [options={}] + * @param {String} key + * @param {Object} [options={}] * - * @return {Promise} + * @return {Promise} */ async get( key, options = {} ) { if ( typeof key !== 'string' || typeof options !== 'object' ) @@ -147,12 +147,12 @@ class DataServer extends EventEmitter { } /** - * @brief Any operations with the data server should reject if the data server is not responding + * @brief Any operations with the data server should reject if the data server is not responding * - * @private - * @property {*} [returnValue=null] + * @protected + * @param {*} [returnValue=null] * - * @return {*} + * @return {*} */ _handleServerDown( returnValue = null ) { const error = 'The data server is not responding'; @@ -164,16 +164,16 @@ class DataServer extends EventEmitter { } /** - * @brief Gets the data + * @brief Gets the data * - * @details Prunes the data if it is expired + * @details Prunes the data if it is expired * * @private * @async - * @property {String} key - * @property {Object} [options={}] + * @param {String} key + * @param {Object} [options={}] * - * @return {Promise} + * @return {Promise} */ async _get( key, options = {} ) { return new Promise( async ( resolve ) => { @@ -187,15 +187,15 @@ class DataServer extends EventEmitter { } /** - * @brief Sets the value to the data server + * @brief Sets the value to the data server * * @async - * @property {String} key - * @property {*} value - * @property {Number} [ttl=0] - * @property {Object} [options={}] + * @param {String} key + * @param {*} value + * @param {Number} [ttl=0] + * @param {Object} [options={}] * - * @return {Promise} + * @return {Promise} */ async set( key, value, ttl = 0, options = {} ) { if ( @@ -212,18 +212,18 @@ class DataServer extends EventEmitter { } /** - * @brief Sets the data + * @brief Sets the data * - * @details Resolves the data if it was correctly set, otherwise resolves to null + * @details Resolves the data if it was correctly set, otherwise resolves to null * * @private * @async - * @property {String} key - * @property {*} value - * @property {Number} ttl - * @property {Object} options + * @param {String} key + * @param {*} value + * @param {Number} ttl + * @param {Object} options * - * @return {Promise} + * @return {Promise} */ async _set( key, value, ttl, options ) { return new Promise(( resolve ) => { @@ -237,14 +237,14 @@ class DataServer extends EventEmitter { } /** - * @brief Increment a numeric key value + * @brief Increment a numeric key value * * @async - * @property {String} key - * @property {Number} [value=1] - * @property {Object} [options={}] + * @param {String} key + * @param {Number} [value=1] + * @param {Object} [options={}] * - * @return {Promise} + * @return {Promise} */ async increment( key, value = 1, options = {} ) { if ( @@ -259,17 +259,17 @@ class DataServer extends EventEmitter { } /** - * @brief Increment a numeric key value + * @brief Increment a numeric key value * - * @details Does no async operations intentionally + * @details Does no async operations intentionally * * @async * @private - * @property {String} key - * @property {Number} value - * @property {Object} options + * @param {String} key + * @param {Number} value + * @param {Object} options * - * @return {Promise} + * @return {Promise} */ async _increment( key, value, options ) { return new Promise( async ( resolve, reject ) => { @@ -291,14 +291,14 @@ class DataServer extends EventEmitter { } /** - * @brief Decrements a numeric key value + * @brief Decrements a numeric key value * * @async - * @property {String} key - * @property {Number} [value=1] - * @property {Object} [options={}] + * @param {String} key + * @param {Number} [value=1] + * @param {Object} [options={}] * - * @return {Promise} + * @return {Promise} */ async decrement( key, value = 1, options = {} ) { if ( @@ -313,17 +313,17 @@ class DataServer extends EventEmitter { } /** - * @brief Decrements a numeric key value + * @brief Decrements a numeric key value * - * @details Does no async operations intentionally + * @details Does no async operations intentionally * * @async * @private - * @property {String} key - * @property {Number} value - * @property {Object} options + * @param {String} key + * @param {Number} value + * @param {Object} options * - * @return {Promise} + * @return {Promise} */ async _decrement( key, value, options ) { return new Promise( async ( resolve, reject ) => { @@ -345,13 +345,13 @@ class DataServer extends EventEmitter { } /** - * @brief Locking mechanism. Will return a boolean if the lock was ok + * @brief Locking mechanism. Will return a boolean if the lock was ok * * @async - * @property {String} key - * @property {Object} [options={}] + * @param {String} key + * @param {Object} [options={}] * - * @return {Promise} + * @return {Promise} */ async lock( key, options = {} ) { if ( typeof key !== 'string' || typeof options !== 'object' ) @@ -361,14 +361,14 @@ class DataServer extends EventEmitter { } /** - * @brief Locking mechanism. Will return a boolean if the lock was ok + * @brief Locking mechanism. Will return a boolean if the lock was ok * * @async * @private - * @property {String} key - * @property {Object} options + * @param {String} key + * @param {Object} options * - * @return {Boolean} + * @return {Boolean} */ async _lock( key, options ) { return new Promise(( resolve ) => { @@ -385,13 +385,13 @@ class DataServer extends EventEmitter { } /** - * @brief Releases the lock + * @brief Releases the lock * * @async - * @property {String} key - * @property {Object} [options={}] + * @param {String} key + * @param {Object} [options={}] * - * @return {Promise} + * @return {Promise} */ async unlock( key, options = {} ) { if ( typeof key !== 'string' || typeof options !== 'object' ) @@ -401,14 +401,14 @@ class DataServer extends EventEmitter { } /** - * @brief Releases the key + * @brief Releases the key * * @async * @private - * @property {String} key - * @property {Object} options + * @param {String} key + * @param {Object} options * - * @return {Boolean} + * @return {Boolean} */ async _unlock( key, options ) { return new Promise(( resolve ) => { @@ -422,15 +422,15 @@ class DataServer extends EventEmitter { } /** - * @brief Makes a new dataSet from the data + * @brief Makes a new dataSet from the data * * @private - * @property {String} key - * @property {*} value - * @property {Number} ttl - * @property {Boolean} persist + * @param {String} key + * @param {*} value + * @param {Number} ttl + * @param {Boolean} persist * - * @return {Object} + * @return {Object} */ _makeDataSet( key, value, ttl, persist ) { const expirationDate = this._getExpirationDateFromTtl( ttl ); @@ -438,16 +438,16 @@ class DataServer extends EventEmitter { } /** - * @brief Touches the given key + * @brief Touches the given key * - * @details Checks if the arguments are correct + * @details Checks if the arguments are correct * * @async - * @property {String} key - * @property {Number} [ttl=0] - * @property {Object} [options={}] + * @param {String} key + * @param {Number} [ttl=0] + * @param {Object} [options={}] * - * @return {Promise} + * @return {Promise} */ async touch( key, ttl = 0, options = {} ) { if ( typeof key !== 'string' || typeof ttl !== 'number' || typeof options !== 'object' ) @@ -457,15 +457,15 @@ class DataServer extends EventEmitter { } /** - * @brief Touches the key + * @brief Touches the key * * @async * @private - * @property {String} key - * @property {Number} ttl - * @property {Object} options + * @param {String} key + * @param {Number} ttl + * @param {Object} options * - * @return {Promise} + * @return {Promise} */ async _touch( key, ttl, options ) { return new Promise( async ( resolve ) => { @@ -481,14 +481,14 @@ class DataServer extends EventEmitter { } /** - * @brief Removes a key if it is expired, otherwise, return it + * @brief Removes a key if it is expired, otherwise, return it * * @async * @private - * @property {String} key - * @property {Object} options + * @param {String} key + * @param {Object} options * - * @return {Promise} + * @return {Promise} */ async _prune( key, options ) { return new Promise( async ( resolve ) => { @@ -511,15 +511,15 @@ class DataServer extends EventEmitter { } /** - * @brief Completely removes the key from the server + * @brief Completely removes the key from the server * - * @details Returns true on success and false on failure. If the key does not exist, false will be returned + * @details Returns true on success and false on failure. If the key does not exist, false will be returned * * @async - * @property {String} key - * @property {Object} [options={}] + * @param {String} key + * @param {Object} [options={}] * - * @return {Promise} + * @return {Promise} */ async delete( key, options = {} ) { if ( typeof key === 'string' && typeof options === 'object' ) @@ -529,14 +529,14 @@ class DataServer extends EventEmitter { } /** - * @brief Deletes the key from the server + * @brief Deletes the key from the server * * @async * @private - * @property {String} key - * @property {Object} options + * @param {String} key + * @param {Object} options * - * @return {Promise} + * @return {Promise} */ _delete( key, options ) { return new Promise(( resolve ) => { @@ -650,12 +650,12 @@ class DataServer extends EventEmitter { } /** - * @brief Gets the ttl depending on the values given + * @brief Gets the ttl depending on the values given * * @private - * @property {Number} [ttl=-1] + * @param {Number} [ttl=-1] * - * @return {Number} + * @return {Number} */ _getTtl( ttl = -1 ) { if ( ttl === -1 ) @@ -665,12 +665,12 @@ class DataServer extends EventEmitter { } /** - * @brief Gets the expiration date of the record given the ttl + * @brief Gets the expiration date of the record given the ttl * - * @private - * @property {Number} [ttl=-1] + * @protected + * @param {Number} [ttl=-1] * - * @return {Number} + * @return {Number} */ _getExpirationDateFromTtl( ttl = -1 ) { return new Date().getTime() / 1000 + this._getTtl( ttl ); diff --git a/server/components/caching/data_server_map.js b/server/components/caching/data_server_map.js index 3d3215c4..e40af43a 100644 --- a/server/components/caching/data_server_map.js +++ b/server/components/caching/data_server_map.js @@ -16,7 +16,15 @@ const DEFAULT_PERSIST_FILE = path.join( PROJECT_ROOT, 'cacheMap' ); */ class DataServerMap extends DataServer { /** - * @property {Object} options + * @private + * @param {Object} options + * @param {Number} options.defaultTtl - Default time to live for resources set to the data server + * @param {String} options.persistPath - Path to persist the data + * @param {Number} options.persistInterval - Time in seconds to persist data + * @param {Number} options.gcInterval - Time in seconds to garbage collect data in the DataServer + * @param {Boolean} options.persist - Flag whether data should be persisted + * @param {Boolean} options.useBigMap - Flag should we use a Map or a BigMap ( BigMap is a custom-made class + * that can hold an infinite amount of data ) * * @return void */ @@ -34,7 +42,7 @@ class DataServerMap extends DataServer { /** * @brief Sets up the persistence * - * @return void + * @private */ _setUpPersistence() { if ( fs.existsSync( this.persistPath ) ) { @@ -48,7 +56,7 @@ class DataServerMap extends DataServer { /** * @brief Stops the server * - * @return void + * @private */ _stop() { if ( fs.existsSync( this.persistPath ) ) @@ -60,12 +68,14 @@ class DataServerMap extends DataServer { /** * @brief Gets the data * + * @private + * @async * @details Prunes the data if it is expired * - * @property {String} key - * @property {Object} [options={}] + * @param {String} key + * @param {Object} [options={}] * - * @return Promise + * @return {Promise} */ async _get( key, options = {} ) { return new Promise( async ( resolve ) => { @@ -81,14 +91,16 @@ class DataServerMap extends DataServer { /** * @brief Sets the data * + * @private + * @async * @details Resolves the data if it was correctly set, otherwise resolves to null * - * @property {String} key - * @property {*} value - * @property {Number} ttl - * @property {Object} options + * @param {String} key + * @param {*} value + * @param {Number} ttl - Time to live for the record + * @param {Object} options * - * @return Promise + * @return {Promise} */ async _set( key, value, ttl, options ) { return new Promise(( resolve ) => { @@ -107,13 +119,15 @@ class DataServerMap extends DataServer { /** * @brief Increment a numeric key value * + * @private + * @async * @details Does no async operations intentionally * - * @property {String} key - * @property {Number} value - * @property {Object} options + * @param {String} key + * @param {Number} value + * @param {Object} options * - * @return Promise + * @return {Promise} */ async _increment( key, value, options ) { return new Promise( async ( resolve, reject ) => { @@ -137,13 +151,15 @@ class DataServerMap extends DataServer { /** * @brief Decrements a numeric key value * + * @private + * @async * @details Does no async operations intentionally * - * @property {String} key - * @property {Number} value - * @property {Object} options + * @param {String} key + * @param {Number} value + * @param {Object} options * - * @return Promise + * @return {Promise} */ async _decrement( key, value, options ) { return new Promise( async ( resolve, reject ) => { @@ -167,10 +183,12 @@ class DataServerMap extends DataServer { /** * @brief Locking mechanism. Will return a boolean if the lock was ok * - * @property {String} key - * @property {Object} options + * @private + * @async + * @param {String} key + * @param {Object} options * - * @return Boolean + * @return {Boolean} */ async _lock( key, options ) { return new Promise(( resolve ) => { @@ -186,12 +204,14 @@ class DataServerMap extends DataServer { } /** - * @brief Releases the key + * @brief Releases the lock * - * @property {String} key - * @property {Object} options + * @private + * @async + * @param {String} key + * @param {Object} options * - * @return Boolean + * @return {Boolean} */ async _unlock( key, options ) { return new Promise(( resolve ) => { @@ -203,17 +223,19 @@ class DataServerMap extends DataServer { } /** - * @brief Touches the key + * @brief Touches the given key * - * @property {String} key - * @property {Number} ttl - * @property {Object} options + * @private + * @async + * @param {String} key + * @param {Number} ttl + * @param {Object} options * - * @return Promise + * @return {Promise} */ async _touch( key, ttl, options ) { return new Promise( async ( resolve ) => { - const dataSet = await this._prune( key ); + const dataSet = await this._prune( key, options ); if ( dataSet === null ) return resolve( false ); @@ -230,10 +252,12 @@ class DataServerMap extends DataServer { /** * @brief Removes a key if it is expired, otherwise, return it * - * @property {String} key - * @property {Object} options + * @private + * @async + * @param {String} key + * @param {Object} options * - * @return Promise + * @return {Promise} */ async _prune( key, options ) { return new Promise( async ( resolve ) => { @@ -259,10 +283,12 @@ class DataServerMap extends DataServer { /** * @brief Deletes the key from the server * - * @property {String} key - * @property {Object} options + * @private + * @async + * @param {String} key + * @param {Object} options * - * @return Promise + * @return {Promise} */ _delete( key, options ) { return new Promise(( resolve ) => { @@ -278,9 +304,10 @@ class DataServerMap extends DataServer { /** * @brief Returns how many keys there are * + * @private * @details THIS IS USED FOR TESTING PURPOSES ONLY * - * @return Number + * @return {Number} */ /* istanbul ignore next */ length() { @@ -290,7 +317,7 @@ class DataServerMap extends DataServer { /** * @brief Performs Garbage collection to free up memory * - * @return void + * @private */ _garbageCollect() { this.server.forEach( ( value, key ) => { @@ -301,7 +328,7 @@ class DataServerMap extends DataServer { /** * @brief Saves the data to a file periodically * - * @return void + * @private */ _saveData() { let serverData = this.useBigMap ? new BigMap() : new Map(); @@ -347,7 +374,7 @@ class DataServerMap extends DataServer { /** * @brief Merge server data from file * - * @return void + * @private */ _loadData() { let serverData; @@ -369,10 +396,10 @@ class DataServerMap extends DataServer { } /** - * @property {*} key - * @property {*} value + * @param {*} key + * @param {*} value * - * @return * + * @return {*} */ static replacer( key, value ) { const originalObject = this[key]; @@ -388,16 +415,15 @@ class DataServerMap extends DataServer { return { dataType : 'BigMap', value: { maps: value, _limit : originalObject._limit } }; } - else return value; } /** - * @property {*} key - * @property {*} value + * @param {*} key + * @param {*} value * - * @return * + * @return {*} */ static reviver( key, value ) { if( typeof value === 'object' && value !== null && value.dataType === 'Map' ) diff --git a/server/components/error/error_handler.js b/server/components/error/error_handler.js index a047808d..fcc86bc5 100644 --- a/server/components/error/error_handler.js +++ b/server/components/error/error_handler.js @@ -27,12 +27,12 @@ class ErrorHandler { /** * @brief Handles an error * - * @property {EventRequest} event - * @property {*} [errorToHandle=null] - * @property {Number} [errStatusCode=null] - * @property {Boolean} [emitError=null] + * @param {EventRequest} event + * @param {*} [errorToHandle=null] + * @param {Number} [errStatusCode=null] + * @param {Boolean} [emitError=null] * - * @return Promise: void + * @return {Promise} */ async handleError( event, errorToHandle = null, errStatusCode = null, emitError = null ) { let errorNamespace = null; @@ -97,15 +97,14 @@ class ErrorHandler { /** * @brief Adds a new namespace * - * @property {String} code - * @property {*} message - * @property {Function} callback - * @property {Number} status - * @property {Boolean} emit - * @property {Object} headers - * @property {Function} formatter - * - * @return void + * @param {String} code + * @param {Object} object + * @param {*} object.message + * @param {Function} object.callback + * @param {Number} object.status + * @param {Boolean} object.emit + * @param {Object} object.headers + * @param {Function} object.formatter */ addNamespace( code, { message, callback, status, emit, headers, formatter } = {} ) { if ( ! this.validateNamespaceCode( code ) ) @@ -130,7 +129,7 @@ class ErrorHandler { /** * @brief Validates that the provided errorCode is a string and does not have any white space characters * - * @property {String} errorCode + * @param {String} errorCode * * @return {Boolean} */ @@ -141,7 +140,7 @@ class ErrorHandler { /** * @brief Returns the expectation that contains the errorCode and message * - * @property {String} errorCode + * @param {String} errorCode * * @return {Object|null} */ @@ -166,23 +165,23 @@ class ErrorHandler { /** * @brief Fallback namespace that will be called whenever there is no namespace for the given error code OR the namespace match does not have a callback * + * @private * @details This callback will set any headers provided * This callback will set the status code given * This callback will format an appropriate message in case of an error * This callback emit an error IF needed * - * @property {EventRequest} event - * @property {String} errorCode - * @property {Number} status - * @property {*} error - * @property {*} message - * @property {Object} headers - * @property {Boolean} emit - * @property {Function} formatter + * @param {Object} object + * @param {EventRequest} object.event - the EventRequest object + * @param {String} object.code - error code to send + * @param {Number} object.status - status code to return + * @param {*} object.error - the error message or object + * @param {*} object.message - the error message -> this will take precedence over the error in regards to the message + * @param {Object} object.headers - extra headers to set + * @param {Boolean} object.emit - Flag to emit the error or not + * @param {Function} object.formatter - The error formatter * - * @private - * - * @return Promise: void + * @return {Promise} */ async _defaultCase( { event, code, status, error, message, headers, emit, formatter } ) { if ( event.isFinished() ) @@ -210,17 +209,18 @@ class ErrorHandler { const result = formatter( { event, code, status, error, message, headers, emit } ); if ( result instanceof Promise ) - event.send( await result, status ); + await event.send( await result, status ); else - event.send( result, status ); + await event.send( result, status ); } /** * @brief Formats the error in a presentable format * - * @property {*} error + * @private + * @param {*} error - the error to format ( will extract the message if Error object, otherwise return ) * - * @return * + * @return {*} */ _formatError( error ) { if ( error instanceof Error ) diff --git a/server/components/file_streams/abstract_file_stream.js b/server/components/file_streams/abstract_file_stream.js index d5ee3607..84b6010b 100644 --- a/server/components/file_streams/abstract_file_stream.js +++ b/server/components/file_streams/abstract_file_stream.js @@ -5,8 +5,8 @@ const path = require( 'path' ); class AbstractFileStream { /** - * @property {Array} supportedFormats - * @property {String} streamType + * @param {Array} [supportedFormats=[]] + * @param {String} [streamType='unknown'] */ constructor( supportedFormats = [], streamType = 'unknown' ) { this.SUPPORTED_FORMATS = supportedFormats; @@ -16,9 +16,9 @@ class AbstractFileStream { /** * @brief Check whether the given file is supported by the file stream * - * @property {String} file + * @param {String} file - the file to check if it is supported * - * @return Boolean + * @return {Boolean} */ supports( file ) { const parsedPath = path.parse( file ); @@ -28,7 +28,7 @@ class AbstractFileStream { /** * @brief Gets the type of file this stream supports * - * @return String + * @return {String} */ getType() { return this._streamType; diff --git a/server/components/file_streams/audio_file_stream.js b/server/components/file_streams/audio_file_stream.js index 168af772..cbbc3d68 100644 --- a/server/components/file_streams/audio_file_stream.js +++ b/server/components/file_streams/audio_file_stream.js @@ -16,14 +16,14 @@ class AudioFileStream extends AbstractFileStream { /** * @brief Gets the file stream for the file * - * @property {EventRequest} event - * @property {String} file - * @property {Object} [options={}] + * @param {EventRequest} event + * @param {String} file + * @param {Object} [options={}] * - * @return ReadStream + * @return {ReadStream} */ getFileStream( event, file, options = {} ) { - let stream = null; + let stream; const stat = fs.statSync( file ); const fileSize = stat.size; const range = event.getRequestHeader( 'range' ); diff --git a/server/components/file_streams/file_stream_handler.js b/server/components/file_streams/file_stream_handler.js index cb3f9e2d..7617f180 100644 --- a/server/components/file_streams/file_stream_handler.js +++ b/server/components/file_streams/file_stream_handler.js @@ -7,15 +7,17 @@ const AudioFileStream = require( './audio_file_stream' ); const TextFileStream = require( './text_file_stream' ); const ImageFileStream = require( './image_file_stream' ); + module.exports = { /** * @brief Gets the file streamer responsible for handling the given file type * - * @details Returns null if a file streamer is not found + * @details Returns null if a file streamer is not found. + * The fileStreams are created intentionally inside * - * @property {String} file + * @param {String} file * - * @return VideoFileStream|AudioFileStream|ImageFileStream|TextFileStream|null + * @return {AbstractFileStream|null} */ getFileStreamerForType : ( file ) => { const fileStreams = [ diff --git a/server/components/file_streams/image_file_stream.js b/server/components/file_streams/image_file_stream.js index 3775f2fe..26343960 100644 --- a/server/components/file_streams/image_file_stream.js +++ b/server/components/file_streams/image_file_stream.js @@ -4,40 +4,34 @@ const fs = require( 'fs' ); const path = require( 'path' ); const AbstractFileStream = require( './abstract_file_stream' ); +const { findMimeType } = require( '../mime_type/mime_type' ); /** * @brief Used to stream text files */ class ImageFileStream extends AbstractFileStream { constructor() { - super( [], 'image' ); - // @TODO NEW MIME-TYPE COMPONENT SHOULD BE MADE - this.formats = { - '.apng' : 'image/apng', '.avif' : 'image/avif', '.gif' : 'image/gif', '.jpg' : 'image/jpeg', - '.jpeg' : 'image/jpeg', '.jfif' : 'image/jpeg', '.pjpeg' : 'image/jpeg', '.pjp' : 'image/jpeg', - '.png' : 'image/png', '.svg' : 'image/svg+xml', '.webp' : 'image/webp', '.ico' : 'image/x-icon', - '.bmp' : 'image/bmp', - }; - - this.SUPPORTED_FORMATS = Object.keys( this.formats ); + super( [ + '.gif', '.jpg', '.jpeg', '.bmp', + '.png', '.svg', '.webp', '.ico' + ], 'image' ); } /** * @brief Gets the file stream for the file * - * @property {EventRequest} event - * @property {String} file - * @property {Object} [options={}] + * @param {EventRequest} event + * @param {String} file + * @param {Object} [options={}] * - * @return ReadStream + * @return {ReadStream} */ getFileStream( event, file, options = {} ) { const stream = fs.createReadStream( file, options ); const parsedPath = path.parse( file ); - const mimeType = this.formats[parsedPath.ext.toLowerCase()]; + const mimeType = findMimeType( parsedPath.ext.toLowerCase() ); - if ( typeof mimeType === 'string' ) - event.setResponseHeader( 'Content-Type', mimeType ); + event.setResponseHeader( 'Content-Type', mimeType ); return stream; } diff --git a/server/components/file_streams/text_file_stream.js b/server/components/file_streams/text_file_stream.js index 6bd9f5a7..c3403729 100644 --- a/server/components/file_streams/text_file_stream.js +++ b/server/components/file_streams/text_file_stream.js @@ -3,36 +3,40 @@ // Dependencies const fs = require( 'fs' ); const AbstractFileStream = require( './abstract_file_stream' ); +const path = require( 'path' ); +const { findMimeType } = require( '../mime_type/mime_type' ); /** * @brief Used to stream text files */ class TextFileStream extends AbstractFileStream { - //@TODO ADD MIME TYPES constructor() { - super( - [ - '.txt', '.js', '.php', '.html', '.json', '.cpp', '.h', - '.md', '.bat', '.log', '.yml', '.ini', '.ts', '.ejs', '.twig', - '', '.rtf', '.apt', '.fodt', '.rft', '.apkg', '.fpt', '.lst', - '.doc', '.docx', '.man', '.plain', '.text', '.odm', '.readme', - '.cmd', '.ps1', '.conf', '.default', '.config' - ], - 'text' - ); + super([ + '.txt', '.js', '.php', '.html', '.json', '.cpp', '.h', + '.md', '.bat', '.log', '.yml', '.ini', '.ts', '.ejs', '.twig', + '', '.rtf', '.apt', '.fodt', '.rft', '.apkg', '.fpt', '.lst', + '.doc', '.docx', '.man', '.plain', '.text', '.odm', '.readme', + '.cmd', '.ps1', '.conf', '.default', '.config', '.csv' + ], 'text' ); } /** * @brief Gets the file stream for the file * - * @property {EventRequest} event - * @property {String} file - * @property {Object} [options={}] + * @param {EventRequest} event + * @param {String} file + * @param {Object} [options={}] * - * @return ReadStream + * @return {ReadStream} */ getFileStream( event, file, options = {} ) { - return fs.createReadStream( file, options ); + const stream = fs.createReadStream( file, options ); + const parsedPath = path.parse( file ); + const mimeType = findMimeType( parsedPath.ext.toLowerCase() ); + + event.setResponseHeader( 'Content-Type', mimeType ); + + return stream; } } diff --git a/server/components/file_streams/video_file_stream.js b/server/components/file_streams/video_file_stream.js index 6dfaeee5..230ae46a 100644 --- a/server/components/file_streams/video_file_stream.js +++ b/server/components/file_streams/video_file_stream.js @@ -16,11 +16,11 @@ class VideoFileStream extends AbstractFileStream { /** * @brief Gets the file stream for the file * - * @property {EventRequest} event - * @property {String} file - * @property {Object} [options={}] + * @param {EventRequest} event + * @param {String} file + * @param {Object} [options={}] * - * @return ReadStream + * @return {ReadStream} */ getFileStream( event, file, options = {} ) { let stream = null; diff --git a/server/components/helpers/unique_id.js b/server/components/helpers/unique_id.js index f1e90a19..3f16d65b 100644 --- a/server/components/helpers/unique_id.js +++ b/server/components/helpers/unique_id.js @@ -4,14 +4,13 @@ module.exports = { /** * @brief Helper method that generates a random string * - * @property {Number} length + * @param {Number} length * - * @return String + * @return {String} */ - makeId : ( length ) => { + makeId : ( length = 32 ) => { let text = ""; const possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"; - length = typeof length === 'number' ? length : 10; for ( let i = 0; i < length; ++ i ) text += possible.charAt( Math.floor( Math.random() * possible.length ) ); diff --git a/server/components/logger/components/log.js b/server/components/logger/components/log.js index b36278c0..19edb204 100644 --- a/server/components/logger/components/log.js +++ b/server/components/logger/components/log.js @@ -19,9 +19,9 @@ const DEFAULT_LOG_LEVEL = LOG_LEVELS.notice; */ class Log { /** - * @property {*} log - * @property {Number} level - * @property {Boolean} isRaw + * @param {*} log + * @param {Number} level + * @param {Boolean} isRaw */ constructor( log, level, isRaw ) { this.level = 0; @@ -37,11 +37,9 @@ class Log { /** * @brief Processes the given log * - * @property {*} [message=''] - * @property {Number} [level=LOG_LEVELS.error] - * @property {Boolean} [isRaw=false] - * - * @return void + * @param {*} [message=''] + * @param {Number} [level=LOG_LEVELS.error] + * @param {Boolean} [isRaw=false] */ processLog( message = '', level = LOG_LEVELS.error, isRaw = false ) { let logType = typeof message; @@ -73,7 +71,7 @@ class Log { /** * @brief Gets the log level of the provided log * - * @return Number + * @return {Number} */ getLevel() { return this.level; @@ -82,7 +80,7 @@ class Log { /** * @brief Gets the log message of the provided log * - * @return String + * @return {String} */ getMessage() { return this.message; @@ -91,7 +89,7 @@ class Log { /** * @brief Gets the raw log message of the provided log * - * @return mixed + * @return {*} */ getRawMessage() { return this.rawMessage; @@ -100,7 +98,7 @@ class Log { /** * @brief Gets whether this log is attempting to be logged raw * - * @return Boolean + * @return {Boolean} */ getIsRaw() { return this.isRaw; @@ -109,7 +107,7 @@ class Log { /** * @brief Gets the log timestamp of the provided log in UNIX time * - * @return Number + * @return {Number} */ getTimestamp() { return this.timestamp; @@ -118,16 +116,14 @@ class Log { /** * @brief Get the unique id set by the Loggur * - * @return String + * @return {String} */ getUniqueId() { return this.uniqueId; } /** - * @property {String} uniqueId - * - * @return void + * @param {String} uniqueId */ setUniqueId( uniqueId ) { this.uniqueId = uniqueId; @@ -136,7 +132,7 @@ class Log { /** * @brief Get the log in a string format * - * @return String + * @return {String} */ toString() { return `{Level: ${this.getLevel()}, Message: ${this.getMessage()}, Time: ${this.getTimestamp()}`; @@ -145,11 +141,11 @@ class Log { /** * @brief Get a new instance of the Log * - * @property {*} log - * @property {Number} level - * @property {Boolean} isRaw + * @param {*} log + * @param {Number} level + * @param {Boolean} isRaw * - * @return Log + * @return {Log} */ static getInstance( log, level, isRaw ) { if ( log instanceof Log ) { @@ -165,7 +161,7 @@ class Log { /** * @brief Get the current time in UNIX format * - * @return Number + * @return {Number} */ static getUNIXTime() { return Date.now() / 1000; diff --git a/server/components/logger/components/logger.js b/server/components/logger/components/logger.js index e441edde..fb03af85 100644 --- a/server/components/logger/components/logger.js +++ b/server/components/logger/components/logger.js @@ -15,8 +15,8 @@ const LOGGER_DEFAULT_LOG_LEVEL = LOG_LEVELS.info; */ class Logger { /** - * @property {Object} [options={}] - * @property {Boolean} [uniqueId=null] + * @param {Object} [options={}] + * @param {Boolean} [uniqueId=null] */ constructor( options = {}, uniqueId = null ) { if ( typeof uniqueId !== 'string' ) @@ -33,20 +33,18 @@ class Logger { /** * @brief Sanitize the loggers config * - * @details Accepted options: - * - serverName - String - The name of the server to be concatenated with the uniqueId - Defaults to empty - * - transports - Array - Array of the transports to be added to the logger - Defaults to empty - * - logLevel - Number - The log severity level -> Defaults to error - * - logLevels - Object - JSON object with all the log severity levels and their values - * All added log levels will be attached to the instance of the logger class -> Defaults to LOG_LEVELS - * - capture - Boolean - Whether to attach event listeners for process.on - * uncaughtException and unhandledRejection - Defaults to false - * - dieOnCapture - Boolean - If the process should exit in case of a caught exception -> Defaults to true - * - unhandledExceptionLevel - Number - What level should the unhandled exceptions be logged at -> Defaults to error - * - * @property {Object} options - * - * @return void + * @param {Object} options + * @param {String} [options.serverName=""] - The name of the server to be concatenated with the uniqueId + * @param {Array} [options.transports=[]] - Array of the transports to be added to the logger + * @param {Number} [options.logLevel=LOG_LEVELS.error] - The log severity level + * @param {Object} [options.logLevels=LOG_LEVELS] - JSON object with all the log severity levels and their values + * All added log levels will be attached to the instance + * of the logger class + * @param {Boolean} [options.capture=false] - Whether to attach event listeners for process.on + * uncaughtException and unhandledRejection + * @param {Boolean} [options.dieOnCapture=true] - If the process should exit in case of a caught exception + * @param {Number} [options.unhandledExceptionLevel=LOG_LEVELS.error] + * - What level should the unhandled exceptions be logged at */ sanitizeConfig( options ) { this.serverName = typeof options.serverName === 'string' @@ -90,9 +88,7 @@ class Logger { /** * @brief Sets the Log Level of the Logger * - * @property {Number} logLevel - * - * @return void + * @param {Number} logLevel */ setLogLevel( logLevel ) { this.logLevel = logLevel; @@ -103,8 +99,6 @@ class Logger { * * @details If capture is set to true only. If dieOnCapture is set to false the process won't die but this is * not recommended - * - * @return void */ /* istanbul ignore next */ attachUnhandledEventListener() { @@ -137,8 +131,6 @@ class Logger { /** * @brief Attach the provided log levels to the logger for convenience - * - * @return void */ attachLogLevelsToLogger() { for ( let key in this.logLevels ) { @@ -160,11 +152,11 @@ class Logger { } /** - * @brief Add a transport to the logger + * @brief Add transport to the logger * - * @property {*} transport + * @param {*} transport * - * @return Boolean + * @return {Boolean} */ addTransport( transport ) { if ( transport instanceof Transport ) { @@ -180,7 +172,7 @@ class Logger { * * @brief {*} log * - * @return Boolean + * @return {Boolean} */ supports( log ) { if ( ! ( log instanceof Log ) ) @@ -192,7 +184,7 @@ class Logger { /** * @brief Returns a unique id to be set in the log * - * @return String + * @return {String} */ getUniqueId() { return typeof this.serverName === 'string' @@ -203,11 +195,11 @@ class Logger { /** * @brief Logs the given data * - * @property {*} log - * @property {Number} [level=null] - * @property {Boolean} [isRaw=false] + * @param {*} log + * @param {Number} [level=null] + * @param {Boolean} [isRaw=false] * - * @return Promise + * @return {Promise} */ log( log, level = null, isRaw = false ) { log = Log.getInstance( log, level, isRaw ); diff --git a/server/components/logger/components/transport_types/console.js b/server/components/logger/components/transport_types/console.js index 5e1ede68..67382ffa 100644 --- a/server/components/logger/components/transport_types/console.js +++ b/server/components/logger/components/transport_types/console.js @@ -10,9 +10,9 @@ class Console extends Transport { /** * @brief Sanitize the config * - * @property {Object} options - * - * @return void + * @param {Object} options + * @param {Array[Function]} options.processors - Holds an array of processors to apply to the log + * @param {Function} options.formatter - Formatter function */ sanitizeConfig( options ) { super.sanitizeConfig( options ); @@ -29,11 +29,9 @@ class Console extends Transport { /** * @brief Logs the data * - * @property {Array} data - * @property {Function} resolve - * @property {Function} reject - * - * @return void + * @param {Array} data + * @param {Function} resolve + * @param {Function} reject */ _log( data, resolve, reject ) { console.log.apply( this, data ); diff --git a/server/components/logger/components/transport_types/file.js b/server/components/logger/components/transport_types/file.js index dc5695fc..82169c7f 100644 --- a/server/components/logger/components/transport_types/file.js +++ b/server/components/logger/components/transport_types/file.js @@ -18,12 +18,10 @@ class File extends Transport { /** * @brief Sanitizes the config * - * @details Accepted options: - * - filePath - String - the location of the file to log to -> if it is not provided the transport will not log - * - * @property {Object} options - * - * @return void + * @param {Object} options + * @param {String} options.filePath - The location of the file to log to -> if it is not provided the transport will not log + * @param {String} options.processors - Holds an array of processors to apply to the log + * @param {Function} options.formatter - Formatter function */ sanitizeConfig( options ) { super.sanitizeConfig( options ); @@ -49,7 +47,7 @@ class File extends Transport { /** * @brief Get a new write stream for the given path * - * @return WriteStream + * @return {WriteStream} */ getWriteStream() { const file = path.parse( this.filePath ); @@ -66,7 +64,7 @@ class File extends Transport { /** * @brief Gets the file name with added timestamp * - * @return String + * @return {String} */ getFileName() { const file = path.parse( this.filePath ); @@ -77,7 +75,7 @@ class File extends Transport { /** * @brief Gets the beginning of the current day * - * @return Number + * @return {Number} */ getCurrentDayTimestamp() { const now = new Date(); @@ -88,11 +86,9 @@ class File extends Transport { /** * @brief Logs the log in a file * - * @property {Array} data - * @property {Function} resolve - * @property {Function} reject - * - * @return void + * @param {Array} data + * @param {Function} resolve + * @param {Function} reject */ _log( data, resolve, reject ) { const writeStream = this.getWriteStream(); diff --git a/server/components/logger/components/transport_types/formatters/colorize.js b/server/components/logger/components/transport_types/formatters/colorize.js index 03878e84..d4831196 100644 --- a/server/components/logger/components/transport_types/formatters/colorize.js +++ b/server/components/logger/components/transport_types/formatters/colorize.js @@ -16,9 +16,9 @@ const RESET = '\u001b[0m'; /** * @brief Colorize the logs * - * @property {String} log + * @param {String} log * - * @return String + * @return {String} */ colorize.red = ( log ) => { return RED + log + RESET; }; colorize.black = ( log ) => { return BLACK + log + RESET; }; diff --git a/server/components/logger/components/transport_types/formatters/json_formatter.js b/server/components/logger/components/transport_types/formatters/json_formatter.js index 9e3e04a6..6b0371bf 100644 --- a/server/components/logger/components/transport_types/formatters/json_formatter.js +++ b/server/components/logger/components/transport_types/formatters/json_formatter.js @@ -3,15 +3,15 @@ /** * @brief You can pass your own JSON replacer * - * @return Function + * @return {Function} */ module.exports = ( { replacer = null } = {} ) => { /** * @brief Formats the given log to a JSON * - * @property {Object} context + * @param {Object} context * - * @return Array + * @return {Array} */ return ( context = {} ) => { delete context.rawMessage; diff --git a/server/components/logger/components/transport_types/formatters/plain_formatter.js b/server/components/logger/components/transport_types/formatters/plain_formatter.js index f15b6453..ff91e3bc 100644 --- a/server/components/logger/components/transport_types/formatters/plain_formatter.js +++ b/server/components/logger/components/transport_types/formatters/plain_formatter.js @@ -5,7 +5,7 @@ * * @details noRaw is by default false, which allows raw logs * - * @return Function + * @return {Function} */ module.exports = ( { noRaw = false } = {} ) => { /** @@ -13,9 +13,9 @@ module.exports = ( { noRaw = false } = {} ) => { * * @details This will return an array of all the data that needs to be logged * - * @property {Object} context + * @param {Object} context * - * @return Array + * @return {Array} */ return ( context = {} ) => { const propertiesToTest = ['uniqueId', 'timestamp', 'isRaw', 'rawMessage', 'message']; diff --git a/server/components/logger/components/transport_types/processors/color_processor.js b/server/components/logger/components/transport_types/processors/color_processor.js index 6084e108..5419fbca 100644 --- a/server/components/logger/components/transport_types/processors/color_processor.js +++ b/server/components/logger/components/transport_types/processors/color_processor.js @@ -15,15 +15,13 @@ const DEFAULT_LOG_COLORS = { }; /** - * @property {Object} options + * @param {Object} options * - * @return Function + * @return {Function} */ module.exports = ( { logColors = DEFAULT_LOG_COLORS } = {} ) => { /** * @brief Adds colors to the message, uniqueId and timestamp - * - * @return void */ return ( context = {} ) => { const propertiesToTest = ['level', 'uniqueId', 'timestamp', 'isRaw', 'message']; diff --git a/server/components/logger/components/transport_types/processors/new_line_processor.js b/server/components/logger/components/transport_types/processors/new_line_processor.js index 7203e356..8bc19148 100644 --- a/server/components/logger/components/transport_types/processors/new_line_processor.js +++ b/server/components/logger/components/transport_types/processors/new_line_processor.js @@ -1,14 +1,11 @@ - const os = require( 'os' ); /** - * @return Function + * @return {Function} */ module.exports = () => { /** * @brief Replaces the message with the Error stack - * - * @return void */ return ( context = {} ) => { if ( typeof context.message === 'string' ) diff --git a/server/components/logger/components/transport_types/processors/stack_processor.js b/server/components/logger/components/transport_types/processors/stack_processor.js index 49004e9d..d0dbd015 100644 --- a/server/components/logger/components/transport_types/processors/stack_processor.js +++ b/server/components/logger/components/transport_types/processors/stack_processor.js @@ -1,11 +1,9 @@ /** - * @return Function + * @return {Function} */ module.exports = () => { /** * @brief Replaces the message with the Error stack - * - * @return void */ return ( context = {} ) => { const propertiesToTest = ['rawMessage', 'message']; diff --git a/server/components/logger/components/transport_types/processors/timestamp_processor.js b/server/components/logger/components/transport_types/processors/timestamp_processor.js index 76b4a0a1..b7dfd0f4 100644 --- a/server/components/logger/components/transport_types/processors/timestamp_processor.js +++ b/server/components/logger/components/transport_types/processors/timestamp_processor.js @@ -1,33 +1,29 @@ /** * @brief Gets the timestamp from the Log * - * @property {Number} timestamp + * @param {Number} timestamp * * @return {String} */ function getTimestamp( timestamp ) { - return Intl.DateTimeFormat( 'en-GB', - { - hour12 : false, - year : '2-digit', - month : '2-digit', - day : '2-digit', - hour : '2-digit', - minute : '2-digit', - second : '2-digit' - } - ).format( new Date( timestamp * 1000 ) ); + return Intl.DateTimeFormat( 'en-GB', { + hour12 : false, + year : '2-digit', + month : '2-digit', + day : '2-digit', + hour : '2-digit', + minute : '2-digit', + second : '2-digit' + }).format( new Date( timestamp * 1000 ) ); } /** - * @return Function + * @return {Function} */ module.exports = () => { /** * @brief Formats the timestamp in a more pleasing format - * - * @return void */ return ( context = {} ) => { if ( typeof context.timestamp === 'number' ) diff --git a/server/components/logger/components/transport_types/transport.js b/server/components/logger/components/transport_types/transport.js index e80f843e..e3093956 100644 --- a/server/components/logger/components/transport_types/transport.js +++ b/server/components/logger/components/transport_types/transport.js @@ -26,9 +26,11 @@ class Transport { /** * @brief Sanitize the given options * - * @property {Object} options - * - * @return void + * @param {Object} options + * @param {Number} options.logLevel - The default log level. One of LOG_LEVELS or any other whole number + * @param {Object} options.logLevels - All of the log levels that this transport can work with + * @param {Object} options.processors - Holds an array of processors to apply to the log + * @param {Object} options.formatter - Formatter function */ sanitizeConfig( options ) { this.logLevel = typeof options.logLevel === 'number' @@ -48,9 +50,9 @@ class Transport { /** * @brief Get an instance of the current transport * - * @property {Object} [options={}] + * @param {Object} [options={}] * - * @return Transport + * @return {Transport} */ static getInstance( options = {} ) { return new this( options ); @@ -59,9 +61,9 @@ class Transport { /** * @brief Returns whether the current log is supported by the transport * - * @property {Log} log + * @param {Log} log * - * @return Boolean + * @return {Boolean} */ supports( log ) { if ( ! ( log instanceof Log ) ) @@ -76,13 +78,11 @@ class Transport { /** * @brief The method that actually logs the data * - * @property {Array} data - * @property {Function} resolve - * @property {Function} reject - * * @private + * @param {Array} data + * @param {Function} resolve + * @param {Function} reject * - * @return void */ _log( data, resolve, reject ) { resolve(); @@ -91,11 +91,10 @@ class Transport { /** * @brief Creates an object to be used in the processors * - * @property {Log} log - * * @private + * @param {Log} log * - * @return Object + * @return {Object} */ _createProcessorsObject( log ) { return { @@ -112,9 +111,9 @@ class Transport { /** * @brief Saves the log * - * @property {Log} logg + * @param {Log} log * - * @return Promise + * @return {Promise} */ log( log ) { return new Promise(( resolve, reject ) => { diff --git a/server/components/logger/loggur.js b/server/components/logger/loggur.js index 66fb2a37..0a2c98b8 100644 --- a/server/components/logger/loggur.js +++ b/server/components/logger/loggur.js @@ -30,8 +30,6 @@ class Loggur { /** * @brief Enables the default logger - * - * @return void */ enableDefault() { this.enableDefaultLogger = true; @@ -39,8 +37,6 @@ class Loggur { /** * @brief Disables the default logger - * - * @return void */ disableDefault() { this.enableDefaultLogger = false; @@ -51,10 +47,10 @@ class Loggur { * * @details Configuration for the logger can be passed here and if valid the logger will be created and added * - * @property {String} loggerId - * @property {Logger|Object} [logger={}] + * @param {String} loggerId + * @param {Logger|Object} [logger={}] * - * @return Boolean + * @return {Boolean} */ addLogger( loggerId, logger = {} ) { if ( typeof logger === 'object' && ! ( logger instanceof Logger ) ) @@ -73,14 +69,14 @@ class Loggur { * * @details Returns false if the logger is not added * - * @property {String} loggerId + * @param {String} loggerId * - * @return Logger|Boolean + * @return {Logger|null} */ getLogger( loggerId ) { let logger = this.loggers[loggerId]; if ( logger === undefined ) - return false; + return null; return logger; } @@ -88,9 +84,9 @@ class Loggur { /** * @brief Create a new logger * - * @property {Object} [loggerConfig={}] + * @param {Object} [loggerConfig={}] * - * @return Logger + * @return {Logger} */ createLogger( loggerConfig = {} ) { return new Logger( loggerConfig, this.uniqueId ); @@ -99,7 +95,7 @@ class Loggur { /** * @brief Returns a single instance of the default logger * - * @return Logger + * @return {Logger} */ getDefaultLogger() { if ( this.defaultLogger === null ) { @@ -115,7 +111,7 @@ class Loggur { /** * @brief Logs the data * - * @return Promise + * @return {Promise} */ log() { const loggersPromises = []; @@ -139,9 +135,7 @@ class Loggur { /** * @brief Sets the Log Level of all the attached Loggers * - * @property {Number} logLevel - * - * @return void + * @param {Number} logLevel */ setLogLevel( logLevel ) { if ( Object.keys( this.loggers ).length !== 0 ) { diff --git a/server/components/mime_type/mime_type.js b/server/components/mime_type/mime_type.js index 34a491d7..e713258e 100644 --- a/server/components/mime_type/mime_type.js +++ b/server/components/mime_type/mime_type.js @@ -5,12 +5,13 @@ const data = require( './mime_types_data' ); */ module.exports = { /** - * Gets a mime type by the extension - * If getFirst is passed, then the first mime type is returned ( in case where there may be more than one mime type per extension ), - * otherwise an array is returned + * @brief Gets a mime type by the extension * - * @property {String} extension - * @property {Boolean} getFirst + * @details If getFirst is passed, then the first mime type is returned ( in case where there may be more than + * one mime type per extension ),otherwise an array is returned + * + * @param {String} extension + * @param {Boolean} getFirst * * @return {Array|String} */ @@ -19,9 +20,9 @@ module.exports = { }, /** - * Searches for an extension given the mimeType + * @brief Searches for an extension given the mimeType * - * @property {String} mimeType + * @param {String} mimeType * * @return {null|String} */ diff --git a/server/components/mime_type/mime_types_data.js b/server/components/mime_type/mime_types_data.js index 4558cc2f..5c2f34b1 100644 --- a/server/components/mime_type/mime_types_data.js +++ b/server/components/mime_type/mime_types_data.js @@ -1,7 +1,7 @@ /** - * List of mime types taken from: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types + * @brief List of mime types taken from: https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP/MIME_types/Common_types * - * @var {Object} + * @var {Object} */ module.exports = { '.arc' : ['application/x-freearc'], @@ -23,7 +23,7 @@ module.exports = { '.gif' : ['image/gif'], '.html' : ['text/html'], '.htm' : ['text/html'], - '.ico' : ['image/vnd.microsoft.icon'], + '.ico' : ['image/x-icon'], '.ics' : ['text/calendar'], '.jar' : ['application/java-archive'], '.jpg' : ['image/jpeg'], diff --git a/server/components/rate_limiter/bucket.js b/server/components/rate_limiter/bucket.js index 2226fee8..dd1be676 100644 --- a/server/components/rate_limiter/bucket.js +++ b/server/components/rate_limiter/bucket.js @@ -8,21 +8,13 @@ const { makeId } = require( '../helpers/unique_id' ); */ class Bucket { /** - * @details Refill Amount is how many tokens to refill after the refillTime - * Refill Time is how often tokens should be renewed - * Max Amount is the max amount of tokens to be kept - * The given data store will be used, if none given an in memory one will be used - * Prefix will be used to prefix all keys in the datastore - * key should be passed if this Bucket wants to connect to another one in the datastore or you want to specify your own key - * dataStoreRefetchInterval will be how often to retry the dataStore in ms, should be 1 or 2 but may be increased if the dataStore can't handle the traffice - * - * @property {Number} [refillAmount=100] - * @property {Number} [refillTime=60] - * @property {Number} [maxAmount=1000] - * @property {String} [prefix=Bucket.DEFAULT_PREFIX] - * @property {String} [key=null] - * @property {DataServer} [dataStore=null] - * @property {Number} [dataStoreRefetchInterval=1] + * @param {Number} [refillAmount=100] - Refill Amount is how many tokens to refill after the refillTime + * @param {Number} [refillTime=60] - Refill Time is how often tokens should be renewed + * @param {Number} [maxAmount=1000] - Max Amount is the max amount of tokens to be kept + * @param {String} [prefix=Bucket.DEFAULT_PREFIX] - Prefix will be used to prefix all keys in the datastore + * @param {String} [key=null] - Key should be passed if this Bucket wants to connect to another one in the datastore or you want to specify your own key + * @param {DataServer} [dataStore=null] - The given data store will be used, if none given an in memory one will be used + * @param {Number} [dataStoreRefetchInterval=1] - dataStoreRefetchInterval will be how often to retry the dataStore in ms, should be 1 or 2 but may be increased if the dataStore can't handle the traffice */ constructor( refillAmount = 100, @@ -72,9 +64,7 @@ class Bucket { /** * @brief Handles promise errors * - * @property {Error} error - * - * @return void + * @param {Error} error */ handleError( error ) { setImmediate(() => { @@ -85,7 +75,9 @@ class Bucket { /** * @brief Creates a unique key that is not present in the data store * - * @return String + * @private + * + * @return {String} */ async _getUniqueKey() { let key = null; @@ -102,7 +94,9 @@ class Bucket { /** * @brief Gets the current value * - * @return Number + * @private + * + * @return {Number} */ async _getValue() { const result = await this.dataStore.get( `${this.key}//value` ).catch( this.handleError ); @@ -118,9 +112,9 @@ class Bucket { /** * @brief Sets the value * - * @property {Number} value + * @private * - * @return void + * @param {Number} value */ async _setValue( value ) { await this.dataStore.set( `${this.key}//value`, value ).catch( this.handleError ); @@ -129,7 +123,9 @@ class Bucket { /** * @brief Gets the current value * - * @return Promise + * @private + * + * @return {Promise} */ async _getLastUpdate() { const result = await this.dataStore.get( `${this.key}//lastUpdate` ).catch( this.handleError ); @@ -146,9 +142,9 @@ class Bucket { /** * @brief Sets the lastUpdate * - * @property {Number} lastUpdate + * @private * - * @return void + * @param {Number} lastUpdate */ async _setLastUpdate( lastUpdate ) { await this.dataStore.set( `${this.key}//lastUpdate`, lastUpdate ).catch( this.handleError ); @@ -157,7 +153,7 @@ class Bucket { /** * @brief Resets the value to the maximum available tokens * - * @return Promise + * @return {Promise} */ async reset() { await this._setValue( this.maxAmount ).catch( this.handleError ); @@ -167,7 +163,9 @@ class Bucket { /** * @brief Fetches new data from the DataStore * - * @return Object + * @private + * + * @return {Object} */ async _fetchData() { const lastUpdate = parseInt( await this._getLastUpdate().catch( this.handleError ) ); @@ -179,7 +177,9 @@ class Bucket { /** * @brief Lock the execution * - * @return Promise + * @private + * + * @return {Promise} */ _lock() { return new Promise( async ( resolve, reject ) => { @@ -190,11 +190,12 @@ class Bucket { /** * @brief Implement a locking mechanism * - * @property {Function} resolve - * @property {Function} reject - * @property {Number} counter + * @private + * @param {Function} resolve + * @param {Function} reject + * @param {Number} counter * - * @return Promise + * @return {Promise} */ async _doLock( resolve, reject, counter = 0 ) { const result = await this.dataStore.lock( `${this.key}//lock` ).catch( this.handleError ); @@ -215,7 +216,9 @@ class Bucket { /** * @brief Unlocks the given key * - * @return Promise + * @private + * + * @return {Promise} */ async _unlock() { await this.dataStore.unlock( `${this.key}//lock` ).catch( this.handleError ); @@ -224,11 +227,12 @@ class Bucket { /** * @brief Gets the current available tokens * + * @private * @details The data does not need to be passed ( it is passed from the reduce function to reduce calls to the data store ) * - * @property {Object} data + * @param {Object} [data=null] * - * @return Promise + * @return {Promise} */ async get( data = null ) { if ( data === null ) @@ -243,9 +247,9 @@ class Bucket { * * @details Resolves to true if there are tokens left otherwise, rejects to false * - * @property {Number} [tokens=1] + * @param {Number} [tokens=1] * - * @return Boolean + * @return {Boolean} */ async reduce( tokens = 1 ) { const lockHandle = await this._lock().catch( this.handleError ); @@ -274,9 +278,9 @@ class Bucket { /** * @brief How much should be refilled given the last update * - * @property {Number} lastUpdate + * @param {Number} lastUpdate * - * @return Number + * @return {Number} */ _refillCount( lastUpdate ) { return Math.floor( ( this._getCurrentTime() - lastUpdate ) / this.refillTime ); @@ -285,7 +289,7 @@ class Bucket { /** * @brief Checks if the bucket has all tokens available * - * @return Boolean + * @return {Boolean} */ async isFull() { return await this.get() === this.maxAmount; @@ -294,7 +298,7 @@ class Bucket { /** * @brief Gets the current timestamp in seconds * - * @return Number + * @return {Number} */ _getCurrentTime() { return Date.now(); diff --git a/server/components/routing/route.js b/server/components/routing/route.js index 24367716..759db772 100644 --- a/server/components/routing/route.js +++ b/server/components/routing/route.js @@ -14,6 +14,7 @@ const DEFAULT_ROUTE_HANDLER = ( event ) => { /** * @brief RegEx used to match routes that need to be parsed + * * @var {RegExp} ROUTE_REGEX */ const ROUTE_REGEX = /^:([^:]+):$/; @@ -34,7 +35,7 @@ class Route { /** * @brief Returns an empty unmatched object to work with * - * @return Object + * @return {Object} */ static getMatchObject() { return { @@ -46,9 +47,7 @@ class Route { /** * @brief Sets Route options * - * @property {Object} routeConfig - * - * @return void + * @param {Object} routeConfig */ sanitize( routeConfig ) { if ( typeof routeConfig !== 'object' || routeConfig === null ) @@ -81,9 +80,9 @@ class Route { * String * Function * - * @property {Object} routeConfig + * @param {Object} routeConfig * - * @return * + * @return {*} */ parseGlobalMiddlewares( routeConfig ) { switch ( true ) { @@ -104,7 +103,7 @@ class Route { /** * @brief Returns the current route * - * @return String|RegExp + * @return {String|RegExp} */ getRoute() { return this.route; @@ -113,7 +112,7 @@ class Route { /** * @brief Returns the current handler * - * @return Function + * @return {Function} */ getHandler() { return this.handler; @@ -122,7 +121,7 @@ class Route { /** * @brief Returns the current method(s) * - * @return Array|String + * @return {Array|String} */ getMethod() { return this.method; @@ -131,7 +130,7 @@ class Route { /** * @brief Returns the middlewares set for the current route * - * @return Array + * @return {Array} */ getMiddlewares() { return this.middlewares; @@ -140,9 +139,9 @@ class Route { /** * @brief Matches the requestedMethod with the route's one * - * @property {String} requestedMethod + * @param {String} requestedMethod * - * @return Boolean + * @return {Boolean} */ matchMethod( requestedMethod ) { requestedMethod = requestedMethod.toUpperCase(); @@ -157,10 +156,10 @@ class Route { * * @details Sets the matchedParams with any parameters found * - * @property {String} requestedRoute - * @property {Object} [matchedParams={}] + * @param {String} requestedRoute + * @param {Object} [matchedParams={}] * - * @return Object + * @return {Object} */ matchPath( requestedRoute, matchedParams = {} ) { if ( requestedRoute === '' ) diff --git a/server/components/routing/router.js b/server/components/routing/router.js index 374000eb..30c26101 100644 --- a/server/components/routing/router.js +++ b/server/components/routing/router.js @@ -26,9 +26,7 @@ class Router extends PluginInterface { /** * @brief Enables or disables caching * - * @property {Boolean} [enable=true] - * - * @return void + * @param {Boolean} [enable=true] */ enableCaching( enable = true ) { this.cachingIsEnabled = enable; @@ -36,8 +34,6 @@ class Router extends PluginInterface { /** * @brief Sets the caching key limit - * - * @return void */ setKeyLimit( ...args ) { this.cache.setKeyLimit.apply( this.cache, args ); @@ -46,10 +42,10 @@ class Router extends PluginInterface { /** * @brief Defines a middleware to be used globally * - * @property {String} middlewareName - * @property {Function} middleware + * @param {String} middlewareName + * @param {Function} middleware * - * @return Router + * @return {Router} */ define( middlewareName, middleware ) { if ( @@ -68,9 +64,7 @@ class Router extends PluginInterface { /** * @brief Attaches methods to the server on runtime * - * @property {Server} server - * - * @return void + * @param {Server} server */ setServerOnRuntime( server ) { this.setUpHttpMethodsToObject( server ); @@ -78,7 +72,7 @@ class Router extends PluginInterface { /** * @brief Function that adds a middleware to the block chain of the router * - * @returns Server + * @returns {Server} */ server.add = ( ...args ) => { this.add.apply( this, args ); @@ -88,11 +82,7 @@ class Router extends PluginInterface { } /** - * @brief Adds .post, .put, .get, .delete methods to the object - * * @details If route is a function then the handler will be treated as middlewares - * - * @return void */ setUpHttpMethodsToObject( object ) { const methods = ['POST', 'PUT', 'GET', 'DELETE', 'HEAD', 'PATCH', 'COPY']; @@ -163,7 +153,7 @@ class Router extends PluginInterface { * * Accepts a route and an instance of a router ( String route, Router router ) * - * @returns Router + * @returns {Router} */ add( ...args ) { let first = args[0]; @@ -196,9 +186,9 @@ class Router extends PluginInterface { /** * @brief This will process the request and return the appropriate block chain * - * @property {EventRequest} event + * @param {EventRequest} event * - * @return Array + * @return {Array} */ getExecutionBlockForCurrentEvent( event ) { const blockKey = `${event.path}${event.method}`; @@ -238,11 +228,11 @@ class Router extends PluginInterface { /** * @brief Gets all the global middlewares for the given route * - * @property {Route} route + * @param {Route} route * * @private * - * @return Array + * @return {Array} */ _getGlobalMiddlewaresForRoute( route ) { const middlewares = []; @@ -273,12 +263,12 @@ class Router extends PluginInterface { * * @details If a path is passed, then that path will be used to prefix all the middlewares * - * @property {Router} router - * @property {String} path + * @param {Router} router + * @param {String} path * * @private * - * @return Router + * @return {Router} */ _concat( router, path = null ) { let middlewares; @@ -323,7 +313,7 @@ class Router extends PluginInterface { /** * @brief Exported for local instances * - * @return Boolean + * @return {Boolean} */ matchMethod() { return Router.matchMethod.apply( Router, arguments ); @@ -332,7 +322,7 @@ class Router extends PluginInterface { /** * @brief Exported for local instances * - * @return Boolean + * @return {Boolean} */ matchRoute() { return Router.matchRoute.apply( Router, arguments ); @@ -343,10 +333,10 @@ class Router extends PluginInterface { * * @details If a string or an array is passed, then it will be converted to a Route * - * @property {String} requestedMethod - * @property {Route|Array|String} method + * @param {String} requestedMethod + * @param {Route|Array|String} method * - * @return Boolean + * @return {Boolean} */ static matchMethod( requestedMethod, method ) { let route; @@ -367,11 +357,11 @@ class Router extends PluginInterface { * * @details Returns bool if there was a successful match * - * @property {String} requestedRoute - * @property {String|RegExp|Route} route - * @property {Object} [matchedParams={}] + * @param {String} requestedRoute + * @param {String|RegExp|Route} route + * @param {Object} [matchedParams={}] * - * @return Boolean + * @return {Boolean} */ static matchRoute( requestedRoute, route, matchedParams = {} ) { if ( typeof route === 'string' || route instanceof RegExp ) diff --git a/server/components/routing/router_cache.js b/server/components/routing/router_cache.js index 83a6d83e..62689b42 100644 --- a/server/components/routing/router_cache.js +++ b/server/components/routing/router_cache.js @@ -15,9 +15,7 @@ class RouterCache { /** * @brief Sets the caching key limit * - * @property {Number} [keyLimit=5000] - * - * @return void + * @param {Number} [keyLimit=5000] */ setKeyLimit( keyLimit = RouterCache.DEFAULT_KEY_LIMIT ) { this.keyLimit = keyLimit; @@ -29,7 +27,7 @@ class RouterCache { * @details If the key is nto cached, then null will be returned. * This will trigger a cache clear first * - * @property {String} key + * @param {String} key * * @return {Object|null} */ @@ -45,11 +43,11 @@ class RouterCache { /** * @brief Renews the block's date * - * @property {Object} block + * @param {Object} block * * @private * - * @return Object + * @return {Object} */ _renewBlock( block ) { block.date = Date.now(); @@ -60,9 +58,7 @@ class RouterCache { /** * @brief Removes the key if it is set * - * @property {String} key - * - * @return void + * @param {String} key */ deleteBlock( key ) { delete this._cache[key]; @@ -71,8 +67,8 @@ class RouterCache { /** * @brief Sets a block, given a key * - * @property {string} key - * @property {Object} block + * @param {string} key + * @param {Object} block * * @return {Object} */ @@ -86,10 +82,8 @@ class RouterCache { * @details ttl is the amount of time in milliseconds a key has to be inactive to be deleted * This function will only attempt to clear once in the given interval of time: debounceInterval * - * @property {Number} [ttl=3600000] - * @property {Number} [debounceInterval=60000] - * - * @return void + * @param {Number} [ttl=3600000] + * @param {Number} [debounceInterval=60000] */ clear( ttl = this.ttl, debounceInterval = this.cacheClearDebounce ) { if ( this.lastClearCacheAttempt + debounceInterval > Date.now() ) @@ -112,7 +106,7 @@ class RouterCache { * * @details If the keyLimit is set to 0 then the cache will have an unlimited size * - * @return Boolean + * @return {Boolean} */ isFull() { if ( this.keyLimit === 0 ) diff --git a/server/components/security/content_security_policy.js b/server/components/security/content_security_policy.js index ffe6a8a4..d7ea93f3 100644 --- a/server/components/security/content_security_policy.js +++ b/server/components/security/content_security_policy.js @@ -53,9 +53,7 @@ class ContentSecurityPolicy { /** * @brief Parses the given options and sets the different directives in keys * - * @property {Object} options - * - * @return void + * @param {Object} options */ parseOptions( options ) { this.setEnabled( options['enabled'] ); @@ -95,8 +93,6 @@ class ContentSecurityPolicy { /** * @brief Enables xss protection - * - * @return void */ xss() { this.addDefaultSrc( 'none' ); @@ -115,9 +111,7 @@ class ContentSecurityPolicy { } /** - * @property {String} mimeType - * - * @return void + * @param {String} mimeType */ allowPluginType( mimeType ) { if ( MIME_TYPE_REGEXP.test( mimeType ) ) @@ -127,9 +121,7 @@ class ContentSecurityPolicy { /** * @brief Sets the component's to either be enabled or not * - * @property {Boolean} [enabled=true] - * - * @return void + * @param {Boolean} [enabled=true] */ setEnabled( enabled = true ) { this.enabled = typeof enabled === 'boolean' ? enabled : true; @@ -138,7 +130,7 @@ class ContentSecurityPolicy { /** * @brief Gets the header according to whether CSP is set to report only * - * @return String + * @return {String} */ getHeader() { return this.reportOnly ? REPORT_ONLY_HEADER_NAME : HEADER_NAME; @@ -147,9 +139,7 @@ class ContentSecurityPolicy { /** * @brief Sets the header to be in report only mode * - * @property {String} uri - * - * @return void + * @param {String} uri */ setReportOnly( uri ) { if ( typeof uri !== 'string' || uri === '' ) @@ -165,9 +155,7 @@ class ContentSecurityPolicy { * * @details The report-uri header won't be added for you, you have to specify that yourself * - * @property {String} uri - * - * @return void + * @param {String} uri */ setReportOnlyWithReportTo( uri ) { if ( typeof uri !== 'string' || uri === '' ) @@ -179,95 +167,77 @@ class ContentSecurityPolicy { } /** - * @return void + * @brief Adds sandbox directive */ enableSandbox() { this._addDirective( SANDBOX_KEY ); } /** - * @return void + * @brief Adds upgrade insecure requests directive */ upgradeInsecureRequests() { this._addDirective( UPGRADE_INSECURE_REQUESTS_JEY ); } /** - * @property {String} value - * - * @return void + * @param {String} value */ allowSandboxValue( value ) { this._addDirective( SANDBOX_KEY, value ); } /** - * @property {String} uri - * - * @return void + * @param {String} uri */ addBaseUri( uri ) { this._addDirective( BASE_URI_KEY, this._decorateFetchDirectiveSource( uri ) ); } /** - * @property {String} uri - * - * @return void + * @param {String} uri */ restrictFormActionUrl( uri ) { this._addDirective( FORM_ACTION_KEY, this._decorateFetchDirectiveSource( uri ) ); } /** - * @property {String} uri - * - * @return void + * @param {String} uri */ addFrameAncestors( uri ) { this._addDirective( FRAME_ANCESTORS_KEY, this._decorateFetchDirectiveSource( uri ) ); } /** - * @property {String} source - * - * @return void + * @param {String} source */ addScriptSrc( source ) { this._addDirective( SCRIPT_SRC_KEY, this._decorateFetchDirectiveSource( source ) ); } /** - * @property {String} source - * - * @return void + * @param {String} source */ addImgSrc( source ) { this._addDirective( IMAGE_SRC_KEY, this._decorateFetchDirectiveSource( source ) ); } /** - * @property {String} source - * - * @return void + * @param {String} source */ addChildSrc( source ) { this._addDirective( CHILD_SRC_KEY, this._decorateFetchDirectiveSource( source ) ); } /** - * @property {String} source - * - * @return void + * @param {String} source */ addConnectSrc( source ) { this._addDirective( CONNECT_SRC_KEY, this._decorateFetchDirectiveSource( source ) ); } /** - * @property {String} source - * - * @return void + * @param {String} source */ addDefaultSrc( source ) { this._addDirective( DEFAULT_SRC_KEY, this._decorateFetchDirectiveSource( source ) ); @@ -275,62 +245,48 @@ class ContentSecurityPolicy { /** * @brief Enables all src for self only - * - * @return void */ enableSelf() { this._addDirective( DEFAULT_SRC_KEY, "'self'" ); } /** - * @property {String} source - * - * @return void + * @param {String} source */ addFontSrc( source ) { this._addDirective( FONT_SRC_KEY, this._decorateFetchDirectiveSource( source ) ); } /** - * @property {String} source - * - * @return void + * @param {String} source */ addFrameSrc( source ) { this._addDirective( FRAME_SRC_KEY, this._decorateFetchDirectiveSource( source ) ); } /** - * @property {String} source - * - * @return void + * @param {String} source */ addManifestSrc( source ) { this._addDirective( MANIFEST_SRC_KEY, this._decorateFetchDirectiveSource( source ) ); } /** - * @property {String} source - * - * @return void + * @param {String} source */ addMediaSrc( source ) { this._addDirective( MEDIA_SRC_KEY, this._decorateFetchDirectiveSource( source ) ); } /** - * @property {String} source - * - * @return void + * @param {String} source */ addObjectSrc( source ) { this._addDirective( OBJECT_SRC_KEY, this._decorateFetchDirectiveSource( source ) ); } /** - * @property {String} source - * - * @return void + * @param {String} source */ addStyleSrc( source ) { this._addDirective( STYLE_SRC_KEY, this._decorateFetchDirectiveSource( source ) ); @@ -339,7 +295,7 @@ class ContentSecurityPolicy { /** * @brief Builds the CSP header * - * @return String + * @return {String} */ build() { if ( ! this.enabled ) @@ -376,9 +332,9 @@ class ContentSecurityPolicy { * * @details Adds quotes when needed * - * @property {String} source + * @param {String} source * - * @return String + * @return {String} */ _decorateFetchDirectiveSource( source ) { if ( DIRECTIVES_SPECIAL_ARGUMENTS.includes( source ) ) @@ -390,10 +346,8 @@ class ContentSecurityPolicy { /** * @brief Adds a new directive * - * @property {String} directive - * @property {String} [value=''] - * - * @return void + * @param {String} directive + * @param {String} [value=''] */ _addDirective( directive, value = '' ) { if ( typeof this.directives[directive] === 'undefined' ) diff --git a/server/components/security/content_type_options.js b/server/components/security/content_type_options.js index 72a8c61d..2d7c7650 100644 --- a/server/components/security/content_type_options.js +++ b/server/components/security/content_type_options.js @@ -3,7 +3,7 @@ /** * @brief Name of the X-Content-Type-Options header * - * @var String + * @var {String} */ const HEADER_NAME = 'X-Content-Type-Options'; @@ -18,9 +18,7 @@ class ContentTypeOptions { /** * @brief Parses the options given to the ContentTypeOptions class * - * @property {Object} options - * - * @return void + * @param {Object} options */ parseOptions( options = {} ) { this.setEnabled( options.enabled ); @@ -29,9 +27,7 @@ class ContentTypeOptions { /** * @brief Sets the component's to either be enabled or not * - * @property {Boolean} [enabled=true] - * - * @return void + * @param {Boolean} [enabled=true] */ setEnabled( enabled = true ) { this.enabled = typeof enabled === 'boolean' ? enabled : true; @@ -40,7 +36,7 @@ class ContentTypeOptions { /** * @brief Returns the header name * - * @return String + * @return {String} */ getHeader() { return HEADER_NAME; @@ -49,7 +45,7 @@ class ContentTypeOptions { /** * @brief Builds the header * - * @return String + * @return {String} */ build() { if ( ! this.enabled ) diff --git a/server/components/security/expect_ct.js b/server/components/security/expect_ct.js index db8ab0df..52bb64fa 100644 --- a/server/components/security/expect_ct.js +++ b/server/components/security/expect_ct.js @@ -6,7 +6,7 @@ * * @details One day in seconds * - * @var Number + * @var {Number} */ const DEFAULT_MAX_AGE = 86400; const DEFAULT_ENFORCE = true; @@ -15,7 +15,7 @@ const DEFAULT_REPORT_URI = ''; /** * @brief Name of the Expect-CT header * - * @var String + * @var {String} */ const HEADER_NAME = 'Expect-CT'; @@ -40,9 +40,7 @@ class ExpectCT { /** * @brief Parses the options given to the ExpectCT class * - * @property {Object} [options={}] - * - * @return void + * @param {Object} [options={}] */ parseOptions( options = {} ) { this.setEnabled( options.enabled ); @@ -63,9 +61,7 @@ class ExpectCT { /** * @brief Sets the component's to either be enabled or not * - * @property {Boolean} [enabled=true] - * - * @return void + * @param {Boolean} [enabled=true] */ setEnabled( enabled = true ) { this.enabled = typeof enabled === 'boolean' ? enabled : true; @@ -74,9 +70,7 @@ class ExpectCT { /** * @brief Sets the enforce flag * - * @property {Boolean} [enforce=true] - * - * @return void + * @param {Boolean} [enforce=true] */ enforce( enforce = true ) { this.isEnforce = typeof enforce === 'boolean' ? enforce : this.isEnforce; @@ -85,9 +79,7 @@ class ExpectCT { /** * @brief Sets the enforce flag * - * @property {Number} maxAge - * - * @return void + * @param {Number} maxAge */ setMaxAge( maxAge ) { this.maxAge = typeof maxAge === 'number' ? maxAge : this.maxAge; @@ -96,9 +88,7 @@ class ExpectCT { /** * @brief Sets the reportUri * - * @property {String} reportUri - * - * @return void + * @param {String} reportUri */ setReportUri( reportUri ) { this.reportUri = typeof reportUri === 'string' ? reportUri : this.reportUri; @@ -107,7 +97,7 @@ class ExpectCT { /** * @brief Returns the header name * - * @return String + * @return {String} */ getHeader() { return HEADER_NAME; @@ -116,7 +106,7 @@ class ExpectCT { /** * @brief Builds the header * - * @return String + * @return {String} */ build() { if ( ! this.enabled ) diff --git a/server/components/security/http_strict_transport_security.js b/server/components/security/http_strict_transport_security.js index 0e550293..9684145b 100644 --- a/server/components/security/http_strict_transport_security.js +++ b/server/components/security/http_strict_transport_security.js @@ -5,7 +5,7 @@ * * @details One year in seconds * - * @var Number + * @var {Number} */ const DEFAULT_MAX_AGE = 31536000; const DEFAULT_INCLUDE_SUB_DOMAINS = false; @@ -14,7 +14,7 @@ const DEFAULT_PRELOAD = false; /** * @brief Name of the HSTS header * - * @var String + * @var {String} */ const HEADER_NAME = 'Strict-Transport-Security'; @@ -39,9 +39,7 @@ class HttpStrictTransportSecurity { /** * @brief Parses the options given to the HSTS class * - * @property {Object} [options={}] - * - * @return void + * @param {Object} [options={}] */ parseOptions( options = {} ) { this.setEnabled( options.enabled ); @@ -62,9 +60,7 @@ class HttpStrictTransportSecurity { /** * @brief Sets the component's to either be enabled or not * - * @property {Boolean} [enabled=true] - * - * @return void + * @param {Boolean} [enabled=true] */ setEnabled( enabled = true ) { this.enabled = typeof enabled === 'boolean' ? enabled : true; @@ -73,9 +69,7 @@ class HttpStrictTransportSecurity { /** * @brief Sets the component's to either be preloaded or not * - * @property {Boolean} [preload=true] - * - * @return void + * @param {Boolean} [preload=true] */ preload( preload = true ) { this.doPreload = typeof preload === 'boolean' ? preload : this.doPreload; @@ -84,9 +78,7 @@ class HttpStrictTransportSecurity { /** * @brief Sets the enforce flag * - * @property {Number} maxAge - * - * @return void + * @param {Number} maxAge */ setMaxAge( maxAge ) { this.maxAge = typeof maxAge === 'number' ? maxAge : this.maxAge; @@ -95,9 +87,7 @@ class HttpStrictTransportSecurity { /** * @brief Enable or disable includeSubDomains * - * @property {Boolean} [include=true] - * - * @return void + * @param {Boolean} [include=true] */ includeSubDomains( include = true ) { this.doIncludeSubDomains = typeof include === 'boolean' ? include : this.doIncludeSubDomains; @@ -106,7 +96,7 @@ class HttpStrictTransportSecurity { /** * @brief Returns the header name * - * @return String + * @return {String} */ getHeader() { return HEADER_NAME; @@ -115,7 +105,7 @@ class HttpStrictTransportSecurity { /** * @brief Builds the header * - * @return String + * @return {String} */ build() { if ( ! this.enabled ) diff --git a/server/components/session/session.js b/server/components/session/session.js index 95683b14..ba54a074 100644 --- a/server/components/session/session.js +++ b/server/components/session/session.js @@ -5,7 +5,7 @@ const uniqueId = require( './../helpers/unique_id' ); /** * @details Time the session should be kept. Defaults to 90 days * - * @var Number TTL + * @var {Number} TTL */ const TTL = 7776000; @@ -50,7 +50,7 @@ class Session { * Initializes the session. This must be called before anything else. The other methods do not check if this has been called * intentionally to save on some speed. * - * @return {Promise} + * @return {Promise} */ async init() { this.sessionId = this.isCookieSession ? @@ -66,7 +66,7 @@ class Session { /** * @brief Creates a new SessionId * - * @return String + * @return {String} */ _makeNewSessionId() { return uniqueId.makeId( this.sessionIdLength ); @@ -75,7 +75,7 @@ class Session { /** * @brief Checks if the user has a session * - * @return Boolean + * @return {Boolean} */ async hasSession() { if ( this.sessionId === null ) @@ -86,8 +86,6 @@ class Session { /** * @brief Removes the session from the caching server - * - * @return void */ async removeSession() { await this.server.delete( Session.SESSION_PREFIX + this.sessionId ); @@ -100,10 +98,9 @@ class Session { } /** - * Starts a new session. - * Returns the sessionId or null on error. + * @brief Starts a new session. * - * @return void + * @details Returns the sessionId or null on error. */ async newSession() { this.sessionId = this._makeNewSessionId(); @@ -119,14 +116,12 @@ class Session { } /** - * Adds a new variable to the session + * @brief Adds a new variable to the session * * @deprecated Use set instead * - * @property {String} name - * @property {*} value - * - * @return void + * @param {String} name + * @param {*} value */ add( name, value ) { this.session[name] = value; @@ -135,9 +130,7 @@ class Session { /** * @brief Deletes a variable from the session * - * @property {String} name - * - * @return void + * @param {String} name */ delete( name ) { delete this.session[name]; @@ -146,21 +139,22 @@ class Session { /** * @brief Checks if a variable exists in the session * - * @property {String} name + * @param {String} name * - * @return Boolean + * @return {Boolean} */ has( name ) { return typeof this.session[name] !== 'undefined'; } /** - * Gets a session variable. - * Returns null if the value does not exist. + * @brief Gets a session variable. * - * @property {String} name + * @details Returns null if the value does not exist. * - * @return * + * @param {String} name + * + * @return {*} */ get( name ) { if ( ! this.has( name ) ) @@ -170,7 +164,7 @@ class Session { } /** - * Gets all session variables. + * @brief Gets all session variables. * * @return {Object} */ @@ -179,10 +173,11 @@ class Session { } /** - * Save the session to the memory storage. - * Returns true if the session was saved successfully. + * @brief Save the session to the memory storage. + * + * @details Returns true if the session was saved successfully. * - * @return Boolean + * @return {Boolean} */ async saveSession() { if ( ! this.session || ! this.sessionId ) @@ -192,10 +187,11 @@ class Session { } /** - * Fetches the session if it exists - * Returns the session if it exists, otherwise return null + * @brief Fetches the session if it exists + * + * @details Returns the session if it exists, otherwise return null * - * @return Boolean + * @return {Boolean} */ async fetchSession() { if ( ! await this.server.touch( Session.SESSION_PREFIX + this.sessionId ) ) @@ -207,7 +203,7 @@ class Session { /** * @brief Returns the sessionId * - * @return String + * @return {String} */ getSessionId() { return this.sessionId; @@ -217,7 +213,7 @@ class Session { /** * @brief Default prefix set before every key that is set in the store * - * @var String SESSION_PREFIX + * @var {String} SESSION_PREFIX */ Session.SESSION_PREFIX = '$S:'; diff --git a/server/components/templating_engine/default_templating_engine.js b/server/components/templating_engine/default_templating_engine.js index 2b29c464..d898a41e 100644 --- a/server/components/templating_engine/default_templating_engine.js +++ b/server/components/templating_engine/default_templating_engine.js @@ -9,8 +9,8 @@ class TemplatingEngine { /** * @brief Return the HTML directly * - * @property {String} html - * @property {Object} variables + * @param {String} html + * @param {Object} variables * * @returns {String} */ @@ -21,10 +21,10 @@ class TemplatingEngine { /** * @brief Reads and renders a html file * - * @property {String} templateLocation - * @property {Object} variables + * @param {String} templateLocation + * @param {Object} variables * - * @return {Promise} + * @return {String} */ async renderFile( templateLocation, variables ) { const data = await readFile( templateLocation ); diff --git a/server/components/templating_engine/experimental_templating_engine.js b/server/components/templating_engine/experimental_templating_engine.js index d84ac67c..2c6206c2 100644 --- a/server/components/templating_engine/experimental_templating_engine.js +++ b/server/components/templating_engine/experimental_templating_engine.js @@ -29,8 +29,8 @@ class TemplatingEngine extends DefaultTemplatingEngine { /** * @brief Renders a template given specific variables * - * @property {String} template - * @property {Object} variables + * @param {String} template + * @param {Object} variables * * @return {String} */ @@ -41,11 +41,9 @@ class TemplatingEngine extends DefaultTemplatingEngine { /** * @brief Builder function for the template * - * @property line String - * @property isJs Boolean - * @property insertDirectly Boolean - * - * @return void + * @param {String} line + * @param {Boolean} isJs + * @param {Boolean} insertDirectly */ const addCode = ( line, isJs, insertDirectly = false ) => { if ( isJs ) { diff --git a/server/components/validation/validation_attribute.js b/server/components/validation/validation_attribute.js index a2e79f03..23573ed2 100644 --- a/server/components/validation/validation_attribute.js +++ b/server/components/validation/validation_attribute.js @@ -83,9 +83,9 @@ class ValidationAttribute { /** * @brief Validates each rule separately * - * @property {String} rule - * @property {Number} index - * @property {Object} params + * @param {String} rule + * @param {Number} index + * @param {Object} params * * @return String|Boolean */ @@ -248,7 +248,7 @@ class ValidationAttribute { /** * @brief Splits the rule additionally and returns any params found * - * @property {String} rule + * @param {String} rule * * @return Object */ diff --git a/server/components/validation/validation_handler.js b/server/components/validation/validation_handler.js index 151f036d..9b7938cf 100644 --- a/server/components/validation/validation_handler.js +++ b/server/components/validation/validation_handler.js @@ -7,8 +7,8 @@ module.exports = { /** * @brief Validates the given object and returns validation results for each object property * - * @property {Object} validationInput - * @property {Object} skeleton + * @param {Object} validationInput + * @param {Object} skeleton * * @return ValidationResult */ diff --git a/server/components/validation/validation_result.js b/server/components/validation/validation_result.js index 1bfecf63..35c81fba 100644 --- a/server/components/validation/validation_result.js +++ b/server/components/validation/validation_result.js @@ -7,8 +7,8 @@ const ValidationAttribute = require( './validation_attribute' ); */ class ValidationResult { /** - * @property {Object} validationInput - * @property {Object} skeleton + * @param {Object} validationInput + * @param {Object} skeleton */ constructor( validationInput, skeleton ) { this.validationInput = validationInput; @@ -43,9 +43,9 @@ class ValidationResult { /** * @brief Forms the result using recursion * - * @property {Object} validationInput - * @property {Object} skeleton - * @property {Object} failures + * @param {Object} validationInput + * @param {Object} skeleton + * @param {Object} failures * * @private * @@ -116,7 +116,7 @@ class ValidationResult { * * @details If $default or $rules are set, that means that the object is an instructional object for the ValidationAttribute * - * @property {Object} rules + * @param {Object} rules * * @private * @@ -131,7 +131,7 @@ class ValidationResult { * * @details This is done because if we want to validate an array of arrays this is the way that the data is passed to be validated * - * @property {*} array + * @param {*} array * * @private * @@ -144,7 +144,7 @@ class ValidationResult { /** * @brief Sanitizes the failures object to not report any empty properties * - * @property {Object} failures + * @param {Object} failures * * @private * diff --git a/server/components/validation/validation_rules.js b/server/components/validation/validation_rules.js index 1a7edaf8..928695d4 100644 --- a/server/components/validation/validation_rules.js +++ b/server/components/validation/validation_rules.js @@ -6,7 +6,7 @@ let assert = {}; /** * @brief Gets the type of the value * - * @property {*} value + * @param {*} value * * @return String */ @@ -17,7 +17,7 @@ function getType( value ) { /** * @brief Gets the array of the value * - * @property {*} value + * @param {*} value * * @return Number */ @@ -48,8 +48,8 @@ const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+" /** * @brief Assert if the two values are equal ignoring type coercion * - * @property {*} actual - * @property {*} expected + * @param {*} actual + * @param {*} expected * * @return Boolean */ @@ -60,8 +60,8 @@ assert.assertEqual = ( actual, expected ) => { /** * @brief Assert if the two values are equal acknowledges type coercion * - * @property {*} actual - * @property {*} expected + * @param {*} actual + * @param {*} expected * * @return Boolean */ @@ -72,8 +72,8 @@ assert.assertStrictEqual = ( actual, expected ) => { /** * @brief Assert if the two values are NOT equal ignoring type coercion * - * @property {*} actual - * @property {*} expected + * @param {*} actual + * @param {*} expected * * @return Boolean */ @@ -84,8 +84,8 @@ assert.assertNotEqual = ( actual, expected ) => { /** * @brief Assert if the two values are NOT equal acknowledges type coercion * - * @property {*} actual - * @property {*} expected + * @param {*} actual + * @param {*} expected * * @return Boolean */ @@ -96,7 +96,7 @@ assert.assertStrictNotEqual = ( actual, expected ) => { /** * @brief Assert that the given value is a string * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -107,7 +107,7 @@ assert.assertIsString = ( actual ) => { /** * @brief Assert that the given value is NOT a string * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -118,7 +118,7 @@ assert.assertNotString = ( actual ) => { /** * @brief Assert that the given value is a number * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -131,7 +131,7 @@ assert.assertIsNumeric = ( actual ) => { /** * @brief Asserts that the given value is NOT a number * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -142,7 +142,7 @@ assert.assertNotNumeric = ( actual ) => { /** * @brief Asserts that the given value is an array * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -153,7 +153,7 @@ assert.assertIsArray = ( actual ) => { /** * @brief Asserts that the given value is NOT an array * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -166,7 +166,7 @@ assert.assertNotArray = ( actual ) => { * * @details Will check for an empty String, empty Object or empty Array * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -183,7 +183,7 @@ assert.assertIsEmpty = ( actual ) => { * * @details Will check for a non empty String, non empty Object and non empty Array * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -203,7 +203,7 @@ assert.assertNotEmpty = ( actual ) => { /** * @brief Assert that the given value is a Date Object or a value that can be cast to a date * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -214,7 +214,7 @@ assert.assertIsDate = ( actual ) => { /** * @brief Assert that the given value is a Date Object * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -225,7 +225,7 @@ assert.assertIsDateObject = ( actual ) => { /** * @brief Assert that the given value is NOT a Date Object or a value that can be cast to a date * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -236,7 +236,7 @@ assert.assertNotDate = ( actual ) => { /** * @brief Assert that the given value is NOT a Date Object * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -247,8 +247,8 @@ assert.assertNotDateObject = ( actual ) => { /** * @brief Assert that the given value is the given internal type like: string, number, array etc * - * @property {*} actual - * @property {String} internalType + * @param {*} actual + * @param {String} internalType * * @return Boolean */ @@ -259,8 +259,8 @@ assert.assertIsInternalType = ( actual, internalType ) => { /** * @brief Assert that the given value is NOT the given internal type like: string, number, array etc * - * @property {*} actual - * @property {String} internalType + * @param {*} actual + * @param {String} internalType * * @return Boolean */ @@ -271,7 +271,7 @@ assert.assertNotInternalType = ( actual, internalType ) => { /** * @brief Asserts that the given value is a valid email address * - * @property {String} actual + * @param {String} actual * * @return Boolean */ @@ -282,7 +282,7 @@ assert.assertIsValidEmail = ( actual ) => { /** * @brief Asserts that the given value is NOT a valid email address * - * @property {String} actual + * @param {String} actual * * @return Boolean */ @@ -293,8 +293,8 @@ assert.assertNotValidEmail = ( actual ) => { /** * @brief Asserts that the given value is bigger than the given comparator * - * @property {*} actual - * @property {*} comparator + * @param {*} actual + * @param {*} comparator * * @return Boolean */ @@ -305,8 +305,8 @@ assert.assertBiggerThan = ( actual, comparator ) => { /** * @brief Asserts that the given value is bigger or equal in regards to the given comparator * - * @property {*} actual - * @property {*} comparator + * @param {*} actual + * @param {*} comparator * * @return Boolean */ @@ -317,8 +317,8 @@ assert.assertBiggerOrEqual = ( actual, comparator ) => { /** * @brief Asserts that the given value is smaller than the given comparator * - * @property {*} actual - * @property {*} comparator + * @param {*} actual + * @param {*} comparator * * @return Boolean */ @@ -329,8 +329,8 @@ assert.assertSmallerThan = ( actual, comparator ) => { /** * @brief Asserts that the given value is smaller or equal in regards to the given comparator * - * @property {*} actual - * @property {*} comparator + * @param {*} actual + * @param {*} comparator * * @return Boolean */ @@ -341,7 +341,7 @@ assert.assertSmallerOrEqual = ( actual, comparator ) => { /** * @brief Assert that the given value is a Boolean * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -354,7 +354,7 @@ assert.assertIsBoolean = ( actual ) => { /** * @brief Assert that the given value is NOT a Boolean * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -365,7 +365,7 @@ assert.assertNotBoolean = ( actual ) => { /** * @brief Asserts that the given value is or casts to TRUE * - * @property {*} actual + * @param {*} actual * * @return Boolean */ @@ -385,7 +385,7 @@ assert.assertTrue = ( actual ) => { /** * @brief Asserts that the given value is or casts to FALSE * - * @property {*} actual + * @param {*} actual * * @return Boolean */ diff --git a/server/event_request.js b/server/event_request.js index 7678b82b..785d7d93 100644 --- a/server/event_request.js +++ b/server/event_request.js @@ -11,8 +11,8 @@ const ValidationHandler = require( './components/validation/validation_handler' */ class EventRequest extends EventEmitter { /** - * @property {IncomingMessage} request - * @property {ServerResponse} response + * @param {IncomingMessage} request + * @param {ServerResponse} response */ constructor( request, response ) { super(); @@ -90,7 +90,7 @@ class EventRequest extends EventEmitter { /** * @brief Easier access to the validation * - * @property {*} args + * @param {*} args * * @return ValidationResult */ @@ -105,9 +105,9 @@ class EventRequest extends EventEmitter { * The options should be an object where all the keys will be taken as is as well as the values * And they will be used to make an cookie header * - * @property {String} name - * @property {String} value - * @property {Object} [options={}] + * @param {String} name + * @param {String} value + * @param {Object} [options={}] * * @return Boolean */ @@ -149,8 +149,8 @@ class EventRequest extends EventEmitter { } /** - * @property {*} [response=''] - * @property {Number} [code=null] + * @param {*} [response=''] + * @param {Number} [code=null] * * @return Promise */ @@ -171,7 +171,7 @@ class EventRequest extends EventEmitter { /** * @brief Formats the response to be sent * - * @property {String|Buffer} response + * @param {String|Buffer} response * * @return {String|Buffer} */ @@ -194,8 +194,8 @@ class EventRequest extends EventEmitter { /** * @brief Safely set header to response ( only if response is not sent ) * - * @property {String} key - * @property {String} value + * @param {String} key + * @param {String} value * * @return EventRequest */ @@ -209,7 +209,7 @@ class EventRequest extends EventEmitter { /** * @brief Removes a set header * - * @property {String} key + * @param {String} key * * @return EventRequest */ @@ -225,8 +225,8 @@ class EventRequest extends EventEmitter { * * @details If the key does not exist, then return the default value if passed. Defaults to NULL * - * @property {String} key - * @property {String} [defaultValue=null] + * @param {String} key + * @param {String} [defaultValue=null] * * @return String */ @@ -252,7 +252,7 @@ class EventRequest extends EventEmitter { /** * @brief Checks if the desired header exists * - * @property {String} key + * @param {String} key * * @return Boolean */ @@ -263,7 +263,7 @@ class EventRequest extends EventEmitter { /** * @brief Sets the status code of the response * - * @property {Number} code + * @param {Number} code * * @return EventRequest */ @@ -276,8 +276,8 @@ class EventRequest extends EventEmitter { /** * @brief Used to send a redirect response to a given redirectUrl * - * @property {String} redirectUrl - * @property {Number} [statusCode=302] + * @param {String} redirectUrl + * @param {Number} [statusCode=302] * * @return void */ @@ -305,7 +305,7 @@ class EventRequest extends EventEmitter { /** * @brief Sets the current execution block * - * @property {Array} block + * @param {Array} block * * @return void */ @@ -320,8 +320,8 @@ class EventRequest extends EventEmitter { * if the event is stopped and the response has not been set then send a server error * This function is wrapped by the next() function * - * @property {*} err - * @property {Number} code + * @param {*} err + * @param {Number} code * * @return void */ @@ -364,7 +364,7 @@ class EventRequest extends EventEmitter { * * @details By default handleError is asynchronous * - * @property {Array} args + * @param {Array} args * * @return void */ diff --git a/server/plugins/available_plugins/body_parser_plugin.js b/server/plugins/available_plugins/body_parser_plugin.js index 570d6814..10ee5bd7 100644 --- a/server/plugins/available_plugins/body_parser_plugin.js +++ b/server/plugins/available_plugins/body_parser_plugin.js @@ -4,9 +4,9 @@ const PluginInterface = require( './../plugin_interface' ); class BodyParserPlugin extends PluginInterface { /** - * @property {JsonBodyParser|MultipartDataParser|RawBodyParser|FormBodyParser} parser - * @property {String} pluginId - * @property {Object} [options={}] + * @param {JsonBodyParser|MultipartDataParser|RawBodyParser|FormBodyParser} parser + * @param {String} pluginId + * @param {Object} [options={}] */ constructor( parser, pluginId, options = {} ) { super( pluginId, options ); @@ -20,7 +20,7 @@ class BodyParserPlugin extends PluginInterface { /** * @brief Set the parser if given * - * @property {Object} [options={}] + * @param {Object} [options={}] * * @return void */ diff --git a/server/plugins/available_plugins/cache_control_plugin.js b/server/plugins/available_plugins/cache_control_plugin.js index 9a656576..f6c1758f 100644 --- a/server/plugins/available_plugins/cache_control_plugin.js +++ b/server/plugins/available_plugins/cache_control_plugin.js @@ -16,7 +16,7 @@ class CacheControlPlugin extends PluginInterface { /** * @brief Dynamic Middleware that will add a cache header to the current request with the options provided * - * @property {Object} [options={}] + * @param {Object} [options={}] * * @return Function */ diff --git a/server/plugins/available_plugins/cors_plugin.js b/server/plugins/available_plugins/cors_plugin.js index 85cc014d..98f3eda6 100644 --- a/server/plugins/available_plugins/cors_plugin.js +++ b/server/plugins/available_plugins/cors_plugin.js @@ -7,8 +7,8 @@ const PluginInterface = require( '../plugin_interface' ); */ class CorsPlugin extends PluginInterface { /** - * @property {String} pluginId - * @property {Object} options + * @param {String} pluginId + * @param {Object} options */ constructor( pluginId, options = {} ) { super( pluginId, options ); @@ -16,7 +16,7 @@ class CorsPlugin extends PluginInterface { } /** - * @property {Object} options + * @param {Object} options */ setOptions( options = {} ) { super.setOptions( options ); @@ -53,7 +53,7 @@ class CorsPlugin extends PluginInterface { /** * @brief Applies all the CORS headers to the response * - * @property {EventRequest} event + * @param {EventRequest} event * * @return void */ diff --git a/server/plugins/available_plugins/data_server_plugin.js b/server/plugins/available_plugins/data_server_plugin.js index 1db9c553..73622eb4 100644 --- a/server/plugins/available_plugins/data_server_plugin.js +++ b/server/plugins/available_plugins/data_server_plugin.js @@ -32,7 +32,7 @@ class DataServerPlugin extends PluginInterface { /** * @brief Uses Duck-Typing to check if the Data Server is a valid data server * - * @property {Object} dataServer + * @param {Object} dataServer * * @return {boolean} */ diff --git a/server/plugins/available_plugins/env_plugin.js b/server/plugins/available_plugins/env_plugin.js index 29194554..ba8ec29d 100644 --- a/server/plugins/available_plugins/env_plugin.js +++ b/server/plugins/available_plugins/env_plugin.js @@ -32,7 +32,7 @@ class EnvPlugin extends PluginInterface { /** * @brief Loads the env variables on runtime * - * @property {Server} server + * @param {Server} server * * @return void */ diff --git a/server/plugins/available_plugins/etag_plugin.js b/server/plugins/available_plugins/etag_plugin.js index a89b7d04..c87d75b0 100644 --- a/server/plugins/available_plugins/etag_plugin.js +++ b/server/plugins/available_plugins/etag_plugin.js @@ -13,8 +13,8 @@ const IF_MATCH_CONDITIONAL_HEADER_NAME = 'If-Match'; */ class EtagPlugin extends PluginInterface { /** - * @property {String} pluginId - * @property {Object} options + * @param {String} pluginId + * @param {Object} options */ constructor( pluginId, options = {} ) { super( pluginId, options ); @@ -23,7 +23,7 @@ class EtagPlugin extends PluginInterface { } /** - * @property {Object} options + * @param {Object} options */ setOptions( options = {} ) { this.strong = typeof options.strong === 'boolean' @@ -34,8 +34,8 @@ class EtagPlugin extends PluginInterface { /** * @brief Calculates the ETag for a payload * - * @property {String|Buffer|Stats} payload - * @property {Boolean} strong + * @param {String|Buffer|Stats} payload + * @param {Boolean} strong * * @return String */ @@ -58,9 +58,9 @@ class EtagPlugin extends PluginInterface { * * @details This function will calculate * - * @property {EventRequest} event - * @property {String|Buffer|Stats} payload - * @property {Boolean} strong + * @param {EventRequest} event + * @param {String|Buffer|Stats} payload + * @param {Boolean} strong * * @return Object */ @@ -100,10 +100,10 @@ class EtagPlugin extends PluginInterface { /** * @brief Conditionally sends the request depending on the IF-* conditional headers * - * @property {EventRequest} event - * @property {String|Buffer} payload - * @property {Number} code - * @property {Boolean} strong + * @param {EventRequest} event + * @param {String|Buffer} payload + * @param {Number} code + * @param {Boolean} strong * * @return {void} */ @@ -164,7 +164,7 @@ class EtagPlugin extends PluginInterface { /** * @brief Extracts the conditional headers values * - * @property {String} header + * @param {String} header * * @private * diff --git a/server/plugins/available_plugins/file_stream_handler_plugin.js b/server/plugins/available_plugins/file_stream_handler_plugin.js index 235e8a9a..fbf64b4a 100644 --- a/server/plugins/available_plugins/file_stream_handler_plugin.js +++ b/server/plugins/available_plugins/file_stream_handler_plugin.js @@ -10,7 +10,7 @@ class FileStreamHandlerPlugin extends PluginInterface { /** * @brief Attaches the function stream file to the event * - * @property {EventRequest} event + * @param {EventRequest} event * * @return void */ @@ -20,8 +20,8 @@ class FileStreamHandlerPlugin extends PluginInterface { * * @details The file must be the absolute path to the file to be streamed * - * @property {String} file - * @property {Object} [options={}] + * @param {String} file + * @param {Object} [options={}] * * @return ReadStream|null */ @@ -39,9 +39,9 @@ class FileStreamHandlerPlugin extends PluginInterface { * * @details The file must be the absolute path to the file to be streamed * - * @property {String} file - * @property {Object} [options={}] - * @property {Function} [errCallback=null] + * @param {String} file + * @param {Object} [options={}] + * @param {Function} [errCallback=null] * * @return void */ diff --git a/server/plugins/available_plugins/logger_plugin.js b/server/plugins/available_plugins/logger_plugin.js index fc7a05be..ed721032 100644 --- a/server/plugins/available_plugins/logger_plugin.js +++ b/server/plugins/available_plugins/logger_plugin.js @@ -17,7 +17,7 @@ class LoggerPlugin extends PluginInterface { /** * @brief Attaches a process.log function for easier use * - * @property {Server} server + * @param {Server} server * * @return void */ @@ -48,7 +48,7 @@ class LoggerPlugin extends PluginInterface { * * @details Events attached: error, on_error, finished, redirect, cleanUp * - * @property {EventRequest} event + * @param {EventRequest} event * * @return void */ diff --git a/server/plugins/available_plugins/rate_limits_plugin.js b/server/plugins/available_plugins/rate_limits_plugin.js index 24329d0e..411afb16 100644 --- a/server/plugins/available_plugins/rate_limits_plugin.js +++ b/server/plugins/available_plugins/rate_limits_plugin.js @@ -92,7 +92,7 @@ class RateLimitsPlugin extends PluginInterface { /** * @brief Does rule validation for each parameter * - * @property {Object} options + * @param {Object} options * * @return void */ @@ -127,8 +127,8 @@ class RateLimitsPlugin extends PluginInterface { /** * Gets a Bucket from the rule options and key * - * @property {String} key - * @property {Object} options + * @param {String} key + * @param {Object} options * * @return Bucket */ @@ -152,7 +152,7 @@ class RateLimitsPlugin extends PluginInterface { * If a DataStore was not passed, gets the data store from the server er_data_server plugin, otherwise * creates a new datastore with persistence and not ttl. * - * @property {Server} server + * @param {Server} server * * @return void */ @@ -171,7 +171,7 @@ class RateLimitsPlugin extends PluginInterface { * Global middleware that can be used to dynamically rate limit requests * Creates a default data store if one is not set. * - * @property {Object} rule + * @param {Object} rule * * @return Function */ @@ -213,8 +213,8 @@ class RateLimitsPlugin extends PluginInterface { * Adds a rateLimited key IF one is not set already. This also detects that this is the first time * this plugin is invoked and will attach an on `cleanUp` event * - * @property {EventRequest} eventRequest - * @property {Array} rules + * @param {EventRequest} eventRequest + * @param {Array} rules * * @return void */ @@ -273,8 +273,8 @@ class RateLimitsPlugin extends PluginInterface { * Returns true if the request has been rate limited and a retry after should be sent, * otherwise return false * - * @property {Object} rule - * @property {Bucket} bucket + * @param {Object} rule + * @param {Bucket} bucket * * @returns Promise */ @@ -316,8 +316,8 @@ class RateLimitsPlugin extends PluginInterface { /** * Sends a 429 response whenever a request was rateLimited * - * @property {EventRequest} eventRequest - * @property {Number} retryAfterTime + * @param {EventRequest} eventRequest + * @param {Number} retryAfterTime * * @return void */ diff --git a/server/plugins/available_plugins/response_cache_plugin.js b/server/plugins/available_plugins/response_cache_plugin.js index 024c01d3..624955dc 100644 --- a/server/plugins/available_plugins/response_cache_plugin.js +++ b/server/plugins/available_plugins/response_cache_plugin.js @@ -29,7 +29,7 @@ class ResponseCachePlugin extends PluginInterface { /** * @brief Creates a rcp namespace to be used * - * @property {Server} server + * @param {Server} server * * @return void */ @@ -46,7 +46,7 @@ class ResponseCachePlugin extends PluginInterface { * * @details This will check if this request should be cached using the client's ip or not * - * @property {EventRequest} event + * @param {EventRequest} event * * @return String */ @@ -69,7 +69,7 @@ class ResponseCachePlugin extends PluginInterface { /** * @brief Gets the time to live from the config passed or not from the options set * - * @property {EventRequest} event + * @param {EventRequest} event * * @return Number */ diff --git a/server/plugins/available_plugins/session_plugin.js b/server/plugins/available_plugins/session_plugin.js index f91db5ba..52fb6c2c 100644 --- a/server/plugins/available_plugins/session_plugin.js +++ b/server/plugins/available_plugins/session_plugin.js @@ -24,7 +24,7 @@ class SessionPlugin extends PluginInterface { /** * @brief creates the namespace when attaching to the server * - * @property {Server} server + * @param {Server} server * * @return void */ diff --git a/server/plugins/available_plugins/static_resources_plugin.js b/server/plugins/available_plugins/static_resources_plugin.js index ba57feb6..dc065cfd 100644 --- a/server/plugins/available_plugins/static_resources_plugin.js +++ b/server/plugins/available_plugins/static_resources_plugin.js @@ -179,8 +179,8 @@ class StaticResourcesPlugin extends PluginInterface { * Finds a file starting from a dir * If start Path is a file, then it will be returned directly :) * - * @property {String} startPath - * @property {String} fileToFind + * @param {String} startPath + * @param {String} fileToFind * * @return {String|null} */ @@ -211,8 +211,8 @@ class StaticResourcesPlugin extends PluginInterface { * Sends a given file. * Sets the correct Content-Type header as well as the correct status code * - * @property {EventRequest} event - * @property {String} file + * @param {EventRequest} event + * @param {String} file */ _sendFile( event, file ) { event.setResponseHeader( 'Content-Type', MimeType.findMimeType( path.extname( file ) ) ).setStatusCode( 200 ); diff --git a/server/plugins/available_plugins/templating_engine_plugin.js b/server/plugins/available_plugins/templating_engine_plugin.js index dd585c4f..26a0c23d 100644 --- a/server/plugins/available_plugins/templating_engine_plugin.js +++ b/server/plugins/available_plugins/templating_engine_plugin.js @@ -25,7 +25,7 @@ class TemplatingEnginePlugin extends PluginInterface { /** * @brief Attaches a render function to the event request * - * @property {EventRequest} eventRequest + * @param {EventRequest} eventRequest * * @return void */ @@ -33,8 +33,8 @@ class TemplatingEnginePlugin extends PluginInterface { /** * @brief Renders the template given * - * @property {String} templateName - * @property {Object} variables + * @param {String} templateName + * @param {Object} variables * * @return Promise */ @@ -67,7 +67,7 @@ class TemplatingEnginePlugin extends PluginInterface { * due to the way JS behaves. Consider binding the function to the correct instance before passing: * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind * - * @property {Object} options + * @param {Object} options */ setOptions( options ) { const defaultTemplatingEngine = new DefaultTemplatingEngine(); diff --git a/server/plugins/available_plugins/timeout_plugin.js b/server/plugins/available_plugins/timeout_plugin.js index 49922c01..4f0b407d 100644 --- a/server/plugins/available_plugins/timeout_plugin.js +++ b/server/plugins/available_plugins/timeout_plugin.js @@ -35,8 +35,8 @@ class TimeoutPlugin extends PluginInterface { /** * @brief Set a timeout to the eventRequest * - * @property {EventRequest} event - * @property {Number} timeout + * @param {EventRequest} event + * @param {Number} timeout * * @return void */ diff --git a/server/plugins/available_plugins/validation_plugin.js b/server/plugins/available_plugins/validation_plugin.js index f459cdd1..f9507629 100644 --- a/server/plugins/available_plugins/validation_plugin.js +++ b/server/plugins/available_plugins/validation_plugin.js @@ -7,8 +7,8 @@ const PluginInterface = require( '../plugin_interface' ); */ class ValidationPlugin extends PluginInterface { /** - * @property {String} pluginId - * @property {Object} [options={}] + * @param {String} pluginId + * @param {Object} [options={}] */ constructor( pluginId, options = {} ) { super( pluginId, options ); @@ -17,7 +17,7 @@ class ValidationPlugin extends PluginInterface { } /** - * @property {Object} options + * @param {Object} options */ setOptions( options ) { super.setOptions( options ); @@ -34,8 +34,8 @@ class ValidationPlugin extends PluginInterface { * * @details This will merge the result with the properties that are being validated * - * @property {Object} validationRules - * @property {Function} failureCallback + * @param {Object} validationRules + * @param {Function} failureCallback * * @return Function */ diff --git a/server/plugins/plugin_interface.js b/server/plugins/plugin_interface.js index e7456c0d..2b1e1d93 100644 --- a/server/plugins/plugin_interface.js +++ b/server/plugins/plugin_interface.js @@ -7,8 +7,8 @@ */ class PluginInterface { /** - * @property {String} pluginId - * @property {Object} [options={}] + * @param {String} pluginId + * @param {Object} [options={}] */ constructor( pluginId, options = {} ) { this.options = options; @@ -40,7 +40,7 @@ class PluginInterface { * * @details This method should attach to any events dispatched by the server * - * @property {Server} server + * @param {Server} server * * @return void */ @@ -50,7 +50,7 @@ class PluginInterface { /** * @brief Sets new options for the plugin * - * @property {Object} options + * @param {Object} options * * @return void */ diff --git a/server/plugins/plugin_manager.js b/server/plugins/plugin_manager.js index 35355eaf..3a356bcc 100644 --- a/server/plugins/plugin_manager.js +++ b/server/plugins/plugin_manager.js @@ -11,7 +11,7 @@ class PluginManager { /** * @brief Adds a plugin to the Manager * - * @property {PluginInterface} plugin + * @param {PluginInterface} plugin * * @return void */ @@ -25,7 +25,7 @@ class PluginManager { /** * @brief Checks whether the given plugin id corresponds to a plugin added to the manager * - * @property {String} id + * @param {String} id * * @return Boolean */ @@ -36,7 +36,7 @@ class PluginManager { /** * @brief Removes a plugin by id * - * @property {String} id + * @param {String} id * * @return void */ @@ -56,7 +56,7 @@ class PluginManager { /** * @brief Returns if the given plugin is a valid plugin interface * - * @property {PluginInterface|Object} plugin + * @param {PluginInterface|Object} plugin * * @return Boolean */ @@ -71,7 +71,7 @@ class PluginManager { /** * @brief Gets a plugin given an id * - * @property {String} id + * @param {String} id * * @return PluginInterface */ diff --git a/server/server.js b/server/server.js index 199c47cc..d774a392 100644 --- a/server/server.js +++ b/server/server.js @@ -133,8 +133,8 @@ class Server extends EventEmitter { * @details The plugin manager can be used to extract and set up plugins and then add them to the server just by * giving their plugin ids * - * @property {PluginInterface|Object|String} plugin - * @property {Object} options + * @param {PluginInterface|Object|String} plugin + * @param {Object} options * * @return Server */ @@ -156,7 +156,7 @@ class Server extends EventEmitter { /** * @brief Attaches a PluginInterface to the server * - * @property {PluginInterface} plugin + * @param {PluginInterface} plugin * * @return void */ @@ -181,7 +181,7 @@ class Server extends EventEmitter { * * @details Will throw if the plugin is not attached * - * @property {String|PluginInterface} pluginId + * @param {String|PluginInterface} pluginId * * @return PluginInterface */ @@ -197,7 +197,7 @@ class Server extends EventEmitter { /** * @brief Checks whether the server has a plugin with the given id * - * @property {String|PluginInterface} pluginId + * @param {String|PluginInterface} pluginId * * @return Boolean */ diff --git a/server/tester/mock.js b/server/tester/mock.js index 962e3821..e423cf1a 100644 --- a/server/tester/mock.js +++ b/server/tester/mock.js @@ -6,7 +6,7 @@ const Mocker = require( './mocker' ); /** * @brief Used to create a MockedObject * - * @property {*} objectToMock + * @param {*} objectToMock * * @return Function */ @@ -15,7 +15,7 @@ let Mock = function ( objectToMock ) { /** * @brief Method used to mock other methods * - * @property {Object} mockMethodOptions + * @param {Object} mockMethodOptions * * @return Object */ @@ -32,7 +32,7 @@ let Mock = function ( objectToMock ) { /** * @brief Method used to mock other methods * - * @property {Object} mockMethodOptions + * @param {Object} mockMethodOptions * * @return MockedClass */ diff --git a/server/tester/mocker.js b/server/tester/mocker.js index 81677ec4..c7cdbc9d 100644 --- a/server/tester/mocker.js +++ b/server/tester/mocker.js @@ -64,7 +64,7 @@ class Mocker { /** * @brief Assert whether correct with arguments are passed * - * @property {Array} args + * @param {Array} args * * @return void */ @@ -128,7 +128,7 @@ class Mocker { /** * @brief Gets the next function to execute * - * @property {Array} args + * @param {Array} args * * @return mixed */ diff --git a/server/tester/tester.js b/server/tester/tester.js index 2a9a73f9..b6d4cbdf 100644 --- a/server/tester/tester.js +++ b/server/tester/tester.js @@ -40,7 +40,7 @@ class Tester { * * @details This is done so we can run the test many times per instance * - * @property {Object} options + * @param {Object} options * * @return void */ @@ -119,7 +119,7 @@ class Tester { /** * @brief Formats the given test object by adding needed internal fields * - * @property {Object} test + * @param {Object} test * * @return Array */ @@ -175,7 +175,7 @@ class Tester { /** * @brief Adds the given test to the queue * - * @property {Object} test + * @param {Object} test * * @return void */ @@ -199,8 +199,8 @@ class Tester { /** * @brief Called if there is an error in the test * - * @property {Object} test - * @property {*} error + * @param {Object} test + * @param {*} error */ errorCallback( test, error ) { if ( error instanceof Error ) { @@ -248,8 +248,8 @@ class Tester { /** * @brief Called by the done function of the tests * - * @property {Object} test - * @property {*} err + * @param {Object} test + * @param {*} err * * @return void */ @@ -269,7 +269,7 @@ class Tester { /** * @brief Checks the given test's status and determines what should happen * - * @property {Object} test + * @param {Object} test * * @return Boolean */ @@ -349,7 +349,7 @@ class Tester { * * @details This will produce an output directly to the console of the user * - * @property {Object} options + * @param {Object} options * * @return void */ diff --git a/tests/server/components/body_parsers/multipart_data_parser_test.js b/tests/server/components/body_parsers/multipart_data_parser_test.js index bd765847..57fb1779 100644 --- a/tests/server/components/body_parsers/multipart_data_parser_test.js +++ b/tests/server/components/body_parsers/multipart_data_parser_test.js @@ -860,7 +860,7 @@ test({ /** * @brief Waits for a file to exist and return the contents * - * @property {String} file + * @param {String} file * * @return {Promise} */ diff --git a/tests/server/components/file_streams/image_file_stream_test.js b/tests/server/components/file_streams/image_file_stream_test.js index b89b480c..8c5b862c 100644 --- a/tests/server/components/file_streams/image_file_stream_test.js +++ b/tests/server/components/file_streams/image_file_stream_test.js @@ -5,30 +5,18 @@ const { assert, test, helpers } = require( '../../../test_helper' ); const path = require( 'path' ); const fs = require( 'fs' ); -const formats = { - '.apng' : 'image/apng', '.avif' : 'image/avif', '.gif' : 'image/gif', '.jpg' : 'image/jpeg', - '.jpeg' : 'image/jpeg', '.jfif' : 'image/jpeg', '.pjpeg' : 'image/jpeg', '.pjp' : 'image/jpeg', - '.png' : 'image/png', '.svg' : 'image/svg+xml', '.webp' : 'image/webp', '.ico' : 'image/x-icon', - '.bmp' : 'image/bmp', -}; - test({ message : 'ImageFileStream.getFileStream with different types', dataProvider: [ [path.join( __dirname, './fixtures/testFile.png' ), 'image/png'], - [path.join( __dirname, './fixtures/testFile.apng' ), 'image/apng'], - [path.join( __dirname, './fixtures/testFile.avif' ), 'image/avif'], [path.join( __dirname, './fixtures/testFile.gif' ), 'image/gif'], [path.join( __dirname, './fixtures/testFile.jpg' ), 'image/jpeg'], [path.join( __dirname, './fixtures/testFile.jpeg' ), 'image/jpeg'], - [path.join( __dirname, './fixtures/testFile.jfif' ), 'image/jpeg'], - [path.join( __dirname, './fixtures/testFile.pjpeg' ), 'image/jpeg'], - [path.join( __dirname, './fixtures/testFile.pjp' ), 'image/jpeg'], [path.join( __dirname, './fixtures/testFile.svg' ), 'image/svg+xml'], [path.join( __dirname, './fixtures/testFile.webp' ), 'image/webp'], [path.join( __dirname, './fixtures/testFile.ico' ), 'image/x-icon'], [path.join( __dirname, './fixtures/testFile.bmp' ), 'image/bmp'], - [path.join( __dirname, './fixtures/testFile.unknown' ), null], + [path.join( __dirname, './fixtures/testFile.unknown' ), "*/*"], ], test : ( done, filePath, expectedMimeType ) => { const eventRequest = helpers.getEventRequest( undefined, undefined, undefined ); diff --git a/tests/server/components/file_streams/text_file_stream_test.js b/tests/server/components/file_streams/text_file_stream_test.js index 2db8f904..3265aa05 100644 --- a/tests/server/components/file_streams/text_file_stream_test.js +++ b/tests/server/components/file_streams/text_file_stream_test.js @@ -10,8 +10,17 @@ const DEFAULT_TEST_FILE = path.join( __dirname, './fixtures/testFile.txt' ); test({ message : 'TextFileStream.getFileStream', test : ( done ) => { - const eventRequest = helpers.getEventRequest( undefined, undefined, undefined ); - const fileStream = new TextFileStream(); + const eventRequest = helpers.getEventRequest( undefined, undefined, undefined ); + const fileStream = new TextFileStream(); + let mimeType = null; + let expectedMimeType = "text/plain"; + + eventRequest._mock({ + method : 'setResponseHeader', + shouldReturn : ( key, value ) => { + mimeType = value; + } + }); const stream = fileStream.getFileStream( eventRequest, DEFAULT_TEST_FILE ); @@ -25,6 +34,7 @@ test({ stream.on( 'end', () => { assert.deepStrictEqual( Buffer.concat( data ).toString(), 'This is a test file. It has a bit of data.' ); + assert.deepStrictEqual( mimeType, expectedMimeType ); done(); }); } diff --git a/tests/server/components/helpers/unique_id_test.js b/tests/server/components/helpers/unique_id_test.js index 2cb46455..b0a56a7a 100644 --- a/tests/server/components/helpers/unique_id_test.js +++ b/tests/server/components/helpers/unique_id_test.js @@ -18,15 +18,11 @@ test({ }); test({ - message : 'UniqueId.makeId.with.not.a.number.argument', + message : 'UniqueId.makeId makes a random ID with the correct length defaults to 32', test : ( done ) => { - const idOne = uniqueId.makeId( 10 ); - const idTwo = uniqueId.makeId( 'wrong' ); - - assert.equal( idOne.length, 10 ); - assert.equal( idTwo.length, 10 ); - assert.notEqual( idOne, idTwo ); + const idOne = uniqueId.makeId(); + assert.equal( idOne.length, 32 ); done(); } }); diff --git a/tests/server/components/logger/components/transport_types/processors/timestamp_processor_test.js b/tests/server/components/logger/components/transport_types/processors/timestamp_processor_test.js index cbdb573e..213429a4 100644 --- a/tests/server/components/logger/components/transport_types/processors/timestamp_processor_test.js +++ b/tests/server/components/logger/components/transport_types/processors/timestamp_processor_test.js @@ -7,7 +7,7 @@ const timestampProcessor = require( './../../../../../../../server/components/lo /** * @brief Gets the timestamp from the Log * - * @property {Number} timestamp + * @param {Number} timestamp * * @return {String} */ diff --git a/tests/server/components/logger/loggur_test.js b/tests/server/components/logger/loggur_test.js index 9d3e9636..4de8a1d0 100644 --- a/tests/server/components/logger/loggur_test.js +++ b/tests/server/components/logger/loggur_test.js @@ -81,7 +81,7 @@ test({ let testLogger = loggur.createLogger({}); loggur.addLogger( loggerName, testLogger ); assert.equal( loggur.getLogger( loggerName ), testLogger ); - assert.equal( loggur.getLogger( loggerName ) !== false, true ); + assert.equal( loggur.getLogger( loggerName ) !== null, true ); done(); } @@ -92,7 +92,7 @@ test({ test : ( done ) => { let loggur = helpers.getMockedLoggur(); let loggerName = 'testLogger'; - assert.equal( loggur.getLogger( loggerName ), false ); + assert.equal( loggur.getLogger( loggerName ), null ); done(); } diff --git a/tests/server/components/mime_type/mime_type_test.js b/tests/server/components/mime_type/mime_type_test.js index 06feb875..c9d451d9 100644 --- a/tests/server/components/mime_type/mime_type_test.js +++ b/tests/server/components/mime_type/mime_type_test.js @@ -22,7 +22,7 @@ test({ ['.gz','application/gzip'], ['.gif','image/gif'], ['.html','text/html'], - ['.ico','image/vnd.microsoft.icon'], + ['.ico','image/x-icon'], ['.ics','text/calendar'], ['.jar','application/java-archive'], ['.jpg','image/jpeg'], @@ -104,7 +104,7 @@ test({ ['.gif','image/gif'], ['.htm','text/html'], ['.html','text/html'], - ['.ico','image/vnd.microsoft.icon'], + ['.ico','image/x-icon'], ['.ics','text/calendar'], ['.jar','application/java-archive'], ['.jpg','image/jpeg'], @@ -189,7 +189,7 @@ test({ ['.gif',['image/gif']], ['.htm',['text/html']], ['.html',['text/html']], - ['.ico',['image/vnd.microsoft.icon']], + ['.ico',['image/x-icon']], ['.ics',['text/calendar']], ['.jar',['application/java-archive']], ['.jpg',['image/jpeg']], diff --git a/tests/server/components/routing/route_test.js b/tests/server/components/routing/route_test.js index d8860163..3c76a4f3 100644 --- a/tests/server/components/routing/route_test.js +++ b/tests/server/components/routing/route_test.js @@ -7,10 +7,10 @@ const Route = require( '../../../../server/components/routing/route' ); /** * @brief Gets a route with the given arguments * - * @property Function handler - * @property mixed route - * @property mixed method - * @property Array middlewares + * @param Function handler + * @param mixed route + * @param mixed method + * @param Array middlewares * * @return Route */ diff --git a/tests/test_bootstrap.js b/tests/test_bootstrap.js index 7afcd759..e4b02198 100644 --- a/tests/test_bootstrap.js +++ b/tests/test_bootstrap.js @@ -12,8 +12,8 @@ const TEST_ROOT = path.parse( __dirname ).dir; * * @details This action is not recursive and is synchronous * - * @property String dir - * @property Array whiteList + * @param String dir + * @param Array whiteList * * @return void */ diff --git a/tests/test_helper.js b/tests/test_helper.js index f2db1509..6c889b92 100644 --- a/tests/test_helper.js +++ b/tests/test_helper.js @@ -83,9 +83,9 @@ helpers.getEmptyMiddleware = () => { /** * @brief Returns a mocked instance of the eventRequest * - * @property {String} [requestMethod=''] - * @property {String} [requestUrl='/'] - * @property {Object} [headers={}] + * @param {String} [requestMethod=''] + * @param {String} [requestUrl='/'] + * @param {Object} [headers={}] * * @return EventRequest */ @@ -111,13 +111,13 @@ helpers.getEventRequest = ( requestMethod = '', requestUrl = '/', headers = {} ) /** * @brief Sends a request to the server and returns a Promise * - * @property {String} path - * @property {String} [method='GET'] - * @property {Number} [statusCode=200] - * @property {*} [data=''] - * @property {Object} [headers={}] - * @property {Number} [port=3333] - * @property {String} [expectedBody=null] + * @param {String} path + * @param {String} [method='GET'] + * @param {Number} [statusCode=200] + * @param {*} [data=''] + * @param {Object} [headers={}] + * @param {Number} [port=3333] + * @param {String} [expectedBody=null] * * @return Promise */ From bfdeb8e8b23ec6288e659886aae8f194cfe918d7 Mon Sep 17 00:00:00 2001 From: Stefan Genov Date: Sat, 22 Jan 2022 18:25:31 +0200 Subject: [PATCH 2/2] [develop] Housekeeping progress --- .../validation/validation_attribute.js | 6 +- .../validation/validation_handler.js | 2 +- .../validation/validation_result.js | 10 +--- .../components/validation/validation_rules.js | 60 +++++++++---------- server/event_request.js | 34 ++++------- .../available_plugins/body_parser_plugin.js | 4 +- .../available_plugins/cache_control_plugin.js | 4 +- .../plugins/available_plugins/cors_plugin.js | 4 +- .../available_plugins/data_server_plugin.js | 6 +- .../plugins/available_plugins/env_plugin.js | 6 +- .../plugins/available_plugins/etag_plugin.js | 6 +- .../file_stream_handler_plugin.js | 8 +-- .../available_plugins/logger_plugin.js | 8 +-- .../available_plugins/rate_limits_plugin.js | 49 +++++++-------- .../response_cache_plugin.js | 10 ++-- .../available_plugins/security_plugin.js | 2 +- .../available_plugins/session_plugin.js | 16 +++-- .../static_resources_plugin.js | 20 ++++--- .../templating_engine_plugin.js | 7 ++- .../available_plugins/timeout_plugin.js | 8 ++- .../available_plugins/validation_plugin.js | 3 +- server/plugins/plugin_interface.js | 10 +--- server/plugins/plugin_manager.js | 12 ++-- server/server.js | 20 +++---- server/tester/mock.js | 6 +- server/tester/mocker.js | 12 +--- server/tester/tester.js | 18 +----- 27 files changed, 141 insertions(+), 210 deletions(-) diff --git a/server/components/validation/validation_attribute.js b/server/components/validation/validation_attribute.js index 23573ed2..d11aca61 100644 --- a/server/components/validation/validation_attribute.js +++ b/server/components/validation/validation_attribute.js @@ -50,7 +50,7 @@ class ValidationAttribute { /** * @brief Returns false otherwise returns reason why it is not valid * - * @return Array|Boolean + * @return {Array|Boolean} */ validateSelf() { if ( typeof this.rules === 'object' && typeof this.rules['$default'] !== 'undefined' && typeof this.rules['$rules'] === 'string') { @@ -87,7 +87,7 @@ class ValidationAttribute { * @param {Number} index * @param {Object} params * - * @return String|Boolean + * @return {String|Boolean} */ validateRule( rule, index, params ) { let valueLength, sameEntry, inputEntry; @@ -250,7 +250,7 @@ class ValidationAttribute { * * @param {String} rule * - * @return Object + * @return {Object} */ getRuleParams( rule ) { const ruleParams = rule.split( ':' ); diff --git a/server/components/validation/validation_handler.js b/server/components/validation/validation_handler.js index 9b7938cf..99500c70 100644 --- a/server/components/validation/validation_handler.js +++ b/server/components/validation/validation_handler.js @@ -10,7 +10,7 @@ module.exports = { * @param {Object} validationInput * @param {Object} skeleton * - * @return ValidationResult + * @return {ValidationResult} */ validate : ( validationInput, skeleton ) => { if ( typeof validationInput !== 'object' ) diff --git a/server/components/validation/validation_result.js b/server/components/validation/validation_result.js index 35c81fba..b058deb8 100644 --- a/server/components/validation/validation_result.js +++ b/server/components/validation/validation_result.js @@ -21,8 +21,6 @@ class ValidationResult { * @brief Validates all the attributes * * @details Will not validate if validation was already performed - * - * @return void */ validateAllAttributes() { if ( this.validationFailed !== null ) @@ -49,7 +47,7 @@ class ValidationResult { * * @private * - * @return Object|Array + * @return {Object|Array} */ _formResult( validationInput, skeleton, failures ) { let result = {}; @@ -147,8 +145,6 @@ class ValidationResult { * @param {Object} failures * * @private - * - * @return void */ _sanitizeFailures( failures ) { for ( const key in failures ) { @@ -168,7 +164,7 @@ class ValidationResult { /** * @brief Checks if the validation of a given ValidationInput has failed. * - * @return Boolean + * @return {Boolean} */ hasValidationFailed() { this.validateAllAttributes(); @@ -180,7 +176,7 @@ class ValidationResult { * @brief Gets the reason if any of validation failure otherwise the returned * object will have the values mapped to the keys that were being validated * - * @return Array + * @return {Array} */ getValidationResult() { this.validateAllAttributes(); diff --git a/server/components/validation/validation_rules.js b/server/components/validation/validation_rules.js index 928695d4..47b913e5 100644 --- a/server/components/validation/validation_rules.js +++ b/server/components/validation/validation_rules.js @@ -8,7 +8,7 @@ let assert = {}; * * @param {*} value * - * @return String + * @return {String} */ function getType( value ) { return typeof value; @@ -19,7 +19,7 @@ function getType( value ) { * * @param {*} value * - * @return Number + * @return {Number} */ function getLength( value ) { if ( value === undefined ) @@ -51,7 +51,7 @@ const EMAIL_REGEX = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+" * @param {*} actual * @param {*} expected * - * @return Boolean + * @return {Boolean} */ assert.assertEqual = ( actual, expected ) => { return actual == expected; @@ -63,7 +63,7 @@ assert.assertEqual = ( actual, expected ) => { * @param {*} actual * @param {*} expected * - * @return Boolean + * @return {Boolean} */ assert.assertStrictEqual = ( actual, expected ) => { return actual === expected; @@ -75,7 +75,7 @@ assert.assertStrictEqual = ( actual, expected ) => { * @param {*} actual * @param {*} expected * - * @return Boolean + * @return {Boolean} */ assert.assertNotEqual = ( actual, expected ) => { return actual != expected; @@ -87,7 +87,7 @@ assert.assertNotEqual = ( actual, expected ) => { * @param {*} actual * @param {*} expected * - * @return Boolean + * @return {Boolean} */ assert.assertStrictNotEqual = ( actual, expected ) => { return actual !== expected; @@ -98,7 +98,7 @@ assert.assertStrictNotEqual = ( actual, expected ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertIsString = ( actual ) => { return assert.assertIsInternalType( actual, 'string' ); @@ -109,7 +109,7 @@ assert.assertIsString = ( actual ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertNotString = ( actual ) => { return assert.assertNotInternalType( actual, 'string' ); @@ -120,7 +120,7 @@ assert.assertNotString = ( actual ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertIsNumeric = ( actual ) => { const check = Number( actual ); @@ -133,7 +133,7 @@ assert.assertIsNumeric = ( actual ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertNotNumeric = ( actual ) => { return isNaN( Number( actual ) ); @@ -144,7 +144,7 @@ assert.assertNotNumeric = ( actual ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertIsArray = ( actual ) => { return Array.isArray( actual ); @@ -155,7 +155,7 @@ assert.assertIsArray = ( actual ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertNotArray = ( actual ) => { return ! Array.isArray( actual ); @@ -168,7 +168,7 @@ assert.assertNotArray = ( actual ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertIsEmpty = ( actual ) => { return actual === null @@ -185,7 +185,7 @@ assert.assertIsEmpty = ( actual ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertNotEmpty = ( actual ) => { if ( actual === undefined || actual === null ) @@ -205,7 +205,7 @@ assert.assertNotEmpty = ( actual ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertIsDate = ( actual ) => { return ! isNaN( Date.parse( actual ) ); @@ -216,7 +216,7 @@ assert.assertIsDate = ( actual ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertIsDateObject = ( actual ) => { return actual instanceof Date; @@ -227,7 +227,7 @@ assert.assertIsDateObject = ( actual ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertNotDate = ( actual ) => { return isNaN( Date.parse( actual ) ); @@ -238,7 +238,7 @@ assert.assertNotDate = ( actual ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertNotDateObject = ( actual ) => { return ! ( actual instanceof Date ); @@ -250,7 +250,7 @@ assert.assertNotDateObject = ( actual ) => { * @param {*} actual * @param {String} internalType * - * @return Boolean + * @return {Boolean} */ assert.assertIsInternalType = ( actual, internalType ) => { return getType( actual ) === internalType; @@ -262,7 +262,7 @@ assert.assertIsInternalType = ( actual, internalType ) => { * @param {*} actual * @param {String} internalType * - * @return Boolean + * @return {Boolean} */ assert.assertNotInternalType = ( actual, internalType ) => { return getType( actual ) !== internalType; @@ -273,7 +273,7 @@ assert.assertNotInternalType = ( actual, internalType ) => { * * @param {String} actual * - * @return Boolean + * @return {Boolean} */ assert.assertIsValidEmail = ( actual ) => { return EMAIL_REGEX.test( String( actual ).toLowerCase() ); @@ -284,7 +284,7 @@ assert.assertIsValidEmail = ( actual ) => { * * @param {String} actual * - * @return Boolean + * @return {Boolean} */ assert.assertNotValidEmail = ( actual ) => { return ! EMAIL_REGEX.test( String( actual ).toLowerCase() ); @@ -296,7 +296,7 @@ assert.assertNotValidEmail = ( actual ) => { * @param {*} actual * @param {*} comparator * - * @return Boolean + * @return {Boolean} */ assert.assertBiggerThan = ( actual, comparator ) => { return getLength( actual ) > getLength( comparator ); @@ -308,7 +308,7 @@ assert.assertBiggerThan = ( actual, comparator ) => { * @param {*} actual * @param {*} comparator * - * @return Boolean + * @return {Boolean} */ assert.assertBiggerOrEqual = ( actual, comparator ) => { return getLength( actual ) >= getLength( comparator ); @@ -320,7 +320,7 @@ assert.assertBiggerOrEqual = ( actual, comparator ) => { * @param {*} actual * @param {*} comparator * - * @return Boolean + * @return {Boolean} */ assert.assertSmallerThan = ( actual, comparator ) => { return getLength( actual ) < getLength( comparator ); @@ -332,7 +332,7 @@ assert.assertSmallerThan = ( actual, comparator ) => { * @param {*} actual * @param {*} comparator * - * @return Boolean + * @return {Boolean} */ assert.assertSmallerOrEqual = ( actual, comparator ) => { return getLength( actual ) <= getLength( comparator ); @@ -343,7 +343,7 @@ assert.assertSmallerOrEqual = ( actual, comparator ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertIsBoolean = ( actual ) => { return assert.assertIsInternalType( actual, 'boolean' ) @@ -356,7 +356,7 @@ assert.assertIsBoolean = ( actual ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertNotBoolean = ( actual ) => { return assert.assertNotInternalType( actual, 'boolean' ); @@ -367,7 +367,7 @@ assert.assertNotBoolean = ( actual ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertTrue = ( actual ) => { if ( assert.assertIsInternalType( actual, 'boolean' ) ) @@ -387,7 +387,7 @@ assert.assertTrue = ( actual ) => { * * @param {*} actual * - * @return Boolean + * @return {Boolean} */ assert.assertFalse = ( actual ) => { if ( assert.assertIsInternalType( actual, 'boolean' ) ) diff --git a/server/event_request.js b/server/event_request.js index 785d7d93..95e98d95 100644 --- a/server/event_request.js +++ b/server/event_request.js @@ -62,8 +62,6 @@ class EventRequest extends EventEmitter { * @details Removes all listeners from the eventEmitter * Stops the event * Clears internal pointers - * - * @return void */ _cleanUp() { this.emit( 'cleanUp' ); @@ -92,7 +90,7 @@ class EventRequest extends EventEmitter { * * @param {*} args * - * @return ValidationResult + * @return {ValidationResult} */ validate( ...args ) { return this.validation.validate.apply( this.validation, args ); @@ -109,7 +107,7 @@ class EventRequest extends EventEmitter { * @param {String} value * @param {Object} [options={}] * - * @return Boolean + * @return {Boolean} */ setCookie( name, value, options = {} ) { const cookieHeaderName = 'set-cookie'; @@ -152,7 +150,7 @@ class EventRequest extends EventEmitter { * @param {*} [response=''] * @param {Number} [code=null] * - * @return Promise + * @return {Promise} */ send( response = '', code = null ) { if ( typeof code === 'number' ) @@ -185,7 +183,7 @@ class EventRequest extends EventEmitter { /** * @brief Ends the response with the given params * - * @return Promise + * @return {Promise} */ async end( ...args ) { this.response.end.apply( this.response, args ); @@ -197,7 +195,7 @@ class EventRequest extends EventEmitter { * @param {String} key * @param {String} value * - * @return EventRequest + * @return {EventRequest} */ setResponseHeader( key, value ) { if ( ! this.isFinished() && ! this.response.headersSent ) @@ -211,7 +209,7 @@ class EventRequest extends EventEmitter { * * @param {String} key * - * @return EventRequest + * @return {EventRequest} */ removeResponseHeader( key ) { if ( ! this.isFinished() && ! this.response.headersSent ) @@ -228,7 +226,7 @@ class EventRequest extends EventEmitter { * @param {String} key * @param {String} [defaultValue=null] * - * @return String + * @return {String} */ getRequestHeader( key, defaultValue = null ) { return ! this.hasRequestHeader( key ) @@ -243,7 +241,7 @@ class EventRequest extends EventEmitter { /** * @brief Return all the headers for the current request * - * @return Object + * @return {Object} */ getRequestHeaders() { return this.headers; @@ -254,7 +252,7 @@ class EventRequest extends EventEmitter { * * @param {String} key * - * @return Boolean + * @return {Boolean} */ hasRequestHeader( key ) { return typeof this.headers[key.toLowerCase()] !== 'undefined' || typeof this.headers[key] !== 'undefined'; @@ -265,7 +263,7 @@ class EventRequest extends EventEmitter { * * @param {Number} code * - * @return EventRequest + * @return {EventRequest} */ setStatusCode( code ) { this.response.statusCode = typeof code === 'number' ? code : 500; @@ -278,8 +276,6 @@ class EventRequest extends EventEmitter { * * @param {String} redirectUrl * @param {Number} [statusCode=302] - * - * @return void */ redirect( redirectUrl, statusCode = 302 ) { this.emit( 'redirect', { redirectUrl, statusCode } ); @@ -296,7 +292,7 @@ class EventRequest extends EventEmitter { /** * @brief Checks if the response is finished * - * @return Boolean + * @return {Boolean} */ isFinished() { return this.finished === true || this.response.writableEnded; @@ -306,8 +302,6 @@ class EventRequest extends EventEmitter { * @brief Sets the current execution block * * @param {Array} block - * - * @return void */ _setBlock( block ) { this.block = block; @@ -322,8 +316,6 @@ class EventRequest extends EventEmitter { * * @param {*} err * @param {Number} code - * - * @return void */ _next( err, code ) { if ( err ) @@ -350,7 +342,7 @@ class EventRequest extends EventEmitter { /** * @brief Gets the error handler or creates a new one if needed * - * @return ErrorHandler + * @return {ErrorHandler} */ getErrorHandler() { if ( this.errorHandler === null || typeof this.errorHandler === 'undefined' || typeof this.errorHandler.handleError !== 'function' ) @@ -365,8 +357,6 @@ class EventRequest extends EventEmitter { * @details By default handleError is asynchronous * * @param {Array} args - * - * @return void */ sendError( ...args ) { const errorHandler = this.getErrorHandler(); diff --git a/server/plugins/available_plugins/body_parser_plugin.js b/server/plugins/available_plugins/body_parser_plugin.js index 10ee5bd7..9da72efd 100644 --- a/server/plugins/available_plugins/body_parser_plugin.js +++ b/server/plugins/available_plugins/body_parser_plugin.js @@ -21,8 +21,6 @@ class BodyParserPlugin extends PluginInterface { * @brief Set the parser if given * * @param {Object} [options={}] - * - * @return void */ setOptions( options = {} ) { super.setOptions( options ); @@ -36,7 +34,7 @@ class BodyParserPlugin extends PluginInterface { * @details This plugin can be configured multiple times if needed and reused. If other plugins have similar functionality * this plugin will not overwrite their properties * - * @return Array + * @return {Array} */ getPluginMiddleware() { const pluginMiddleware = { diff --git a/server/plugins/available_plugins/cache_control_plugin.js b/server/plugins/available_plugins/cache_control_plugin.js index f6c1758f..319b76e3 100644 --- a/server/plugins/available_plugins/cache_control_plugin.js +++ b/server/plugins/available_plugins/cache_control_plugin.js @@ -18,7 +18,7 @@ class CacheControlPlugin extends PluginInterface { * * @param {Object} [options={}] * - * @return Function + * @return {Function} */ cache( options = {} ) { const header = this.builder.build( options ); @@ -30,7 +30,7 @@ class CacheControlPlugin extends PluginInterface { } /** - * @return Array + * @return {Array} */ getPluginMiddleware() { return [this.cache( this.options )]; diff --git a/server/plugins/available_plugins/cors_plugin.js b/server/plugins/available_plugins/cors_plugin.js index 98f3eda6..1bc9dfe4 100644 --- a/server/plugins/available_plugins/cors_plugin.js +++ b/server/plugins/available_plugins/cors_plugin.js @@ -54,8 +54,6 @@ class CorsPlugin extends PluginInterface { * @brief Applies all the CORS headers to the response * * @param {EventRequest} event - * - * @return void */ applyCors( event ) { if ( ! Array.isArray( this.origin ) ) { @@ -96,7 +94,7 @@ class CorsPlugin extends PluginInterface { /** * @brief Gets the cors middleware that adds the extra CORS headers * - * @return Array + * @return {Array} */ getPluginMiddleware() { return [{ handler : this.applyCors.bind( this ) }]; diff --git a/server/plugins/available_plugins/data_server_plugin.js b/server/plugins/available_plugins/data_server_plugin.js index 73622eb4..8dbae21e 100644 --- a/server/plugins/available_plugins/data_server_plugin.js +++ b/server/plugins/available_plugins/data_server_plugin.js @@ -14,7 +14,7 @@ class DataServerPlugin extends PluginInterface { /** * @brief Returns the DataServer * - * @returns DataServer + * @returns {DataServer} */ getServer() { if ( this.server ) @@ -34,7 +34,7 @@ class DataServerPlugin extends PluginInterface { * * @param {Object} dataServer * - * @return {boolean} + * @return {Boolean} */ isValidDataServer( dataServer ) { if ( typeof dataServer !== 'object' ) @@ -60,7 +60,7 @@ class DataServerPlugin extends PluginInterface { * * @details Attaches a cleanUp event as well * - * @returns Array + * @returns {Array} */ getPluginMiddleware() { const pluginMiddleware = { diff --git a/server/plugins/available_plugins/env_plugin.js b/server/plugins/available_plugins/env_plugin.js index ba8ec29d..3a6ecb8c 100644 --- a/server/plugins/available_plugins/env_plugin.js +++ b/server/plugins/available_plugins/env_plugin.js @@ -13,8 +13,6 @@ const ENV_SEPARATOR = '='; class EnvPlugin extends PluginInterface { /** * @brief Loads the file to the process.env - * - * @return void */ loadFileInEnv() { const absFilePath = this.getEnvFileAbsPath(); @@ -33,8 +31,6 @@ class EnvPlugin extends PluginInterface { * @brief Loads the env variables on runtime * * @param {Server} server - * - * @return void */ setServerOnRuntime( server ) { this.loadFileInEnv(); @@ -43,7 +39,7 @@ class EnvPlugin extends PluginInterface { /** * @brief Gets the absolute file path to the .env file * - * @return String + * @return {String} */ getEnvFileAbsPath() { return typeof this.options.fileLocation === 'string' diff --git a/server/plugins/available_plugins/etag_plugin.js b/server/plugins/available_plugins/etag_plugin.js index c87d75b0..1c0e2b8c 100644 --- a/server/plugins/available_plugins/etag_plugin.js +++ b/server/plugins/available_plugins/etag_plugin.js @@ -37,7 +37,7 @@ class EtagPlugin extends PluginInterface { * @param {String|Buffer|Stats} payload * @param {Boolean} strong * - * @return String + * @return {String} */ etag( payload, strong = this.strong ) { const algo = strong ? 'sha1' : 'md5'; @@ -62,7 +62,7 @@ class EtagPlugin extends PluginInterface { * @param {String|Buffer|Stats} payload * @param {Boolean} strong * - * @return Object + * @return {Object} */ getConditionalResult( event, payload, strong = this.strong ) { const etag = this.etag( payload, strong ); @@ -104,8 +104,6 @@ class EtagPlugin extends PluginInterface { * @param {String|Buffer} payload * @param {Number} code * @param {Boolean} strong - * - * @return {void} */ conditionalSend( event, payload, code = null, strong = this.strong ) { payload = event.formatResponse( payload ); diff --git a/server/plugins/available_plugins/file_stream_handler_plugin.js b/server/plugins/available_plugins/file_stream_handler_plugin.js index fbf64b4a..48c44f07 100644 --- a/server/plugins/available_plugins/file_stream_handler_plugin.js +++ b/server/plugins/available_plugins/file_stream_handler_plugin.js @@ -11,8 +11,6 @@ class FileStreamHandlerPlugin extends PluginInterface { * @brief Attaches the function stream file to the event * * @param {EventRequest} event - * - * @return void */ attachFunctions( event ) { /** @@ -23,7 +21,7 @@ class FileStreamHandlerPlugin extends PluginInterface { * @param {String} file * @param {Object} [options={}] * - * @return ReadStream|null + * @return {ReadStream|null} */ event.getFileStream = function( file, options = {} ) { const fileStream = this.fileStreamHandler.getFileStreamerForType( file ); @@ -42,8 +40,6 @@ class FileStreamHandlerPlugin extends PluginInterface { * @param {String} file * @param {Object} [options={}] * @param {Function} [errCallback=null] - * - * @return void */ event.streamFile = function( file, options = {}, errCallback = null ) { const fileStream = event.getFileStream( file, options ); @@ -61,7 +57,7 @@ class FileStreamHandlerPlugin extends PluginInterface { /** * @brief Gets the plugin middlewares to attach to the event request * - * @return Array + * @return {Array} */ getPluginMiddleware() { return [{ diff --git a/server/plugins/available_plugins/logger_plugin.js b/server/plugins/available_plugins/logger_plugin.js index ed721032..ebc9016c 100644 --- a/server/plugins/available_plugins/logger_plugin.js +++ b/server/plugins/available_plugins/logger_plugin.js @@ -18,8 +18,6 @@ class LoggerPlugin extends PluginInterface { * @brief Attaches a process.log function for easier use * * @param {Server} server - * - * @return void */ setServerOnRuntime( server ) { if ( this.options.attachToProcess === true ) @@ -31,7 +29,7 @@ class LoggerPlugin extends PluginInterface { * * @details This MUST be called AFTER the setOptions because once created this will not respect the options * - * @return Logger + * @return {Logger} */ getLogger() { if ( this.logger === null || this.logger === undefined ) { @@ -49,8 +47,6 @@ class LoggerPlugin extends PluginInterface { * @details Events attached: error, on_error, finished, redirect, cleanUp * * @param {EventRequest} event - * - * @return void */ attachEventsToEventRequest( event ) { const logger = this.getLogger(); @@ -87,7 +83,7 @@ class LoggerPlugin extends PluginInterface { /** * @brief Gets the plugin middleware, responsible for attaching logging functionality to the event request and adding a logger * - * @return Array + * @return {Array} */ getPluginMiddleware() { const logger = this.getLogger(); diff --git a/server/plugins/available_plugins/rate_limits_plugin.js b/server/plugins/available_plugins/rate_limits_plugin.js index 411afb16..a9f1e385 100644 --- a/server/plugins/available_plugins/rate_limits_plugin.js +++ b/server/plugins/available_plugins/rate_limits_plugin.js @@ -8,7 +8,7 @@ const DataServer = require( './../../components/caching/data_server' ); /** * @brief Status code send during strict policy in case of rate limit reached * - * @var Number TOO_MANY_REQUESTS_STATUS_CODE + * @var {Number} TOO_MANY_REQUESTS_STATUS_CODE */ const TOO_MANY_REQUESTS_STATUS_CODE = 429; @@ -17,7 +17,7 @@ const TOO_MANY_REQUESTS_STATUS_CODE = 429; * * @details This policy will let the client connect freely but a flag will be set that it was rate limited * - * @var String PERMISSIVE_POLICY + * @var {String} PERMISSIVE_POLICY */ const PERMISSIVE_POLICY = 'permissive'; @@ -30,7 +30,7 @@ const PERMISSIVE_POLICY = 'permissive'; * The first connection delay policy hit in the case of many will be used to determine the delay time but * all buckets affected by such a connection delay will be affected * - * @var String CONNECTION_DELAY_POLICY + * @var {String} CONNECTION_DELAY_POLICY */ const CONNECTION_DELAY_POLICY = 'connection_delay'; @@ -41,7 +41,7 @@ const CONNECTION_DELAY_POLICY = 'connection_delay'; * This will also include a Retry-After header. If this policy is triggered, stopPropagation will be ignored and * the request will be immediately canceled * - * @var String STRICT_POLICY + * @var {String} STRICT_POLICY */ const STRICT_POLICY = 'strict'; @@ -93,8 +93,6 @@ class RateLimitsPlugin extends PluginInterface { * @brief Does rule validation for each parameter * * @param {Object} options - * - * @return void */ validateRule( options ) { if ( @@ -125,12 +123,12 @@ class RateLimitsPlugin extends PluginInterface { } /** - * Gets a Bucket from the rule options and key + * @brief Gets a Bucket from the rule options and key * * @param {String} key * @param {Object} options * - * @return Bucket + * @return {Bucket} */ async getBucketFromOptions( key, options ) { if ( typeof this.buckets[key] !== 'undefined' ) @@ -149,12 +147,10 @@ class RateLimitsPlugin extends PluginInterface { } /** - * If a DataStore was not passed, gets the data store from the server er_data_server plugin, otherwise - * creates a new datastore with persistence and not ttl. + * @details If a DataStore was not passed, gets the data store from the server er_data_server plugin, otherwise + * creates a new datastore with persistence and not ttl. * * @param {Server} server - * - * @return void */ setServerOnRuntime( server ) { if ( this.dataStore === null ) { @@ -168,12 +164,13 @@ class RateLimitsPlugin extends PluginInterface { } /** - * Global middleware that can be used to dynamically rate limit requests - * Creates a default data store if one is not set. + * @brief Global middleware that can be used to dynamically rate limit requests + * + * @details Creates a default data store if one is not set. * * @param {Object} rule * - * @return Function + * @return {Function} */ rateLimit( rule ) { if ( ! this.dataStore ) { @@ -200,23 +197,22 @@ class RateLimitsPlugin extends PluginInterface { } /** - * Gets the plugin middlewares + * @brief Gets the plugin middlewares * - * @returns`Array + * @return {Array} */ getPluginMiddleware() { return [{ handler: ( event ) => this._rateLimit( event, this.rules.slice() ) }]; } /** - * Checks whether the client's ip has reached the limit of requests. - * Adds a rateLimited key IF one is not set already. This also detects that this is the first time - * this plugin is invoked and will attach an on `cleanUp` event + * @brief Checks whether the client's ip has reached the limit of requests. + * + * @details Adds a rateLimited key IF one is not set already. This also detects that this is the first time + * this plugin is invoked and will attach an on `cleanUp` event * * @param {EventRequest} eventRequest * @param {Array} rules - * - * @return void */ async _rateLimit( eventRequest, rules ) { if ( eventRequest.isFinished() ) @@ -270,13 +266,12 @@ class RateLimitsPlugin extends PluginInterface { } /** - * Returns true if the request has been rate limited and a retry after should be sent, - * otherwise return false + * @details Returns true if the request has been rate limited and a retry after should be sent, otherwise return false * * @param {Object} rule * @param {Bucket} bucket * - * @returns Promise + * @returns {Promise} */ async _shouldRateLimitRule( rule, bucket ) { return new Promise(( resolve, reject ) => { @@ -314,12 +309,10 @@ class RateLimitsPlugin extends PluginInterface { } /** - * Sends a 429 response whenever a request was rateLimited + * @brief Sends a 429 response whenever a request was rateLimited * * @param {EventRequest} eventRequest * @param {Number} retryAfterTime - * - * @return void */ async sendRetryAfterResponse( eventRequest, retryAfterTime ) { await eventRequest.sendError({ diff --git a/server/plugins/available_plugins/response_cache_plugin.js b/server/plugins/available_plugins/response_cache_plugin.js index 624955dc..bd0c636a 100644 --- a/server/plugins/available_plugins/response_cache_plugin.js +++ b/server/plugins/available_plugins/response_cache_plugin.js @@ -20,7 +20,7 @@ class ResponseCachePlugin extends PluginInterface { /** * @brief Dependent on a cache server created by the event request * - * @return Array + * @return {Array} */ getPluginDependencies() { return ['er_data_server']; @@ -30,8 +30,6 @@ class ResponseCachePlugin extends PluginInterface { * @brief Creates a rcp namespace to be used * * @param {Server} server - * - * @return void */ setServerOnRuntime( server ) { this.dataServer = server.getPlugin( 'er_data_server' ).getServer(); @@ -48,7 +46,7 @@ class ResponseCachePlugin extends PluginInterface { * * @param {EventRequest} event * - * @return String + * @return {String} */ getCacheId( event ) { let cacheId = event.path; @@ -71,7 +69,7 @@ class ResponseCachePlugin extends PluginInterface { * * @param {EventRequest} event * - * @return Number + * @return {Number} */ getTimeToLive( event ) { const config = event.currentResponseCacheConfig; @@ -84,7 +82,7 @@ class ResponseCachePlugin extends PluginInterface { } /** - * @return Array + * @return {Array} */ getPluginMiddleware() { const pluginMiddleware = { diff --git a/server/plugins/available_plugins/security_plugin.js b/server/plugins/available_plugins/security_plugin.js index 8ed9abad..7aafed77 100644 --- a/server/plugins/available_plugins/security_plugin.js +++ b/server/plugins/available_plugins/security_plugin.js @@ -23,7 +23,7 @@ class SecurityPlugin extends PluginInterface { /** * @brief Attaches all the security modules * - * @return Array + * @return {Array} */ getPluginMiddleware() { const middlewares = []; diff --git a/server/plugins/available_plugins/session_plugin.js b/server/plugins/available_plugins/session_plugin.js index 52fb6c2c..7418e43f 100644 --- a/server/plugins/available_plugins/session_plugin.js +++ b/server/plugins/available_plugins/session_plugin.js @@ -4,7 +4,7 @@ const PluginInterface = require( './../plugin_interface' ); const Session = require( '../../components/session/session' ); /** - * @brief Adds session the the event request + * @brief Adds session in the event request */ class SessionPlugin extends PluginInterface { constructor( id, options = {} ) { @@ -15,7 +15,7 @@ class SessionPlugin extends PluginInterface { /** * @brief This plugin depends on having a cache * - * @return Array + * @return {Array} */ getPluginDependencies() { return ['er_data_server']; @@ -25,21 +25,19 @@ class SessionPlugin extends PluginInterface { * @brief creates the namespace when attaching to the server * * @param {Server} server - * - * @return void */ setServerOnRuntime( server ) { this.dataServer = server.er_data_server.getServer(); } /** - * Adds a session to the event request + * @brief Adds a session to the event request * - * Even tho the cleanUp will remove the event.session - * the event.session.saveSession() in the send - * has already queued up the session save so it will still execute. + * @details Even tho the cleanUp will remove the event.session + * the event.session.saveSession() in the send + * has already queued up the session save so it will still execute. * - * @return Array + * @return {Array} */ getPluginMiddleware() { return [{ diff --git a/server/plugins/available_plugins/static_resources_plugin.js b/server/plugins/available_plugins/static_resources_plugin.js index dc065cfd..b9b25e05 100644 --- a/server/plugins/available_plugins/static_resources_plugin.js +++ b/server/plugins/available_plugins/static_resources_plugin.js @@ -41,7 +41,7 @@ class StaticResourcesPlugin extends PluginInterface { /** * @brief Sets the given path as the static path where resources can be delivered easily * - * @return Array + * @return {Array} */ getPluginMiddleware() { const pluginMiddlewares = this._getPluginMiddlewares(); @@ -51,7 +51,7 @@ class StaticResourcesPlugin extends PluginInterface { } /** - * Wrapper for getPluginMiddleware + * @brief Wrapper for getPluginMiddleware */ _getPluginMiddlewares() { const type = typeof this.options.type === 'number' @@ -86,7 +86,7 @@ class StaticResourcesPlugin extends PluginInterface { } /** - * Sets paths that follow the rules defined in StaticResourcesPlugin.DYNAMIC + * @brief Sets paths that follow the rules defined in StaticResourcesPlugin.DYNAMIC * * @see StaticResourcesPlugin.DYNAMIC * @@ -131,9 +131,9 @@ class StaticResourcesPlugin extends PluginInterface { } /** - * Sets paths that follow the rules defined in StaticResourcesPlugin.ABSOLUTE + * @brief Sets paths that follow the rules defined in StaticResourcesPlugin.ABSOLUTE * - * @see StaticResourcesPlugin.ABSOLUTE + * @see StaticResourcesPlugin.ABSOLUTE */ _setAbsolutePaths( paths, cacheControl, useEtag, strong ) { const pluginMiddlewares = []; @@ -176,8 +176,9 @@ class StaticResourcesPlugin extends PluginInterface { } /** - * Finds a file starting from a dir - * If start Path is a file, then it will be returned directly :) + * @brief Finds a file starting from a dir + * + * @details If start Path is a file, then it will be returned directly :) * * @param {String} startPath * @param {String} fileToFind @@ -208,8 +209,9 @@ class StaticResourcesPlugin extends PluginInterface { } /** - * Sends a given file. - * Sets the correct Content-Type header as well as the correct status code + * @brief Sends a given file. + * + * @details Sets the correct Content-Type header as well as the correct status code * * @param {EventRequest} event * @param {String} file diff --git a/server/plugins/available_plugins/templating_engine_plugin.js b/server/plugins/available_plugins/templating_engine_plugin.js index 26a0c23d..3c0c4404 100644 --- a/server/plugins/available_plugins/templating_engine_plugin.js +++ b/server/plugins/available_plugins/templating_engine_plugin.js @@ -26,8 +26,6 @@ class TemplatingEnginePlugin extends PluginInterface { * @brief Attaches a render function to the event request * * @param {EventRequest} eventRequest - * - * @return void */ attachRenderFunction( eventRequest ) { /** @@ -36,7 +34,7 @@ class TemplatingEnginePlugin extends PluginInterface { * @param {String} templateName * @param {Object} variables * - * @return Promise + * @return {Promise} */ eventRequest.render = ( templateName, variables = {} ) => { return new Promise( async ( resolve,reject ) => { @@ -68,6 +66,9 @@ class TemplatingEnginePlugin extends PluginInterface { * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Function/bind * * @param {Object} options + * @param {Function} options.render - Render function to call + * @param {String} options.templateDir - Absolute path to the template dir + * @param {String} options.templateExtension - The extension fo the templating engine */ setOptions( options ) { const defaultTemplatingEngine = new DefaultTemplatingEngine(); diff --git a/server/plugins/available_plugins/timeout_plugin.js b/server/plugins/available_plugins/timeout_plugin.js index 4f0b407d..31b15a0a 100644 --- a/server/plugins/available_plugins/timeout_plugin.js +++ b/server/plugins/available_plugins/timeout_plugin.js @@ -17,6 +17,10 @@ class TimeoutPlugin extends PluginInterface { /** * @inheritDoc + * + * @param {Object} options + * @param {Number} options.timeout - Time in milliseconds after which the request should be finished + * @param {Function} options.callback - callback when a timeout happens */ setOptions( options ) { super.setOptions( options ); @@ -37,8 +41,6 @@ class TimeoutPlugin extends PluginInterface { * * @param {EventRequest} event * @param {Number} timeout - * - * @return void */ setTimeout( event, timeout ) { event.response.setTimeout( timeout, () => { @@ -53,7 +55,7 @@ class TimeoutPlugin extends PluginInterface { * @details Sets a new clearTimeout function of the event, listens for cleanUp event from the eventRequest and clears the * internal timeout * - * @return Array + * @return {Array} */ getPluginMiddleware() { const pluginMiddleware = { diff --git a/server/plugins/available_plugins/validation_plugin.js b/server/plugins/available_plugins/validation_plugin.js index f9507629..1e00eab7 100644 --- a/server/plugins/available_plugins/validation_plugin.js +++ b/server/plugins/available_plugins/validation_plugin.js @@ -18,6 +18,7 @@ class ValidationPlugin extends PluginInterface { /** * @param {Object} options + * @param {Object} options.failureCallback - Function to call when there is a validation failure */ setOptions( options ) { super.setOptions( options ); @@ -37,7 +38,7 @@ class ValidationPlugin extends PluginInterface { * @param {Object} validationRules * @param {Function} failureCallback * - * @return Function + * @return {Function} */ validate( validationRules, failureCallback ) { failureCallback = typeof failureCallback === 'undefined' ? this.failureCallback : failureCallback; diff --git a/server/plugins/plugin_interface.js b/server/plugins/plugin_interface.js index 2b1e1d93..45737e6e 100644 --- a/server/plugins/plugin_interface.js +++ b/server/plugins/plugin_interface.js @@ -18,7 +18,7 @@ class PluginInterface { /** * @brief Returns the pluginId * - * @return String + * @return {String} */ getPluginId() { return this.pluginId; @@ -29,7 +29,7 @@ class PluginInterface { * * @details If the dependencies are not added to the server, then an error will be thrown * - * @return Array + * @return {Array} */ getPluginDependencies() { return []; @@ -41,8 +41,6 @@ class PluginInterface { * @details This method should attach to any events dispatched by the server * * @param {Server} server - * - * @return void */ setServerOnRuntime( server ) { } @@ -51,8 +49,6 @@ class PluginInterface { * @brief Sets new options for the plugin * * @param {Object} options - * - * @return void */ setOptions( options ) { this.options = options; @@ -64,7 +60,7 @@ class PluginInterface { * @details These will be retrieved by the server and each one will be added to the router * They must be normal middleware objects implementing handler, route, method keys or instances of Route * - * @return Array + * @return {Array} */ getPluginMiddleware() { return []; diff --git a/server/plugins/plugin_manager.js b/server/plugins/plugin_manager.js index 3a356bcc..bbcc867a 100644 --- a/server/plugins/plugin_manager.js +++ b/server/plugins/plugin_manager.js @@ -12,8 +12,6 @@ class PluginManager { * @brief Adds a plugin to the Manager * * @param {PluginInterface} plugin - * - * @return void */ addPlugin( plugin ) { if ( this.isValidPlugin( plugin ) ) @@ -27,7 +25,7 @@ class PluginManager { * * @param {String} id * - * @return Boolean + * @return {Boolean} */ hasPlugin( id ) { return typeof this.plugins[id] !== 'undefined'; @@ -37,8 +35,6 @@ class PluginManager { * @brief Removes a plugin by id * * @param {String} id - * - * @return void */ removePlugin( id ) { delete this.plugins[id]; @@ -47,7 +43,7 @@ class PluginManager { /** * @brief Get all plugins added to the plugin manager * - * @return Array + * @return {Array} */ getAllPluginIds() { return Object.keys( this.plugins ); @@ -58,7 +54,7 @@ class PluginManager { * * @param {PluginInterface|Object} plugin * - * @return Boolean + * @return {Boolean} */ isValidPlugin( plugin ) { return typeof plugin.getPluginId === 'function' @@ -73,7 +69,7 @@ class PluginManager { * * @param {String} id * - * @return PluginInterface + * @return {PluginInterface} */ getPlugin( id ) { if ( ! this.hasPlugin( id ) ) diff --git a/server/server.js b/server/server.js index d774a392..6b39dba9 100644 --- a/server/server.js +++ b/server/server.js @@ -52,7 +52,7 @@ class Server extends EventEmitter { /** * @brief Adds a new middleware to the router * - * @return Server + * @return {Server} */ define() { this.router.define.apply( this.router, arguments ); @@ -62,8 +62,6 @@ class Server extends EventEmitter { /** * @brief Sets up the default plugins - * - * @return void */ setUpDefaultPlugins() { // attached like this to enable smart autocomplete in IDE's @@ -112,7 +110,7 @@ class Server extends EventEmitter { /** * @brief Returns the plugin manager * - * @return PluginManager + * @return {PluginManager} */ getPluginManager() { return this.pluginManager; @@ -121,7 +119,7 @@ class Server extends EventEmitter { /** * @brief Creates a new router * - * @return Router + * @return {Router} */ Router() { return new RouterClass(); @@ -136,7 +134,7 @@ class Server extends EventEmitter { * @param {PluginInterface|Object|String} plugin * @param {Object} options * - * @return Server + * @return {Server} */ apply( plugin, options = null ) { if ( typeof plugin === 'string' ) @@ -157,8 +155,6 @@ class Server extends EventEmitter { * @brief Attaches a PluginInterface to the server * * @param {PluginInterface} plugin - * - * @return void */ _attachPlugin( plugin ) { const pluginDependencies = plugin.getPluginDependencies(); @@ -183,7 +179,7 @@ class Server extends EventEmitter { * * @param {String|PluginInterface} pluginId * - * @return PluginInterface + * @return {PluginInterface} */ getPlugin( pluginId ) { const id = typeof pluginId === 'string' ? pluginId : pluginId.getPluginId(); @@ -199,7 +195,7 @@ class Server extends EventEmitter { * * @param {String|PluginInterface} pluginId * - * @return Boolean + * @return {Boolean} */ hasPlugin( pluginId ) { const id = typeof pluginId === 'string' ? pluginId : pluginId.getPluginId(); @@ -210,7 +206,7 @@ class Server extends EventEmitter { /** * @brief Callback for the http.createServer * - * @return Function + * @return {Function} */ attach() { return ( request, response ) => { @@ -264,7 +260,7 @@ class Server extends EventEmitter { /** * @brief Starts the server on the given port * - * @return Server + * @return {Server} */ listen() { const httpServer = http.createServer( this.attach() ); diff --git a/server/tester/mock.js b/server/tester/mock.js index e423cf1a..4cac1b58 100644 --- a/server/tester/mock.js +++ b/server/tester/mock.js @@ -8,7 +8,7 @@ const Mocker = require( './mocker' ); * * @param {*} objectToMock * - * @return Function + * @return {Function} */ let Mock = function ( objectToMock ) { if ( typeof objectToMock === 'object' ) { @@ -17,7 +17,7 @@ let Mock = function ( objectToMock ) { * * @param {Object} mockMethodOptions * - * @return Object + * @return {Object} */ objectToMock._mock = ( mockMethodOptions )=> { Mocker( objectToMock, mockMethodOptions ); @@ -34,7 +34,7 @@ let Mock = function ( objectToMock ) { * * @param {Object} mockMethodOptions * - * @return MockedClass + * @return {MockedClass} */ _mock( mockMethodOptions ) { Mocker( this, mockMethodOptions ); diff --git a/server/tester/mocker.js b/server/tester/mocker.js index c7cdbc9d..8a015a9f 100644 --- a/server/tester/mocker.js +++ b/server/tester/mocker.js @@ -43,8 +43,6 @@ class Mocker { /** * @brief Creates the mocked method that should later be attached to the mocked class - * - * @return void */ setUpMockedMethod() { let functionCalled = 0; @@ -65,8 +63,6 @@ class Mocker { * @brief Assert whether correct with arguments are passed * * @param {Array} args - * - * @return void */ assertWithArguments( args ) { if ( this.hasWithArguments() ) { @@ -89,8 +85,6 @@ class Mocker { /** * @brief Attaches the mocked method to the mocked class - * - * @return void */ attachMockedMethod() { let prototypeSpider = typeof this.mockedClass.prototype === 'undefined' @@ -110,7 +104,7 @@ class Mocker { /** * @brief Checks to see if there are with arguments * - * @return Boolean + * @return {Boolean} */ hasWithArguments() { return this.withArguments.length > 0; @@ -119,7 +113,7 @@ class Mocker { /** * @brief Gets the next with arguments * - * @return Array + * @return {Array} */ getWithArguments() { return this.withArguments.length === 1 ? this.withArguments[0] : this.withArguments.shift(); @@ -130,7 +124,7 @@ class Mocker { * * @param {Array} args * - * @return mixed + * @return {*} */ getNextExecutionFunction( args ) { let functionToExecute = this.executionBlock.length > 1 ? this.executionBlock.shift() : this.executionBlock[0]; diff --git a/server/tester/tester.js b/server/tester/tester.js index b6d4cbdf..47d8178a 100644 --- a/server/tester/tester.js +++ b/server/tester/tester.js @@ -41,8 +41,6 @@ class Tester { * @details This is done so we can run the test many times per instance * * @param {Object} options - * - * @return void */ initialize( options ) { this.errors = []; @@ -121,7 +119,7 @@ class Tester { * * @param {Object} test * - * @return Array + * @return {Array} */ formatTest( test ) { if ( typeof test !== 'object' || typeof test.message !== 'string' || typeof test.test !== 'function' ) @@ -176,8 +174,6 @@ class Tester { * @brief Adds the given test to the queue * * @param {Object} test - * - * @return void */ addTest( test ) { this.tests = this.tests.concat( this.formatTest( test ) ); @@ -187,8 +183,6 @@ class Tester { * @brief Called if the test passes successfully * * @details It will output the index of the test as well as the message - * - * @return void */ successCallback( test ) { test.status = TEST_STATUSES.success; @@ -225,8 +219,6 @@ class Tester { /** * @brief Called when all the tests have finished - * - * @return void */ finished() { this.hasFinished = true; @@ -250,8 +242,6 @@ class Tester { * * @param {Object} test * @param {*} err - * - * @return void */ doneCallback( test, err ) { if ( this.hasFinished || this.stop ) @@ -271,7 +261,7 @@ class Tester { * * @param {Object} test * - * @return Boolean + * @return {Boolean} */ checkTestStatus( test ) { switch ( test.status ) { @@ -292,8 +282,6 @@ class Tester { /** * @brief Call next test - * - * @return void */ done() { let test = this.tests.shift(); @@ -350,8 +338,6 @@ class Tester { * @details This will produce an output directly to the console of the user * * @param {Object} options - * - * @return void */ runAllTests( options = {} ) { this.initialize( options );