From fbc23ae4903c9a92f66f7f8639c07610572e9f3a Mon Sep 17 00:00:00 2001 From: alexandershpak <35569337+alexandershpak@users.noreply.github.com> Date: Wed, 20 Feb 2019 15:03:44 +0300 Subject: [PATCH 01/17] bug(fix): Change order of controller's log files (ENG-584) --- src/logger/index.js | 35 ++++++++++++++++++++++++++++++++--- 1 file changed, 32 insertions(+), 3 deletions(-) diff --git a/src/logger/index.js b/src/logger/index.js index 3be3f1e8d..2432fd2f3 100644 --- a/src/logger/index.js +++ b/src/logger/index.js @@ -13,9 +13,20 @@ const winston = require('winston'); const config = require('../config'); - +const fs = require('fs'); const MESSAGE = Symbol.for('message'); +const dirname = config.get('Service:LogsDirectory') + +// Create the log directory if it does not exist +try { + if (!fs.existsSync(dirname)) { + fs.mkdirSync(dirname); + } +} catch (e) { + // can't initialize log folder +} + const levels = { error: 0, warn: 1, @@ -67,13 +78,31 @@ const logger = winston.createLogger({ prepareObjectLogs(), formattedJson() ), - filename: 'iofog-controller.log', - dirname: config.get('Service:LogsDirectory'), + filename: 'iofog-controller.0.log', + dirname: dirname, maxsize: config.get('Service:LogsFileSize'), + rotationFormat: function() { + return getFormattedLogName(); + } }), ], }); +// logFileName pattern similar to agent +function getFormattedLogName() { + if (fs.existsSync(dirname)) { + fs.readdirSync(dirname).reverse().forEach(file => { + const path = dirname + '/' + file + if (fs.existsSync(path)) { + const strNumber = file.replace('iofog-controller.', '').replace('.log', '') + const number = parseInt(strNumber) + 1 + fs.renameSync(path, path.replace(strNumber, number)) + } + }); + } + return '' +} + logger.add(new winston.transports.Console({ level: 'info', format: winston.format((log) => { From e03ef7a0edb98d181e2423a989f16a63da657673 Mon Sep 17 00:00:00 2001 From: MaksimChepelev Date: Wed, 20 Feb 2019 15:06:41 +0300 Subject: [PATCH 02/17] feat(cli): fix help (ENG-742) --- src/cli/connector.js | 2 +- src/cli/controller.js | 2 +- src/cli/diagnostics.js | 2 +- src/cli/flow.js | 2 +- src/cli/registry.js | 2 +- src/cli/tunnel.js | 2 +- src/cli/user.js | 2 +- 7 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/cli/connector.js b/src/cli/connector.js index eaffda741..83b1f2dcd 100644 --- a/src/cli/connector.js +++ b/src/cli/connector.js @@ -101,7 +101,7 @@ class Connector extends BaseCLIHandler { break; case constants.CMD_HELP: default: - return this.help([constants.CMD_LIST]) + return this.help([]) } } catch (error) { this.handleCLIError(error, args.argv); diff --git a/src/cli/controller.js b/src/cli/controller.js index 8793bb5ce..dda25a068 100644 --- a/src/cli/controller.js +++ b/src/cli/controller.js @@ -63,7 +63,7 @@ class Controller extends BaseCLIHandler { break; case constants.CMD_HELP: default: - return this.help([constants.CMD_LIST]) + return this.help([]) } } catch (error) { this.handleCLIError(error, args.argv); diff --git a/src/cli/diagnostics.js b/src/cli/diagnostics.js index 04a6ab8fb..62b08001d 100644 --- a/src/cli/diagnostics.js +++ b/src/cli/diagnostics.js @@ -103,7 +103,7 @@ class Diagnostics extends BaseCLIHandler { break; case constants.CMD_HELP: default: - return this.help([constants.CMD_LIST]) + return this.help([]) } } catch (error) { this.handleCLIError(error, args.argv); diff --git a/src/cli/flow.js b/src/cli/flow.js index f0918ac47..99bcfcbba 100644 --- a/src/cli/flow.js +++ b/src/cli/flow.js @@ -107,7 +107,7 @@ class Flow extends BaseCLIHandler { break; case constants.CMD_HELP: default: - return this.help([constants.CMD_LIST]) + return this.help([]) } } catch (error) { this.handleCLIError(error, args.argv); diff --git a/src/cli/registry.js b/src/cli/registry.js index 51b0397a7..59ba006ab 100644 --- a/src/cli/registry.js +++ b/src/cli/registry.js @@ -111,7 +111,7 @@ class Registry extends BaseCLIHandler { break; case constants.CMD_HELP: default: - return this.help([constants.CMD_LIST]) + return this.help([]) } } catch (error) { this.handleCLIError(error, args.argv); diff --git a/src/cli/tunnel.js b/src/cli/tunnel.js index 8c54cb0c0..cc24be082 100644 --- a/src/cli/tunnel.js +++ b/src/cli/tunnel.js @@ -91,7 +91,7 @@ class Tunnel extends BaseCLIHandler { await _executeCase(tunnelCommand, constants.CMD_LIST, _tunnelList, false); break; default: - return this.help([constants.CMD_HELP]) + return this.help([]) } } catch (error) { this.handleCLIError(error, args.argv); diff --git a/src/cli/user.js b/src/cli/user.js index 8154cb8d7..d858c4f37 100644 --- a/src/cli/user.js +++ b/src/cli/user.js @@ -101,7 +101,7 @@ class User extends BaseCLIHandler { break; case constants.CMD_HELP: default: - return this.help([constants.CMD_LIST]) + return this.help([]) } } catch (error) { this.handleCLIError(error, args.argv); From f2277df4a7bc8307433c85d9e9d94c3f849579ed Mon Sep 17 00:00:00 2001 From: alexandershpak <35569337+alexandershpak@users.noreply.github.com> Date: Wed, 20 Feb 2019 16:06:15 +0300 Subject: [PATCH 03/17] bug(fix): Change order of controller's log files update postinstall script for version less 1.0.37 (ENG-584) (#548) --- scripts/postinstall.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/scripts/postinstall.js b/scripts/postinstall.js index 9d8c5c076..98e21ad49 100644 --- a/scripts/postinstall.js +++ b/scripts/postinstall.js @@ -15,6 +15,7 @@ const os = require('os'); const execSync = require('child_process').execSync; const fs = require('fs'); const semver = require('semver'); +const config = require('../src/config'); const currentVersion = require('../package').version; const {restoreDBs, restoreConfigs, INSTALLATION_VARIABLES_FILE} = require('./util'); @@ -41,6 +42,10 @@ function postinstall() { console.log('upgrading from version <= 1.0.30 :'); updateEncryptionMethod(); } + if (semver.satisfies(prevVersion, '<=1.0.37')) { + console.log('upgrading from version <= 1.0.37 :'); + updateLogName(); + } fs.unlinkSync(INSTALLATION_VARIABLES_FILE); } catch (e) { @@ -151,6 +156,24 @@ function updateEncryptionMethod() { updateEncryptionMethodForEmailService(prodConfig, decryptTextVer30); } +function updateLogName() { + console.log(' updating log name in '); + const dirname = config.get('Service:LogsDirectory') + + if (fs.existsSync(dirname)) { + fs.readdirSync(dirname).forEach(file => { + const path = dirname + '/' + file + if (fs.existsSync(path)) { + fs.unlinkSync(path, function(err) { + if (err) return console.log(err); + console.log('log deleted successfully'); + }) + } + }); + } + +} + module.exports = { postinstall: postinstall }; \ No newline at end of file From 705a2afe1239219b3f380dbdbc5546cd1af619c3 Mon Sep 17 00:00:00 2001 From: MaksimChepelev Date: Wed, 20 Feb 2019 16:08:07 +0300 Subject: [PATCH 04/17] feat(config): add default config values in js code (#549) * feat(config): add dafault config values in js code increase stability. this allow to work without any config fix memory leack problem in jobs Closes ENG-630 * feat(config): add dafault config values in js code fix formatting Closes ENG-630 * 9!!! --- src/config/constants.js | 33 +++++++++++++++++++++++++++++++++ src/config/index.js | 3 ++- 2 files changed, 35 insertions(+), 1 deletion(-) create mode 100644 src/config/constants.js diff --git a/src/config/constants.js b/src/config/constants.js new file mode 100644 index 000000000..21dc6e958 --- /dev/null +++ b/src/config/constants.js @@ -0,0 +1,33 @@ +/* + * ******************************************************************************* + * * Copyright (c) 2019 Edgeworx, Inc. + * * + * * This program and the accompanying materials are made available under the + * * terms of the Eclipse Public License v. 2.0 which is available at + * * http://www.eclipse.org/legal/epl-2.0 + * * + * * SPDX-License-Identifier: EPL-2.0 + * ******************************************************************************* + * + */ + +module.exports = { + 'App:Name': 'iofog-controller', + + 'Server:Port': 54421, + 'Server:DevMode': false, + + 'Email:ActivationEnabled': false, + 'Email:HomeUrl': 'https://iofog.org', + + 'Service:LogsDirectory': '/var/log/iofog-controller', + 'Service:LogsFileSize': 1048576, + + 'Settings:DefaultJobIntervalSeconds': 120, + 'Settings:UserTokenExpirationIntervalSeconds': 3600, + 'Settings:FogTokenExpirationIntervalSeconds': 3600, + 'Settings:FogStatusUpdateIntervalSeconds': 120, + 'Settings:FogStatusFrequencySeconds': 60, + + 'Diagnostics:DiagnosticDir': 'diagnostic', +} \ No newline at end of file diff --git a/src/config/index.js b/src/config/index.js index 8b10ec58d..bc5897449 100644 --- a/src/config/index.js +++ b/src/config/index.js @@ -13,6 +13,7 @@ const nconf = require('nconf') const path = require('path') +const constants = require('./constants'); class Config { constructor() { @@ -22,7 +23,7 @@ class Config { } get(key) { - return nconf.get(key) + return nconf.get(key) || constants[key] } set(key, value) { From 8ddae16eee7b5cdee1e8f8ffc34ac6e54966c8e0 Mon Sep 17 00:00:00 2001 From: Railag Date: Thu, 21 Feb 2019 14:49:21 +0300 Subject: [PATCH 05/17] bug(fix) fixing seeds fogTypeId rollback (ENG-559) --- .../seeders/20180928112152-insert-iofog-type.js | 13 +++++++++++-- 1 file changed, 11 insertions(+), 2 deletions(-) diff --git a/src/sequelize/seeders/20180928112152-insert-iofog-type.js b/src/sequelize/seeders/20180928112152-insert-iofog-type.js index 306fe433a..5a375a6b5 100644 --- a/src/sequelize/seeders/20180928112152-insert-iofog-type.js +++ b/src/sequelize/seeders/20180928112152-insert-iofog-type.js @@ -30,10 +30,19 @@ module.exports = { hal_catalog_item_id: 3, bluetooth_catalog_item_id: 2 } - ]); + ]).then(() => { + return queryInterface.bulkUpdate('Fogs', + { + fog_type_id: 0 + }, + { + fog_type_id: null + } + ) + }); }, down: (queryInterface, Sequelize) => { - return queryInterface.bulkDelete('FogTypes', null, {}); + return queryInterface.bulkDelete('FogTypes', null, {}) } }; \ No newline at end of file From f00f2b4a20e6ba6d77a158f33d2bd90b7cb6e40e Mon Sep 17 00:00:00 2001 From: MaksimChepelev Date: Fri, 22 Feb 2019 14:09:14 +0300 Subject: [PATCH 06/17] feat(logger): fix logger rotation (#557) --- src/cli/base-cli-handler.js | 17 +++++++++-------- src/logger/index.js | 12 ++++++++++-- 2 files changed, 19 insertions(+), 10 deletions(-) diff --git a/src/cli/base-cli-handler.js b/src/cli/base-cli-handler.js index 45cabca57..c98ac5947 100644 --- a/src/cli/base-cli-handler.js +++ b/src/cli/base-cli-handler.js @@ -17,6 +17,7 @@ const AppHelper = require('../helpers/app-helper'); const Errors = require('../helpers/errors'); const ErrorMessages = require('../helpers/error-messages'); const constants = require('../helpers/constants'); +const logger = require('../logger') class CLIHandler { constructor() { @@ -66,7 +67,7 @@ class CLIHandler { content: 'Fog Controller project for Eclipse IoFog @ iofog.org \\nCopyright (c) 2018 Edgeworx, Inc.', } ].concat(sections); - console.log(commandLineUsage(usage)) + logger.cliRes(commandLineUsage(usage)) } helpAll(show = [], showOptions = true, hasCommands = true, additionalSection = []) { @@ -99,28 +100,28 @@ class CLIHandler { content: 'Fog Controller project for Eclipse IoFog @ iofog.org \\nCopyright (c) 2018 Edgeworx, Inc.', } ].concat(sections); - console.log(commandLineUsage(usage)) + logger.cliRes(commandLineUsage(usage)) } handleCLIError(error, args) { switch (error.name) { case "UNKNOWN_OPTION": - console.log("Invalid argument '" + error.optionName.split('-').join('') + "'"); + logger.error("Invalid argument '" + error.optionName.split('-').join('') + "'"); break; case "UNKNOWN_VALUE": if (this.commands[args[0]] && args[1] === 'help') { return this.helpSome([args[0]]); } - console.log("Invalid value " + error.value); + logger.error("Invalid value " + error.value); break; case "InvalidArgumentError": - console.log(error.message); + logger.error(error.message); break; case "InvalidArgumentTypeError": - console.log(error.message); + logger.error(error.message); break; case "ALREADY_SET": - console.log("Parameter '" + error.optionName + "' is used multiple times"); + logger.error("Parameter '" + error.optionName + "' is used multiple times"); break; case 'CLIArgsNotProvidedError': if (this.commands[args[0]]) { @@ -128,7 +129,7 @@ class CLIHandler { } break; default: - console.log(JSON.stringify(error)); + logger.error(JSON.stringify(error)); break; } } diff --git a/src/logger/index.js b/src/logger/index.js index 2432fd2f3..e34efb8ad 100644 --- a/src/logger/index.js +++ b/src/logger/index.js @@ -17,6 +17,7 @@ const fs = require('fs'); const MESSAGE = Symbol.for('message'); const dirname = config.get('Service:LogsDirectory') +const maxsize = config.get('Service:LogsFileSize') // Create the log directory if it does not exist try { @@ -80,7 +81,7 @@ const logger = winston.createLogger({ ), filename: 'iofog-controller.0.log', dirname: dirname, - maxsize: config.get('Service:LogsFileSize'), + maxsize: maxsize, rotationFormat: function() { return getFormattedLogName(); } @@ -91,7 +92,14 @@ const logger = winston.createLogger({ // logFileName pattern similar to agent function getFormattedLogName() { if (fs.existsSync(dirname)) { - fs.readdirSync(dirname).reverse().forEach(file => { + const files = fs.readdirSync(dirname) + const latestFilePath = dirname + '/' + files[0] + + if (files.length === 0 || fs.statSync(latestFilePath).size <= maxsize) { + return '' + } + + files.reverse().forEach(file => { const path = dirname + '/' + file if (fs.existsSync(path)) { const strNumber = file.replace('iofog-controller.', '').replace('.log', '') From c5955359a3a403e05150676ee027176bcb75af20 Mon Sep 17 00:00:00 2001 From: Railag Date: Fri, 22 Feb 2019 14:15:56 +0300 Subject: [PATCH 07/17] bug(fix) updated libs with high vulnerabilities based on npm audit (ENG-691) (#556) --- package.json | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/package.json b/package.json index 47a67e435..a9a42c411 100644 --- a/package.json +++ b/package.json @@ -66,7 +66,7 @@ "ftp": "0.3.10", "helmet": "3.15.0", "jsonschema": "1.2.4", - "moment": "^2.24.0", + "moment": "2.24.0", "morgan": "1.9.1", "nconf": "0.10.0", "newman": "4.3.1", @@ -95,9 +95,9 @@ "chai-http": "4.2.1", "eslint": "5.12.1", "mocha": "5.2.0", - "nyc": "13.1.0", + "newman": "4.3.1", + "nyc": "13.3.0", "sinon": "7.2.3", - "sinon-chai": "3.3.0", - "newman": "4.3.1" + "sinon-chai": "3.3.0" } } From 7a8e0decaac461c1e67f8311fd35b931ccdb17e2 Mon Sep 17 00:00:00 2001 From: Railag Date: Fri, 22 Feb 2019 14:46:05 +0300 Subject: [PATCH 08/17] bug(fix) fixing private registries (ENG-745) (#558) --- src/sequelize/managers/microservice-manager.js | 2 +- src/services/agent-service.js | 2 +- test/src/services/agent-service.test.js | 6 +++--- 3 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/sequelize/managers/microservice-manager.js b/src/sequelize/managers/microservice-manager.js index 4a4e78b26..e1c329f2c 100644 --- a/src/sequelize/managers/microservice-manager.js +++ b/src/sequelize/managers/microservice-manager.js @@ -133,7 +133,7 @@ class MicroserviceManager extends BaseManager { model: Registry, as: 'registry', required: true, - attributes: ['url'] + attributes: ['id'] } ], attributes: ['picture', 'category'] diff --git a/src/services/agent-service.js b/src/services/agent-service.js index 801987aff..868407d82 100644 --- a/src/services/agent-service.js +++ b/src/services/agent-service.js @@ -256,7 +256,7 @@ const getAgentMicroservices = async function (fog, transaction) { rebuild: microservice.rebuild, rootHostAccess: microservice.rootHostAccess, logSize: microservice.logSize, - registryUrl: microservice.catalogItem.registry.url, + registryId: microservice.catalogItem.registry.id, portMappings: microservice.ports, volumeMappings: microservice.volumeMappings, imageSnapshot: microservice.imageSnapshot, diff --git a/test/src/services/agent-service.test.js b/test/src/services/agent-service.test.js index 0cfbf5c74..262e1c5a2 100644 --- a/test/src/services/agent-service.test.js +++ b/test/src/services/agent-service.test.js @@ -749,7 +749,7 @@ describe('Agent Service', () => { } ], registry: { - url: 'testUrl' + id: 10 } }, routes: routes @@ -769,7 +769,7 @@ describe('Agent Service', () => { delete: false, deleteWithCleanup: false, routes: routes, - registryUrl: 'testUrl' + registryId: 10 }] }; @@ -872,7 +872,7 @@ describe('Agent Service', () => { delete: false, deleteWithCleanup: false, routes: routes, - registryUrl: 'testUrl' + registryId: 10 }; const microserviceResponse = { From 20ab841726ff0561b20da11cd69b3d3e823ed225 Mon Sep 17 00:00:00 2001 From: MaksimChepelev Date: Fri, 22 Feb 2019 14:48:00 +0300 Subject: [PATCH 09/17] feat(cli): fix string validation in cli (#559) --- src/cli/base-cli-handler.js | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/src/cli/base-cli-handler.js b/src/cli/base-cli-handler.js index c98ac5947..f51315121 100644 --- a/src/cli/base-cli-handler.js +++ b/src/cli/base-cli-handler.js @@ -280,9 +280,7 @@ function _getCurrentValType(values) { function _validateType(expectedValueType, valType) { let isValidType = true; - if (expectedValueType === 'string' && valType === 'boolean') { - isValidType = false; - } else if ((expectedValueType === 'float' || expectedValueType === 'number') + if ((expectedValueType === 'float' || expectedValueType === 'number') && (valType !== 'float' && valType !== 'number' && valType !== 'integer')) { isValidType = false; } else if (expectedValueType === 'integer' && valType !== 'integer') { From df515132d3de2d6f873d412917a2263a031f676a Mon Sep 17 00:00:00 2001 From: Railag Date: Fri, 22 Feb 2019 16:32:58 +0300 Subject: [PATCH 10/17] bug(fix) filtering agent microservices without images (ENG-560) (#560) * bug(fix) filtering agent microservices without images (ENG-560) * cleanup --- src/services/agent-service.js | 5 +++- test/src/services/agent-service.test.js | 35 ++++++++++++++++++++++--- 2 files changed, 35 insertions(+), 5 deletions(-) diff --git a/src/services/agent-service.js b/src/services/agent-service.js index 868407d82..b01980f58 100644 --- a/src/services/agent-service.js +++ b/src/services/agent-service.js @@ -242,10 +242,13 @@ const getAgentMicroservices = async function (fog, transaction) { const fogTypeId = fog.fogTypeId; const response = []; - for (let microservice of microservices) { + for (const microservice of microservices) { const images = microservice.catalogItem.images; const image = images.find(image => image.fogTypeId === fogTypeId); const imageId = image ? image.containerImage : ''; + if (!imageId || imageId === '') { + continue; + } const routes = await MicroserviceService.getPhysicalConnections(microservice, transaction); diff --git a/test/src/services/agent-service.test.js b/test/src/services/agent-service.test.js index 262e1c5a2..7708288ca 100644 --- a/test/src/services/agent-service.test.js +++ b/test/src/services/agent-service.test.js @@ -730,7 +730,7 @@ describe('Agent Service', () => { const routes = []; - const microservice = { + const microserviceWithValidImage = { uuid: 'testMicroserviceUuid', imageId: '', config: '{}', @@ -755,6 +755,33 @@ describe('Agent Service', () => { routes: routes }; + const microserviceWithInvalidImage = { + uuid: 'testMicroserviceUuid', + imageId: '', + config: '{}', + rebuild: false, + rootHostAccess: false, + logSize: 15, + ports: 'testPorts', + volumeMappings: 'testVolumeMappings', + imageSnapshot: 'testImageSnapshot', + delete: false, + deleteWithCleanup: false, + catalogItem: { + images: [{ + fogTypeId: 3, + containerImage: 'testContainerImage' + } + ], + registry: { + id: 10 + } + }, + routes: routes + }; + + + const microserviceResponse = { microservices: [{ uuid: 'testMicroserviceUuid', @@ -785,7 +812,7 @@ describe('Agent Service', () => { def('subject', () => $subject.getAgentMicroservices($fog, transaction)); - def('findAllMicroservicesResponse', () => Promise.resolve([microservice])); + def('findAllMicroservicesResponse', () => Promise.resolve([microserviceWithValidImage, microserviceWithInvalidImage])); def('getPhysicalConnectionsResponse', () => Promise.resolve(routes)); def('updateResponse', () => Promise.resolve(microserviceResponse)); @@ -811,7 +838,7 @@ describe('Agent Service', () => { context('when MicroserviceManager#findAllActiveFlowMicroservices() succeeds', () => { it('calls MicroserviceService.getPhysicalConnections with correct args', async () => { await $subject; - expect(MicroserviceService.getPhysicalConnections).to.have.been.calledWith(microservice, transaction); + expect(MicroserviceService.getPhysicalConnections).to.have.been.calledWith(microserviceWithValidImage, transaction); }); context('when MicroserviceService#getPhysicalConnections fails', () => { @@ -828,7 +855,7 @@ describe('Agent Service', () => { it('calls MicroserviceManager.update with correct args', async () => { await $subject; expect(MicroserviceManager.update).to.have.been.calledWith({ - uuid: microservice.uuid + uuid: microserviceWithValidImage.uuid }, { rebuild: false }, transaction); From 9755097351381f9f073120c4204acc2491131a2c Mon Sep 17 00:00:00 2001 From: dbusel <10116634+dbusel@users.noreply.github.com> Date: Fri, 22 Feb 2019 17:34:47 +0300 Subject: [PATCH 11/17] enable linting (#561) * re-enabling linting * ESlint errors fix (#555) * feat(core) default configs for microservices progress (ENG-196) (#545) * fix lint errors in test folder * fix lint errors in scripts folder * fix lint errors in src folder * feat(style): fix lint errors (#553) * arguments -> ...args in declaration * some small style fixes * fix lint errors while merge with develop --- .eslintrc.js | 225 +- package.json | 13 +- scripts/cli-tests.js | 523 ++--- scripts/coverage.js | 14 +- scripts/init.js | 14 +- scripts/postinstall.js | 173 +- scripts/postmantest.js | 67 +- scripts/preuninstall.js | 22 +- scripts/scripts-api.js | 62 +- scripts/start-dev.js | 14 +- scripts/start.js | 14 +- scripts/stop.js | 14 +- scripts/test.js | 14 +- scripts/util.js | 66 +- src/cli/base-cli-handler.js | 240 +- src/cli/catalog.js | 238 +- src/cli/cli-data-types.js | 10 +- src/cli/config.js | 228 +- src/cli/connector.js | 111 +- src/cli/controller.js | 99 +- src/cli/diagnostics.js | 154 +- src/cli/flow.js | 170 +- src/cli/index.js | 82 +- src/cli/iofog.js | 265 ++- src/cli/microservice.js | 475 ++-- src/cli/registry.js | 115 +- src/cli/start.js | 41 +- src/cli/tunnel.js | 103 +- src/cli/user.js | 163 +- src/config/constants.js | 2 +- src/config/index.js | 6 +- src/controllers/agent-controller.js | 134 +- src/controllers/catalog-controller.js | 38 +- src/controllers/controller.js | 24 +- src/controllers/diagnostic-controller.js | 38 +- src/controllers/flow-controller.js | 38 +- src/controllers/iofog-controller.js | 50 +- src/controllers/microservices-controller.js | 116 +- src/controllers/registry-controller.js | 40 +- src/controllers/tunnel-controller.js | 40 +- src/controllers/user-controller.js | 102 +- src/daemon.js | 44 +- src/decorators/authorization-decorator.js | 62 +- src/decorators/cli-decorator.js | 30 +- src/decorators/response-decorator.js | 44 +- src/decorators/tracking-decorator.js | 22 +- src/decorators/transaction-decorator.js | 73 +- src/enums/fog-state.js | 6 +- src/enums/microservice-state.js | 4 +- src/enums/tracking-event-type.js | 4 +- src/helpers/app-helper.js | 153 +- src/helpers/constants.js | 2 +- src/helpers/error-messages.js | 52 +- src/helpers/errors.js | 74 +- src/jobs/base/base-job-handler.js | 8 +- src/jobs/fog-status-job.js | 62 +- src/jobs/send-tracking-job.js | 26 +- src/jobs/time-tracking-job.js | 39 +- src/logger/index.js | 90 +- src/main.js | 9 +- src/routes/agent.js | 479 ++-- src/routes/catalog.js | 166 +- src/routes/controller.js | 67 +- src/routes/diagnostics.js | 182 +- src/routes/flow.js | 132 +- src/routes/iofog.js | 264 +-- src/routes/microservices.js | 368 ++-- src/routes/registries.js | 113 +- src/routes/tunnel.js | 88 +- src/routes/user.js | 247 ++- src/schemas/agent.js | 270 +-- src/schemas/catalog.js | 130 +- src/schemas/config.js | 38 +- src/schemas/connector.js | 66 +- src/schemas/diagnostics.js | 48 +- src/schemas/flow.js | 38 +- src/schemas/index.js | 108 +- src/schemas/iofog.js | 226 +- src/schemas/microservice.js | 166 +- src/schemas/registry.js | 78 +- src/schemas/tunnel.js | 26 +- src/schemas/user.js | 170 +- .../managers/access-token-manager.js | 22 +- src/sequelize/managers/base-manager.js | 86 +- .../managers/catalog-item-image-manager.js | 12 +- .../catalog-item-input-type-manager.js | 12 +- .../managers/catalog-item-manager.js | 35 +- .../catalog-item-output-type-manager.js | 12 +- .../managers/change-tracking-manager.js | 4 +- src/sequelize/managers/connector-manager.js | 4 +- .../managers/connector-port-manager.js | 14 +- .../managers/email-activation-code-manager.js | 44 +- src/sequelize/managers/flow-manager.js | 29 +- src/sequelize/managers/hw-info-manager.js | 12 +- .../managers/iofog-access-token-manager.js | 16 +- src/sequelize/managers/iofog-manager.js | 40 +- .../managers/iofog-provision-key-manager.js | 10 +- src/sequelize/managers/iofog-type-manager.js | 10 +- .../managers/iofog-version-command-manager.js | 10 +- .../managers/microservice-manager.js | 302 +-- .../managers/microservice-port-manager.js | 10 +- .../microservice-public-mode-manager.js | 18 +- .../managers/microservice-status-manager.js | 10 +- src/sequelize/managers/registry-manager.js | 12 +- src/sequelize/managers/routing-manager.js | 22 +- .../managers/strace-diagnostics-manager.js | 13 +- src/sequelize/managers/strace-manager.js | 41 +- .../managers/tracking-event-manager.js | 18 +- src/sequelize/managers/tunnel-manager.js | 12 +- src/sequelize/managers/usb-info-manager.js | 12 +- src/sequelize/managers/user-manager.js | 58 +- .../managers/volume-mapping-manager.js | 18 +- .../migrations/20180930155645-create-user.js | 31 +- .../migrations/20180930164635-create-flow.js | 32 +- .../20180930173823-create-registry.js | 34 +- .../20180930184436-create-catalog-item.js | 40 +- .../20180930184703-create-fog-type.js | 32 +- ...0180930184921-create-catalog-item-image.js | 24 +- ...30194506-create-catalog-item-input-type.js | 22 +- ...0195746-create-catalog-item-output-type.js | 22 +- ...0930204039-create-email-activation-code.js | 22 +- .../migrations/20180930225403-create-fog.js | 130 +- .../20180930225846-create-change-tracking.js | 40 +- .../20180930230219-create-fog-access-token.js | 26 +- ...20180930230626-create-fog-provision-key.js | 21 +- ...180930231241-create-fog-version-command.js | 21 +- .../20180930231536-create-hw-info.js | 26 +- .../20180930232242-create-usb-info.js | 26 +- .../20180930232508-create-tunnel.js | 32 +- .../20181001062956-create-microservice.js | 58 +- ...20181001070828-create-microservice-port.js | 32 +- ...181001071315-create-microservice-status.js | 30 +- .../20181001071628-create-connector.js | 30 +- .../20181001071858-create-connector-port.js | 40 +- ...0181001073429-create-strace-diagnostics.js | 18 +- .../20181003102815-create-volume-mapping.js | 20 +- .../20181003104606-create-access-token.js | 20 +- .../20181022110529-create-routing.js | 44 +- ...2114905-create-microservice-public-mode.js | 34 +- ...4923-drop-need-update-col-microservices.js | 14 +- ...croservice-status-add-missing-time-cols.js | 18 +- ...81102163657-microservice-add-col-remove.js | 10 +- ...king-container-to-microservice-renaming.js | 18 +- ...microservice-rename-updatedBy-to-userId.js | 6 +- ...service-port-rename-updatedBy-to-userId.js | 6 +- .../20181109132723-flow-remove-updatedBy.js | 10 +- .../20181113094807-add-missing-constraints.js | 75 +- .../20190117110458-create-tracking-event.js | 22 +- src/sequelize/models/accesstoken.js | 28 +- src/sequelize/models/catalogitem.js | 65 +- src/sequelize/models/catalogitemimage.js | 33 +- src/sequelize/models/catalogiteminputtype.js | 29 +- src/sequelize/models/catalogitemoutputtype.js | 29 +- src/sequelize/models/changetracking.js | 47 +- src/sequelize/models/connector.js | 30 +- src/sequelize/models/connectorport.js | 43 +- src/sequelize/models/emailactivationcode.js | 29 +- src/sequelize/models/flow.js | 35 +- src/sequelize/models/fog.js | 144 +- src/sequelize/models/fogaccesstoken.js | 35 +- src/sequelize/models/fogprovisionkey.js | 30 +- src/sequelize/models/fogtype.js | 42 +- src/sequelize/models/fogversioncommand.js | 28 +- src/sequelize/models/hwinfo.js | 29 +- src/sequelize/models/index.js | 64 +- src/sequelize/models/microservice.js | 83 +- src/sequelize/models/microserviceport.js | 37 +- .../models/microservicepublicmode.js | 46 +- src/sequelize/models/microservicestatus.js | 36 +- src/sequelize/models/registry.js | 39 +- src/sequelize/models/routing.js | 61 +- src/sequelize/models/stracediagnostics.js | 27 +- src/sequelize/models/trackingevent.js | 26 +- src/sequelize/models/tunnel.js | 39 +- src/sequelize/models/usbinfo.js | 29 +- src/sequelize/models/user.js | 59 +- src/sequelize/models/volumemapping.js | 30 +- .../seeders/20180928110125-insert-registry.js | 16 +- .../20180928111532-insert-catalog-item.js | 36 +- .../20180928112152-insert-iofog-type.js | 34 +- ...0180928121334-insert-catalog-item-image.js | 60 +- ...90130112616-insert-logging-catalog-item.js | 38 +- ...1441-insert-json-generator-catalog-item.js | 37 +- .../20190218103641-adding-default-configs.js | 98 +- src/server.js | 126 +- src/services/access-token-service.js | 20 +- src/services/agent-service.js | 459 ++-- src/services/catalog-service.js | 307 ++- src/services/change-tracking-service.js | 46 +- src/services/connector-port-service.js | 131 +- src/services/connector-service.js | 76 +- src/services/controller-service.js | 51 +- src/services/diagnostic-service.js | 244 +- src/services/email-activation-code-service.js | 48 +- src/services/flow-service.js | 130 +- src/services/iofog-access-token-service.js | 30 +- src/services/iofog-service.js | 228 +- src/services/microservices-service.js | 770 ++++--- src/services/registry-service.js | 120 +- src/services/tunnel-service.js | 84 +- src/services/user-service.js | 334 +-- src/tracking/index.js | 141 +- src/views/email-activation-temp.js | 234 +- src/views/email-temp.js | 118 +- src/views/reset-password-temp.js | 216 +- test/src/controllers/agent-controller.test.js | 672 +++--- .../controllers/catalog-controller.test.js | 268 ++- .../controllers/controller-controller.test.js | 94 +- .../diagnostics-controller.test.js | 201 +- test/src/controllers/flow-controller.test.js | 189 +- test/src/controllers/iofog-controller.test.js | 450 ++-- .../microservices-controller.test.js | 532 +++-- .../controllers/registry-controller.test.js | 171 +- .../src/controllers/tunnel-controller.test.js | 10 +- test/src/controllers/user-controller.test.js | 411 ++-- test/src/helpers/app-helpers.test.js | 163 +- .../src/services/access-token-service.test.js | 73 +- test/src/services/agent-service.test.js | 1351 ++++++------ test/src/services/catalog-service.test.js | 887 ++++---- .../services/change-tracking-service.test.js | 133 +- .../services/connector-port-service.test.js | 2 +- test/src/services/connector-service.test.js | 377 ++-- test/src/services/controller-service.test.js | 84 +- test/src/services/diagnostic-service.test.js | 451 ++-- .../email-activation-code-service.test.js | 158 +- test/src/services/flow-service.test.js | 477 ++-- test/src/services/iofog-service.test.js | 1269 ++++++----- .../services/microservices-service.test.js | 1957 ++++++++--------- test/src/services/registry-service.test.js | 427 ++-- test/src/services/tunnel-service.test.js | 34 +- test/src/services/user-service.test.js | 780 ++++--- test/support/setup.js | 2 +- 232 files changed, 13729 insertions(+), 14013 deletions(-) diff --git a/.eslintrc.js b/.eslintrc.js index c1364da48..5dbe0044b 100644 --- a/.eslintrc.js +++ b/.eslintrc.js @@ -6,220 +6,23 @@ module.exports = { 'node': true, }, - 'ecmaFeatures': { - 'modules': true + 'extends': 'google', + 'rules': { + 'require-jsdoc': [OFF, { + 'require': { + 'FunctionDeclaration': true, + 'MethodDefinition': true, + 'ClassDeclaration': false + } + }], + 'max-len': [WARN, 132], + 'no-invalid-this': OFF, + 'no-multi-str': OFF, + 'semi': [ERROR, 'never'], }, 'parserOptions': { 'sourceType': 'module', - 'ecmaVersion': 6, - 'ecmaFeatures': { - 'jsx': true, - 'experimentalObjectRestSpread': true - }, - - 'extends': 'eslint:recommended', - - 'rules': { - // Possible Errors (overrides from recommended set) - 'no-extra-parens': ERROR, - 'no-unexpected-multiline': ERROR, - // All JSDoc comments must be valid - 'valid-jsdoc': [ERROR, { - 'requireReturn': false, - 'requireReturnDescription': false, - 'requireParamDescription': true, - 'prefer': { - 'return': 'returns' - } - }], - - // Best Practices - - // Allowed a getter without setter, but all setters require getters - 'accessor-pairs': [ERROR, { - 'getWithoutSet': false, - 'setWithoutGet': true - }], - 'block-scoped-var': WARN, - 'consistent-return': ERROR, - 'curly': ERROR, - 'default-case': WARN, - // the dot goes with the property when doing multiline - 'dot-location': [WARN, 'property'], - 'dot-notation': WARN, - 'eqeqeq': [ERROR, 'smart'], - 'guard-for-in': WARN, - 'no-alert': ERROR, - 'no-caller': ERROR, - 'no-case-declarations': WARN, - 'no-div-regex': WARN, - 'no-else-return': WARN, - 'no-labels': WARN, - 'no-empty-pattern': WARN, - 'no-eq-null': WARN, - 'no-eval': ERROR, - 'no-extend-native': ERROR, - 'no-extra-bind': WARN, - 'no-floating-decimal': WARN, - 'no-implicit-coercion': [WARN, { - 'boolean': true, - 'number': true, - 'string': true - }], - 'no-implied-eval': ERROR, - 'no-invalid-this': ERROR, - 'no-iterator': ERROR, - 'no-lone-blocks': WARN, - 'no-loop-func': ERROR, - 'no-magic-numbers': WARN, - 'no-multi-spaces': ERROR, - 'no-multi-str': WARN, - 'no-native-reassign': ERROR, - 'no-new-func': ERROR, - 'no-new-wrappers': ERROR, - 'no-new': ERROR, - 'no-octal-escape': ERROR, - 'no-param-reassign': ERROR, - 'no-process-env': OFF, - 'no-proto': ERROR, - 'no-redeclare': ERROR, - 'no-return-assign': ERROR, - 'no-script-url': ERROR, - 'no-self-compare': ERROR, - 'no-throw-literal': ERROR, - 'no-unused-expressions': ERROR, - 'no-useless-call': ERROR, - 'no-useless-concat': ERROR, - 'no-void': WARN, - // Produce warnings when something is commented as TODO or FIXME - 'no-warning-comments': [WARN, { - 'terms': ['TODO', 'FIXME'], - 'location': 'start' - }], - 'no-with': WARN, - 'radix': WARN, - 'vars-on-top': ERROR, - // Enforces the style of wrapped functions - 'wrap-iife': [ERROR, 'outside'], - 'yoda': ERROR, - - // Strict Mode - for ES6, never use strict. - 'strict': [WARN, 'never'], - - // Variables - 'init-declarations': [ERROR, 'always'], - 'no-catch-shadow': WARN, - 'no-delete-var': ERROR, - 'no-label-var': ERROR, - 'no-shadow-restricted-names': ERROR, - 'no-shadow': WARN, - // We require all vars to be initialized (see init-declarations) - // If we NEED a var to be initialized to undefined, it needs to be explicit - 'no-undef-init': OFF, - 'no-undef': ERROR, - 'no-undefined': OFF, - 'no-unused-vars': WARN, - // Disallow hoisting - let & const don't allow hoisting anyhow - 'no-use-before-define': ERROR, - - // Node.js and CommonJS - 'callback-return': [WARN, ['callback', 'next']], - 'global-require': OFF, - 'handle-callback-err': WARN, - 'no-mixed-requires': WARN, - 'no-new-require': ERROR, - // Use path.concat instead - 'no-path-concat': ERROR, - 'no-process-exit': ERROR, - 'no-restricted-modules': OFF, - 'no-sync': WARN, - - // ECMAScript 6 support - 'arrow-body-style': [ERROR, 'always'], - 'arrow-parens': [ERROR, 'always'], - 'arrow-spacing': [ERROR, {'before': true, 'after': true}], - 'constructor-super': ERROR, - 'generator-star-spacing': [ERROR, 'before'], - 'no-confusing-arrow': ERROR, - 'no-class-assign': ERROR, - 'no-const-assign': ERROR, - 'no-dupe-class-members': ERROR, - 'no-this-before-super': ERROR, - 'no-var': WARN, - 'object-shorthand': [WARN, 'never'], - 'prefer-arrow-callback': WARN, - 'prefer-spread': WARN, - 'prefer-template': WARN, - 'require-yield': ERROR, - - // Stylistic - everything here is a warning because of style. - 'array-bracket-spacing': [WARN, 'always'], - 'block-spacing': [WARN, 'always'], - 'brace-style': [WARN, '1tbs', {'allowSingleLine': false}], - 'camelcase': WARN, - 'comma-spacing': [WARN, {'before': false, 'after': true}], - 'comma-style': [WARN, 'last'], - 'computed-property-spacing': [WARN, 'never'], - 'consistent-this': [WARN, 'self'], - 'eol-last': WARN, - 'func-names': WARN, - 'func-style': [WARN, 'declaration'], - 'id-length': [WARN, {'min': 1, 'max': 32}], - 'indent': [WARN, 2], - 'jsx-quotes': [WARN, 'prefer-double'], - 'linebreak-style': [WARN, 'unix'], - 'lines-around-comment': [WARN, {'beforeBlockComment': true}], - 'max-depth': [WARN, 8], - 'max-len': [WARN, 132], - 'max-nested-callbacks': [WARN, 8], - 'max-params': [WARN, 8], - 'new-cap': WARN, - 'new-parens': WARN, - 'no-array-constructor': WARN, - 'no-bitwise': OFF, - 'no-continue': OFF, - 'no-inline-comments': OFF, - 'no-lonely-if': WARN, - 'no-mixed-spaces-and-tabs': ERROR, - 'no-multiple-empty-lines': WARN, - 'no-negated-condition': OFF, - 'no-nested-ternary': WARN, - 'no-new-object': WARN, - 'no-plusplus': OFF, - 'no-spaced-func': WARN, - 'no-ternary': OFF, - 'no-trailing-spaces': WARN, - 'no-underscore-dangle': WARN, - 'no-unneeded-ternary': WARN, - 'object-curly-spacing': [WARN, 'always'], - 'one-var': OFF, - 'operator-assignment': [WARN, 'never'], - 'operator-linebreak': [WARN, 'after'], - 'padded-blocks': [WARN, 'never'], - 'quote-props': [WARN, 'consistent-as-needed'], - 'quotes': [WARN, 'single'], - 'require-jsdoc': [OFF, { - 'require': { - 'FunctionDeclaration': true, - 'MethodDefinition': true, - 'ClassDeclaration': false - } - }], - 'semi-spacing': [WARN, {'before': false, 'after': true}], - 'semi': [ERROR, 'never'], - 'sort-vars': OFF, - 'keyword-spacing': [WARN, { - 'before': true, - 'after': true, - }], - 'space-before-blocks': [WARN, 'always'], - 'space-before-function-paren': [WARN, 'never'], - 'space-in-parens': [WARN, 'never'], - 'space-infix-ops': [WARN, {'int32Hint': true}], - 'space-unary-ops': ERROR, - 'spaced-comment': [WARN, 'always'], - 'wrap-regex': WARN - } + 'ecmaVersion': 2017, } } \ No newline at end of file diff --git a/package.json b/package.json index a9a42c411..29476f21a 100644 --- a/package.json +++ b/package.json @@ -34,17 +34,25 @@ "url": "https://github.com/ioFog/Controller" }, "scripts": { + "prestart": "npm run lint", "start": "node scripts/scripts-api.js start", + "prestart-dev": "npm run lint", "start-dev": "node scripts/scripts-api.js start-dev", + "prebuild": "npm run lint", "build": "node scripts/scripts-api.js init", "preuninstall": "node scripts/scripts-api.js preuninstall", "postinstall": "node scripts/scripts-api.js postinstall", "lint": "./node_modules/.bin/eslint \"**/*.js\"", "automatic-release": "automatic-release", + "pretest": "npm run lint", "test": "node scripts/scripts-api.js test", + "prepostman_test": "npm run lint", "postman_test": "node scripts/scripts-api.js postmantest", + "precli-tests": "npm run lint", "cli-tests": "node scripts/scripts-api.js cli-tests", - "coverage": "node scripts/scripts-api.js coverage" + "precoverage": "npm run lint", + "coverage": "node scripts/scripts-api.js coverage", + "prepare": "npm run lint" }, "preferGlobal": true, "bin": { @@ -93,7 +101,8 @@ "chai": "4.2.0", "chai-as-promised": "7.1.1", "chai-http": "4.2.1", - "eslint": "5.12.1", + "eslint": "^5.14.1", + "eslint-config-google": "^0.12.0", "mocha": "5.2.0", "newman": "4.3.1", "nyc": "13.3.0", diff --git a/scripts/cli-tests.js b/scripts/cli-tests.js index e2741afc7..812e7571e 100644 --- a/scripts/cli-tests.js +++ b/scripts/cli-tests.js @@ -11,426 +11,427 @@ * */ -const execSync = require('child_process').execSync; -const {init} = require('./init'); -const {restoreDBs, backupDBs} = require('./util'); +const execSync = require('child_process').execSync +const {init} = require('./init') +const {restoreDBs, backupDBs} = require('./util') const options = { env: { 'NODE_ENV': 'production', - "PATH": process.env.PATH - } -}; + 'PATH': process.env.PATH, + }, +} -let testsCounter = 0; -let testsFailed = 0; +/* eslint-disable no-unused-vars */ +let testsCounter = 0 +let testsFailed = 0 -const controllerStatusFields = ['status', 'timestamp']; -const controllerEmailActivationFields = ['isEmailActivationEnabled']; -const controllerFogTypesFields = ['fogTypes']; +const controllerStatusFields = ['status', 'timestamp'] +const controllerEmailActivationFields = ['isEmailActivationEnabled'] +const controllerFogTypesFields = ['fogTypes'] -const userCreateFields = ['id']; -const userAccessTokenFields = ['accessToken']; +const userCreateFields = ['id'] +const userAccessTokenFields = ['accessToken'] -const ioFogCreateFields = ['uuid']; -const ioFogListFields = ['fogs']; -const ioFogProvisioningFields = ['key', 'expirationTime']; +const ioFogCreateFields = ['uuid'] +const ioFogListFields = ['fogs'] +const ioFogProvisioningFields = ['key', 'expirationTime'] -const catalogCreateFields = ['id']; -const catalogListFields = ['catalogItems']; +const catalogCreateFields = ['id'] +const catalogListFields = ['catalogItems'] -const flowCreateFields = ['id']; -const flowListFields = ['flows']; +const flowCreateFields = ['id'] +const flowListFields = ['flows'] -const microserviceCreateFields = ['uuid']; -const microserviceListFields = ['microservices']; +const microserviceCreateFields = ['uuid'] +const microserviceListFields = ['microservices'] -const volumeMappingCreateFields = ['id']; +const volumeMappingCreateFields = ['id'] -const registryCreateFields = ['id']; -const registryListFields = ['registries']; +const registryCreateFields = ['id'] +const registryListFields = ['registries'] -const tunnelListFields = ['tunnels']; +const tunnelListFields = ['tunnels'] function testControllerSection() { - console.log("\n=============================\nStarting controller section.."); + console.log('\n=============================\nStarting controller section..') - responseHasFields(testCommand('controller status'), controllerStatusFields); - responseHasFields(testCommand('controller email-activation'), controllerEmailActivationFields); - responseHasFields(testCommand('controller fog-types'), controllerFogTypesFields); - hasSomeResponse(testCommand('controller version')); + responseHasFields(testCommand('controller status'), controllerStatusFields) + responseHasFields(testCommand('controller email-activation'), controllerEmailActivationFields) + responseHasFields(testCommand('controller fog-types'), controllerFogTypesFields) + hasSomeResponse(testCommand('controller version')) } function testUserSection() { - console.log("\n=============================\nStarting user section.."); + console.log('\n=============================\nStarting user section..') - responseHasFields(testCommand("user add -f John -l Doe -e user@domain.com -p '#Bugs4Fun'"), userCreateFields); + responseHasFields(testCommand('user add -f John -l Doe -e user@domain.com -p \'#Bugs4Fun\''), userCreateFields) responseEquals(testCommand('user update -f John2 -l Doe2 -e user@domain.com -p \'#Bugs4Fun34\''), - 'User updated successfully.'); - responseIsArray(testCommand('user list')); - responseHasFields(testCommand('user generate-token -e user@domain.com'), userAccessTokenFields); - responseEquals(testCommand('user suspend -e user@domain.com'), 'User suspended successfully.'); - responseEquals(testCommand('user activate -e user@domain.com'), 'User activated successfully.'); - responseEquals(testCommand('user remove -e user@domain.com'), 'User removed successfully.'); + 'User updated successfully.') + responseIsArray(testCommand('user list')) + responseHasFields(testCommand('user generate-token -e user@domain.com'), userAccessTokenFields) + responseEquals(testCommand('user suspend -e user@domain.com'), 'User suspended successfully.') + responseEquals(testCommand('user activate -e user@domain.com'), 'User activated successfully.') + responseEquals(testCommand('user remove -e user@domain.com'), 'User removed successfully.') } function testConfigSection() { - console.log("\n=============================\nStarting config section.."); + console.log('\n=============================\nStarting config section..') // TODO backup config before this command // hasSomeResponse(testCommand("config add -p 1234 -c testPath -k testSslPath -i testIntermediateCertPath" + // " -h testHomeUrl -a testEmailAddress -w testEmailPassword -s testEmailService -d testLogDir -z 555")); - hasSomeResponse(testCommand('config list')); - responseEquals(testCommand('config dev-mode -o'), 'Dev mode state updated successfully.'); - responseEquals(testCommand('config email-activation -f'), 'Email activation state updated successfully.'); + hasSomeResponse(testCommand('config list')) + responseEquals(testCommand('config dev-mode -o'), 'Dev mode state updated successfully.') + responseEquals(testCommand('config email-activation -f'), 'Email activation state updated successfully.') } function testConnectorSection() { - console.log("\n=============================\nStarting connector section.."); + console.log('\n=============================\nStarting connector section..') - responseContains(testCommand("connector add -i 127.0.0.1 -n Connector1 -d iofog.test.org -c testCertPath" + - " -s -H"), 'Connector has been created successfully.'); + responseContains(testCommand('connector add -i 127.0.0.1 -n Connector1 -d iofog.test.org -c testCertPath' + + ' -s -H'), 'Connector has been created successfully.') responseEquals(testCommand('connector update -i 127.0.0.1 -n Connector2 -d iofog.test.org -c testCertPath' + - ' -s -H'), 'Connector has been updated successfully.'); - responseEquals(testCommand('connector remove -i 127.0.0.1'), 'Connector has been removed successfully.'); - responseIsArray(testCommand('connector list')); + ' -s -H'), 'Connector has been updated successfully.') + responseEquals(testCommand('connector remove -i 127.0.0.1'), 'Connector has been removed successfully.') + responseIsArray(testCommand('connector list')) } function testTunnelSection() { - console.log("\n=============================\nStarting tunnel section.."); + console.log('\n=============================\nStarting tunnel section..') responseContains(testCommand('tunnel update -i testIoFogUuid -u testUsername -p testPassword -s 127.0.0.1 ' + - '-k testRSAKeyPath -o 2048 -a open'), 'ENOENT: no such file or directory'); - responseHasFields(testCommand('tunnel list'), tunnelListFields); + '-k testRSAKeyPath -o 2048 -a open'), 'ENOENT: no such file or directory') + responseHasFields(testCommand('tunnel list'), tunnelListFields) } function testIoFogSection() { - console.log("\n=============================\nStarting iofog section.."); + console.log('\n=============================\nStarting iofog section..') - const userCreateResponse = responseHasFields(executeCommand("user add -f John -l Doe -e fogUser@domain.com" + - " -p '#Bugs4Fun'"), userCreateFields); - const userId = userCreateResponse.id; + const userCreateResponse = responseHasFields(executeCommand('user add -f John -l Doe -e fogUser@domain.com' + + ' -p \'#Bugs4Fun\''), userCreateFields) + const userId = userCreateResponse.id try { - const ioFogCreateResponse = responseHasFields(testCommand("iofog add -n ioFog1 -l testLocation -t 55 -g 65" + - " -d testDescription -D testDockerUrl -M 55 -T testDiskDirectoryString -m 65 -c 24 -G 1 -Y testLogDirectory " + - "-C 15 -s 25 -F 27 -Q 26 -B -W -A -y 1 -u " + userId), ioFogCreateFields); - const ioFogUuid = ioFogCreateResponse.uuid; - responseEquals(testCommand("iofog update -i " + ioFogUuid + " -n ioFog1 -l testLocation -t 55 -g 65 " + - "-d testDescription -D testDockerUrl -M 55 -T testDiskDirectoryString -m 65 -c 24 -G 1 -Y testLogDirectory " + - "-C 15 -s 25 -F 27 -Q 26 -B -W -A -y 1"), 'ioFog node has been updated successfully.'); - responseHasFields(testCommand('iofog list'), ioFogListFields); - responseHasFields(testCommand('iofog info -i ' + ioFogUuid), ioFogCreateFields); - responseHasFields(testCommand('iofog provisioning-key -i ' + ioFogUuid), ioFogProvisioningFields); - responseEquals(testCommand('iofog reboot -i ' + ioFogUuid), 'ioFog reboot command has been set successfully'); + const ioFogCreateResponse = responseHasFields(testCommand('iofog add -n ioFog1 -l testLocation -t 55 -g 65' + + ' -d testDescription -D testDockerUrl -M 55 -T testDiskDirectoryString -m 65 -c 24 -G 1 -Y testLogDirectory ' + + '-C 15 -s 25 -F 27 -Q 26 -B -W -A -y 1 -u ' + userId), ioFogCreateFields) + const ioFogUuid = ioFogCreateResponse.uuid + responseEquals(testCommand('iofog update -i ' + ioFogUuid + ' -n ioFog1 -l testLocation -t 55 -g 65 ' + + '-d testDescription -D testDockerUrl -M 55 -T testDiskDirectoryString -m 65 -c 24 -G 1 -Y testLogDirectory ' + + '-C 15 -s 25 -F 27 -Q 26 -B -W -A -y 1'), 'ioFog node has been updated successfully.') + responseHasFields(testCommand('iofog list'), ioFogListFields) + responseHasFields(testCommand('iofog info -i ' + ioFogUuid), ioFogCreateFields) + responseHasFields(testCommand('iofog provisioning-key -i ' + ioFogUuid), ioFogProvisioningFields) + responseEquals(testCommand('iofog reboot -i ' + ioFogUuid), 'ioFog reboot command has been set successfully') responseEquals(testCommand('iofog version -i ' + ioFogUuid + ' -v upgrade'), - 'ioFog version command has been set successfully'); - hasSomeResponse(testCommand('iofog hal-hw -i ' + ioFogUuid)); - hasSomeResponse(testCommand('iofog hal-usb -i ' + ioFogUuid)); - responseEquals(testCommand('iofog remove -i ' + ioFogUuid), 'ioFog node has been removed successfully'); - executeCommand('user remove -e fogUser@domain.com'); + 'ioFog version command has been set successfully') + hasSomeResponse(testCommand('iofog hal-hw -i ' + ioFogUuid)) + hasSomeResponse(testCommand('iofog hal-usb -i ' + ioFogUuid)) + responseEquals(testCommand('iofog remove -i ' + ioFogUuid), 'ioFog node has been removed successfully') + executeCommand('user remove -e fogUser@domain.com') } catch (exception) { - executeCommand('user remove -e fogUser@domain.com'); + executeCommand('user remove -e fogUser@domain.com') } } function testCatalogSection() { - console.log("\n=============================\nStarting catalog section.."); + console.log('\n=============================\nStarting catalog section..') - const userCreateResponse = responseHasFields(executeCommand("user add -f John -l Doe -e catalogUser@domain.com" + - " -p '#Bugs4Fun'"), userCreateFields); - const userId = userCreateResponse.id; - const registryCreateResponse = responseHasFields(executeCommand("registry add -U testRegistryUri -b -l testUserName" + - " -p testPassword -e testEmail@gmail.com -u " + userId), registryCreateFields); - const registryId = registryCreateResponse.id; + const userCreateResponse = responseHasFields(executeCommand('user add -f John -l Doe -e catalogUser@domain.com' + + ' -p \'#Bugs4Fun\''), userCreateFields) + const userId = userCreateResponse.id + const registryCreateResponse = responseHasFields(executeCommand('registry add -U testRegistryUri -b -l testUserName' + + ' -p testPassword -e testEmail@gmail.com -u ' + userId), registryCreateFields) + const registryId = registryCreateResponse.id try { - const catalogCreateResponse = responseHasFields(testCommand("catalog add -n testCatalogItem1 -d testDescription" + - " -c testCategory -x testIntelImage -a testArmImage -p testPublisher -s 15 -r 15 -t testPicture -g " - + registryId + " -I testInputType -F testInputFormat -O testOutputType -T testOutputFormat " + - "-X '{}' -u " + userId), catalogCreateFields); - const catalogId = catalogCreateResponse.id; - responseEquals(testCommand("catalog update -i " + catalogId + " -n testCatalogItem2 -d testDescription" + - " -c testCategory -x testIntelImage -a testArmImage -p testPublisher -s 15 -r 15 -t testPicture -g " - + registryId + " -I testInputType -F testInputFormat -O testOutputType -T testOutputFormat -X '{}'"), - 'Catalog item has been updated successfully.'); - responseHasFields(testCommand('catalog list'), catalogListFields); - responseHasFields(testCommand('catalog info -i ' + catalogId), catalogCreateFields); - responseEquals(testCommand('catalog remove -i ' + catalogId), 'Catalog item has been removed successfully'); - executeCommand('registry remove -i ' + registryId); - executeCommand('user remove -e catalogUser@domain.com'); + const catalogCreateResponse = responseHasFields(testCommand('catalog add -n testCatalogItem1 -d testDescription' + + ' -c testCategory -x testIntelImage -a testArmImage -p testPublisher -s 15 -r 15 -t testPicture -g ' + + registryId + ' -I testInputType -F testInputFormat -O testOutputType -T testOutputFormat ' + + '-X \'{}\' -u ' + userId), catalogCreateFields) + const catalogId = catalogCreateResponse.id + responseEquals(testCommand('catalog update -i ' + catalogId + ' -n testCatalogItem2 -d testDescription' + + ' -c testCategory -x testIntelImage -a testArmImage -p testPublisher -s 15 -r 15 -t testPicture -g ' + + registryId + ' -I testInputType -F testInputFormat -O testOutputType -T testOutputFormat -X \'{}\''), + 'Catalog item has been updated successfully.') + responseHasFields(testCommand('catalog list'), catalogListFields) + responseHasFields(testCommand('catalog info -i ' + catalogId), catalogCreateFields) + responseEquals(testCommand('catalog remove -i ' + catalogId), 'Catalog item has been removed successfully') + executeCommand('registry remove -i ' + registryId) + executeCommand('user remove -e catalogUser@domain.com') } catch (exception) { - executeCommand('registry remove -i ' + registryId); - executeCommand('user remove -e catalogUser@domain.com'); + executeCommand('registry remove -i ' + registryId) + executeCommand('user remove -e catalogUser@domain.com') } } function testFlowSection() { - console.log("\n=============================\nStarting flow section.."); + console.log('\n=============================\nStarting flow section..') - const userCreateResponse = responseHasFields(executeCommand("user add -f John -l Doe -e flowUser@domain.com" + - " -p '#Bugs4Fun'"), userCreateFields); - const userId = userCreateResponse.id; + const userCreateResponse = responseHasFields(executeCommand('user add -f John -l Doe -e flowUser@domain.com' + + ' -p \'#Bugs4Fun\''), userCreateFields) + const userId = userCreateResponse.id try { - const flowCreateResponse = responseHasFields(testCommand("flow add -n testFlow1 -d testDescription" + - " -a -u " + userId), flowCreateFields); - const flowId = flowCreateResponse.id; - responseEquals(testCommand("flow update -i " + flowId + " -n testFlow1 -d testDescription -a"), - 'Flow updated successfully.'); - responseHasFields(testCommand('flow list'), flowListFields); - responseHasFields(testCommand('flow info -i ' + flowId), flowCreateFields); - responseEquals(testCommand('flow remove -i ' + flowId), 'Flow removed successfully.'); - executeCommand('user remove -e flowUser@domain.com'); + const flowCreateResponse = responseHasFields(testCommand('flow add -n testFlow1 -d testDescription' + + ' -a -u ' + userId), flowCreateFields) + const flowId = flowCreateResponse.id + responseEquals(testCommand('flow update -i ' + flowId + ' -n testFlow1 -d testDescription -a'), + 'Flow updated successfully.') + responseHasFields(testCommand('flow list'), flowListFields) + responseHasFields(testCommand('flow info -i ' + flowId), flowCreateFields) + responseEquals(testCommand('flow remove -i ' + flowId), 'Flow removed successfully.') + executeCommand('user remove -e flowUser@domain.com') } catch (exception) { - executeCommand('user remove -e flowUser@domain.com'); + executeCommand('user remove -e flowUser@domain.com') } } function testMicroserviceSection() { - console.log("\n=============================\nStarting microservice section.."); + console.log('\n=============================\nStarting microservice section..') - const userCreateResponse = responseHasFields(executeCommand("user add -f John -l Doe -e microserviceUser@domain.com" + - " -p '#Bugs4Fun'"), userCreateFields); - const userId = userCreateResponse.id; + const userCreateResponse = responseHasFields(executeCommand('user add -f John -l Doe -e microserviceUser@domain.com' + + ' -p \'#Bugs4Fun\''), userCreateFields) + const userId = userCreateResponse.id - const registryCreateResponse = responseHasFields(executeCommand("registry add -U testRegistryUri -b -l testUserName" + - " -p testPassword -e testEmail@gmail.com -u " + userId), registryCreateFields); - const registryId = registryCreateResponse.id; + const registryCreateResponse = responseHasFields(executeCommand('registry add -U testRegistryUri -b -l testUserName' + + ' -p testPassword -e testEmail@gmail.com -u ' + userId), registryCreateFields) + const registryId = registryCreateResponse.id - const catalogCreateResponse = responseHasFields(executeCommand("catalog add -n testCatalogItem1 -d testDescription" + - " -c testCategory -x testIntelImage -a testArmImage -p testPublisher -s 15 -r 15 -t testPicture -g " - + registryId + " -I testInputType -F testInputFormat -O testOutputType -T testOutputFormat " + - "-X '{}' -u " + userId), catalogCreateFields); - const catalogId = catalogCreateResponse.id; + const catalogCreateResponse = responseHasFields(executeCommand('catalog add -n testCatalogItem1 -d testDescription' + + ' -c testCategory -x testIntelImage -a testArmImage -p testPublisher -s 15 -r 15 -t testPicture -g ' + + registryId + ' -I testInputType -F testInputFormat -O testOutputType -T testOutputFormat ' + + '-X \'{}\' -u ' + userId), catalogCreateFields) + const catalogId = catalogCreateResponse.id - const flowCreateResponse = responseHasFields(executeCommand("flow add -n testFlow1 -d testDescription" + - " -a -u " + userId), flowCreateFields); - const flowId = flowCreateResponse.id; + const flowCreateResponse = responseHasFields(executeCommand('flow add -n testFlow1 -d testDescription' + + ' -a -u ' + userId), flowCreateFields) + const flowId = flowCreateResponse.id - const ioFogCreateResponse = responseHasFields(executeCommand("iofog add -n ioFog1 -l testLocation -t 55 -g 65 " + - "-d testDescription -D testDockerUrl -M 55 -T testDiskDirectoryString -m 65 -c 24 -G 1 -Y testLogDirectory " + - "-C 15 -s 25 -F 27 -Q 26 -B -W -A -y 1 -u " + userId), ioFogCreateFields); - const ioFogUuid = ioFogCreateResponse.uuid; + const ioFogCreateResponse = responseHasFields(executeCommand('iofog add -n ioFog1 -l testLocation -t 55 -g 65 ' + + '-d testDescription -D testDockerUrl -M 55 -T testDiskDirectoryString -m 65 -c 24 -G 1 -Y testLogDirectory ' + + '-C 15 -s 25 -F 27 -Q 26 -B -W -A -y 1 -u ' + userId), ioFogCreateFields) + const ioFogUuid = ioFogCreateResponse.uuid try { - const microserviceCreateResponse = responseHasFields(testCommand("microservice add -n microserviceName1" + - " -c " + catalogId + " -F " + flowId + " -I " + ioFogUuid + " -g '{}' -v /host_src:/container_src:rw -l 15 -R" + - " -p 80:8080:false -u " + userId), microserviceCreateFields); - const microserviceUuid = microserviceCreateResponse.uuid; - responseEquals(testCommand("microservice update -i " + microserviceUuid + " -n microserviceName2" + - " -I " + ioFogUuid + " -g '{}' -v /host_src:/container_src:rw -l 15 -R -w"), - 'Microservice has been updated successfully.'); - responseHasFields(testCommand('microservice list'), microserviceListFields); - responseHasFields(testCommand('microservice info -i ' + microserviceUuid), microserviceCreateFields); + const microserviceCreateResponse = responseHasFields(testCommand('microservice add -n microserviceName1' + + ' -c ' + catalogId + ' -F ' + flowId + ' -I ' + ioFogUuid + ' -g \'{}\' -v /host_src:/container_src:rw -l 15 -R' + + ' -p 80:8080:false -u ' + userId), microserviceCreateFields) + const microserviceUuid = microserviceCreateResponse.uuid + responseEquals(testCommand('microservice update -i ' + microserviceUuid + ' -n microserviceName2' + + ' -I ' + ioFogUuid + ' -g \'{}\' -v /host_src:/container_src:rw -l 15 -R -w'), + 'Microservice has been updated successfully.') + responseHasFields(testCommand('microservice list'), microserviceListFields) + responseHasFields(testCommand('microservice info -i ' + microserviceUuid), microserviceCreateFields) responseContains(testCommand('microservice route-create -T ' + microserviceUuid + ':' + microserviceUuid), - 'has been created successfully'); + 'has been created successfully') responseContains(testCommand('microservice route-remove -T ' + microserviceUuid + ':' + microserviceUuid), - 'has been removed successfully'); + 'has been removed successfully') responseContains(testCommand('microservice port-mapping-create -i ' + microserviceUuid + ' -P 90:9090:false'), - 'Port mapping has been created successfully.'); - responseIsArray(testCommand('microservice port-mapping-list -i ' + microserviceUuid)); + 'Port mapping has been created successfully.') + responseIsArray(testCommand('microservice port-mapping-list -i ' + microserviceUuid)) responseEquals(testCommand('microservice port-mapping-remove -i ' + microserviceUuid + ' -b 90'), - 'Port mapping has been removed successfully.'); + 'Port mapping has been removed successfully.') const volumeMappingCreateResponse = responseHasFields(testCommand('microservice volume-mapping-create' + - ' -i ' + microserviceUuid + ' -P /test_path:/container_test_path:rw'), volumeMappingCreateFields); - const volumeMappingId = volumeMappingCreateResponse.id; - responseIsArray(testCommand('microservice volume-mapping-list -i ' + microserviceUuid)); + ' -i ' + microserviceUuid + ' -P /test_path:/container_test_path:rw'), volumeMappingCreateFields) + const volumeMappingId = volumeMappingCreateResponse.id + responseIsArray(testCommand('microservice volume-mapping-list -i ' + microserviceUuid)) responseContains(testCommand('microservice volume-mapping-remove -i ' + microserviceUuid + ' -a ' + volumeMappingId), - 'Volume mapping has been deleted successfully.'); + 'Volume mapping has been deleted successfully.') responseEquals(testCommand('microservice remove -i ' + microserviceUuid), - 'Microservice has been removed successfully.'); - executeCommand('iofog remove -i ' + ioFogUuid); - executeCommand('flow remove -i ' + flowId); - executeCommand('catalog remove -i ' + catalogId); - executeCommand('user remove -e microserviceUser@domain.com'); + 'Microservice has been removed successfully.') + executeCommand('iofog remove -i ' + ioFogUuid) + executeCommand('flow remove -i ' + flowId) + executeCommand('catalog remove -i ' + catalogId) + executeCommand('user remove -e microserviceUser@domain.com') } catch (exception) { - executeCommand('iofog remove -i ' + ioFogUuid); - executeCommand('flow remove -i ' + flowId); - executeCommand('catalog remove -i ' + catalogId); - executeCommand('registry remove -i ' + registryId); - executeCommand('user remove -e microserviceUser@domain.com'); + executeCommand('iofog remove -i ' + ioFogUuid) + executeCommand('flow remove -i ' + flowId) + executeCommand('catalog remove -i ' + catalogId) + executeCommand('registry remove -i ' + registryId) + executeCommand('user remove -e microserviceUser@domain.com') } } function testRegistrySection() { - console.log("\n=============================\nStarting registry section.."); + console.log('\n=============================\nStarting registry section..') - const userCreateResponse = responseHasFields(executeCommand("user add -f John -l Doe -e registryUser@domain.com" + - " -p '#Bugs4Fun'"), userCreateFields); + const userCreateResponse = responseHasFields(executeCommand('user add -f John -l Doe -e registryUser@domain.com' + + ' -p \'#Bugs4Fun\''), userCreateFields) try { - const userId = userCreateResponse.id; - const registryCreateResponse = responseHasFields(testCommand("registry add -U testRegistryUri -b -l testUserName" + - " -p testPassword -e testEmail@gmail.com -u " + userId), registryCreateFields); - const registryId = registryCreateResponse.id; - responseEquals(testCommand("registry update -i " + registryId + " -U testRegistryUri -b -l testUserName" + - " -p testPassword -e testEmail@gmail.com"), 'Registry has been updated successfully.'); - responseHasFields(testCommand('registry list'), registryListFields); - responseEquals(testCommand('registry remove -i ' + registryId), 'Registry has been removed successfully.'); - executeCommand('user remove -e registryUser@domain.com'); + const userId = userCreateResponse.id + const registryCreateResponse = responseHasFields(testCommand('registry add -U testRegistryUri -b -l testUserName' + + ' -p testPassword -e testEmail@gmail.com -u ' + userId), registryCreateFields) + const registryId = registryCreateResponse.id + responseEquals(testCommand('registry update -i ' + registryId + ' -U testRegistryUri -b -l testUserName' + + ' -p testPassword -e testEmail@gmail.com'), 'Registry has been updated successfully.') + responseHasFields(testCommand('registry list'), registryListFields) + responseEquals(testCommand('registry remove -i ' + registryId), 'Registry has been removed successfully.') + executeCommand('user remove -e registryUser@domain.com') } catch (exception) { - executeCommand('user remove -e registryUser@domain.com'); + executeCommand('user remove -e registryUser@domain.com') } } function testDiagnosticsSection() { - console.log("\n=============================\nStarting diagnostics section.."); + console.log('\n=============================\nStarting diagnostics section..') - const userCreateResponse = responseHasFields(executeCommand("user add -f John -l Doe -e diagnosticsUser@domain.com" + - " -p '#Bugs4Fun'"), userCreateFields); - const userId = userCreateResponse.id; + const userCreateResponse = responseHasFields(executeCommand('user add -f John -l Doe -e diagnosticsUser@domain.com' + + ' -p \'#Bugs4Fun\''), userCreateFields) + const userId = userCreateResponse.id - const registryCreateResponse = responseHasFields(executeCommand("registry add -U testRegistryUri -b -l testUserName" + - " -p testPassword -e testEmail@gmail.com -u " + userId), registryCreateFields); - const registryId = registryCreateResponse.id; + const registryCreateResponse = responseHasFields(executeCommand('registry add -U testRegistryUri -b -l testUserName' + + ' -p testPassword -e testEmail@gmail.com -u ' + userId), registryCreateFields) + const registryId = registryCreateResponse.id - const catalogCreateResponse = responseHasFields(executeCommand("catalog add -n testCatalogItem1 -d testDescription" + - " -c testCategory -x testIntelImage -a testArmImage -p testPublisher -s 15 -r 15 -t testPicture -g " - + registryId + " -I testInputType -F testInputFormat -O testOutputType -T testOutputFormat " + - "-X '{}' -u " + userId), catalogCreateFields); - const catalogId = catalogCreateResponse.id; + const catalogCreateResponse = responseHasFields(executeCommand('catalog add -n testCatalogItem1 -d testDescription' + + ' -c testCategory -x testIntelImage -a testArmImage -p testPublisher -s 15 -r 15 -t testPicture -g ' + + registryId + ' -I testInputType -F testInputFormat -O testOutputType -T testOutputFormat ' + + '-X \'{}\' -u ' + userId), catalogCreateFields) + const catalogId = catalogCreateResponse.id - const flowCreateResponse = responseHasFields(executeCommand("flow add -n testFlow1 -d testDescription" + - " -a -u " + userId), flowCreateFields); - const flowId = flowCreateResponse.id; + const flowCreateResponse = responseHasFields(executeCommand('flow add -n testFlow1 -d testDescription' + + ' -a -u ' + userId), flowCreateFields) + const flowId = flowCreateResponse.id - const ioFogCreateResponse = responseHasFields(executeCommand("iofog add -n ioFog1 -l testLocation -t 55 -g 65" + - " -d testDescription -D testDockerUrl -M 55 -T testDiskDirectoryString -m 65 -c 24 -G 1 -Y testLogDirectory " + - "-C 15 -s 25 -F 27 -Q 26 -B -W -A -y 1 -u " + userId), ioFogCreateFields); - const ioFogUuid = ioFogCreateResponse.uuid; + const ioFogCreateResponse = responseHasFields(executeCommand('iofog add -n ioFog1 -l testLocation -t 55 -g 65' + + ' -d testDescription -D testDockerUrl -M 55 -T testDiskDirectoryString -m 65 -c 24 -G 1 -Y testLogDirectory ' + + '-C 15 -s 25 -F 27 -Q 26 -B -W -A -y 1 -u ' + userId), ioFogCreateFields) + const ioFogUuid = ioFogCreateResponse.uuid - const microserviceCreateResponse = responseHasFields(executeCommand("microservice add -n microserviceName1" + - " -c " + catalogId + " -F " + flowId + " -I " + ioFogUuid + " -g '{}' -v /host_src:/container_src:rw -l 15 -R" + - " -p 80:8080:false -u " + userId), microserviceCreateFields); - const microserviceUuid = microserviceCreateResponse.uuid; + const microserviceCreateResponse = responseHasFields(executeCommand('microservice add -n microserviceName1' + + ' -c ' + catalogId + ' -F ' + flowId + ' -I ' + ioFogUuid + ' -g \'{}\' -v /host_src:/container_src:rw -l 15 -R' + + ' -p 80:8080:false -u ' + userId), microserviceCreateFields) + const microserviceUuid = microserviceCreateResponse.uuid try { - responseEquals(testCommand("diagnostics strace-update -e -i " + microserviceUuid), - 'Microservice strace has been enabled'); + responseEquals(testCommand('diagnostics strace-update -e -i ' + microserviceUuid), + 'Microservice strace has been enabled') responseContains(testCommand('diagnostics strace-info -f string -i ' + microserviceUuid), - 'Microservice strace data has been retrieved successfully.'); + 'Microservice strace data has been retrieved successfully.') responseContains(testCommand('diagnostics strace-ftp-post -i ' + microserviceUuid + ' -h ftpTestHost -p 2024' + - ' -u testFtpUser -s testFtpPass -d ftpTestDestination'), 'FTP error'); + ' -u testFtpUser -s testFtpPass -d ftpTestDestination'), 'FTP error') responseContains(testCommand('diagnostics image-snapshot-create -i ' + microserviceUuid), - 'Microservice image snapshot has been created successfully.'); + 'Microservice image snapshot has been created successfully.') responseContains(testCommand('diagnostics image-snapshot-get -i ' + microserviceUuid), - 'Image snapshot is not available for this microservice.'); - executeCommand('microservice remove -i ' + microserviceUuid); - executeCommand('iofog remove -i ' + ioFogUuid); - executeCommand('flow remove -i ' + flowId); - executeCommand('catalog remove -i ' + catalogId); - executeCommand('registry remove -i ' + registryId); - executeCommand('user remove -e diagnosticsUser@domain.com'); + 'Image snapshot is not available for this microservice.') + executeCommand('microservice remove -i ' + microserviceUuid) + executeCommand('iofog remove -i ' + ioFogUuid) + executeCommand('flow remove -i ' + flowId) + executeCommand('catalog remove -i ' + catalogId) + executeCommand('registry remove -i ' + registryId) + executeCommand('user remove -e diagnosticsUser@domain.com') } catch (exception) { - executeCommand('microservice remove -i ' + microserviceUuid); - executeCommand('iofog remove -i ' + ioFogUuid); - executeCommand('flow remove -i ' + flowId); - executeCommand('catalog remove -i ' + catalogId); - executeCommand('registry remove -i ' + registryId); - executeCommand('user remove -e diagnosticsUser@domain.com'); + executeCommand('microservice remove -i ' + microserviceUuid) + executeCommand('iofog remove -i ' + ioFogUuid) + executeCommand('flow remove -i ' + flowId) + executeCommand('catalog remove -i ' + catalogId) + executeCommand('registry remove -i ' + registryId) + executeCommand('user remove -e diagnosticsUser@domain.com') } } function testCommand(command) { - console.log("\n Testing command '" + command + "'"); - testsCounter++; - return executeCommand(command); + console.log('\n Testing command \'' + command + '\'') + testsCounter++ + return executeCommand(command) } function executeCommand(command) { - let response = execSync('node ./src/main.js ' + command, options); - response = response.toString(); - response = response.replace(/\r?\n?/g, ''); // remove line breaks - return response; + let response = execSync('node ./src/main.js ' + command, options) + response = response.toString() + response = response.replace(/\r?\n?/g, '') // remove line breaks + return response } function hasSomeResponse(response) { if (response === undefined || response === null) { - testsFailed++; - console.log("'hasSomeResponse' test failed with response: " + JSON.stringify(response)); + testsFailed++ + console.log('\'hasSomeResponse\' test failed with response: ' + JSON.stringify(response)) } } function responseIsArray(jsonResponse) { try { - const response = JSON.parse(jsonResponse); + const response = JSON.parse(jsonResponse) if (!Array.isArray(response)) { - testsFailed++; - console.log("'responseIsArray' test failed with response: " + JSON.stringify(response)); + testsFailed++ + console.log('\'responseIsArray\' test failed with response: ' + JSON.stringify(response)) } } catch (exception) { - testsFailed++; - console.log("'responseIsArray' test failed due to invalid JSON with response: " + JSON.stringify(jsonResponse)); + testsFailed++ + console.log('\'responseIsArray\' test failed due to invalid JSON with response: ' + JSON.stringify(jsonResponse)) } } function responseHasFields(jsonResponse, fields) { try { - const response = JSON.parse(jsonResponse); + const response = JSON.parse(jsonResponse) for (const field of fields) { if (!response.hasOwnProperty(field)) { - testsFailed++; - console.log("'responseHasFields' test failed with response: " + JSON.stringify(response)); + testsFailed++ + console.log('\'responseHasFields\' test failed with response: ' + JSON.stringify(response)) } } - return response; + return response } catch (exception) { - testsFailed++; - console.log("'responseHasFields' test failed due to invalid JSON with response: " + JSON.stringify(jsonResponse)); + testsFailed++ + console.log('\'responseHasFields\' test failed due to invalid JSON with response: ' + JSON.stringify(jsonResponse)) } } function responseEquals(response, expectedResponse) { if (response !== expectedResponse) { - testsFailed++; - console.log("'responseEquals' test failed with response: " + JSON.stringify(response)); + testsFailed++ + console.log('\'responseEquals\' test failed with response: ' + JSON.stringify(response)) } } function responseContains(response, expectedResponsePart) { if (!response.includes(expectedResponsePart)) { - testsFailed++; - console.log("'responseContains' test failed with response: " + JSON.stringify(response)); + testsFailed++ + console.log('\'responseContains\' test failed with response: ' + JSON.stringify(response)) } } function cliTest() { try { - backupDBs(); - //create new DBs - init(); - - testControllerSection(); - testUserSection(); - testConfigSection(); - testConnectorSection(); - testTunnelSection(); - testIoFogSection(); - testCatalogSection(); - testFlowSection(); - testMicroserviceSection(); - testRegistrySection(); - testDiagnosticsSection(); - - restoreDBs(); + backupDBs() + // create new DBs + init() + + testControllerSection() + testUserSection() + testConfigSection() + testConnectorSection() + testTunnelSection() + testIoFogSection() + testCatalogSection() + testFlowSection() + testMicroserviceSection() + testRegistrySection() + testDiagnosticsSection() + + restoreDBs() } catch (exception) { - restoreDBs(); + restoreDBs() - console.log("\nException during execution: "); - console.error(exception); - process.exit(1); + console.log('\nException during execution: ') + console.error(exception) + process.exit(1) } if (testsFailed > 0) { - console.log("\nFailed tests count: " + testsFailed); - process.exit(1); + console.log('\nFailed tests count: ' + testsFailed) + process.exit(1) } else { - console.log("\nCLI Tests passed successfully."); + console.log('\nCLI Tests passed successfully.') } } module.exports = { - cliTest: cliTest -}; \ No newline at end of file + cliTest: cliTest, +} diff --git a/scripts/coverage.js b/scripts/coverage.js index 3a7dae7a3..e2bd74a47 100644 --- a/scripts/coverage.js +++ b/scripts/coverage.js @@ -11,20 +11,20 @@ * */ -const execSync = require('child_process').execSync; +const execSync = require('child_process').execSync function coverage() { const options = { env: { 'NODE_ENV': 'test', - "PATH": process.env.PATH + 'PATH': process.env.PATH, }, - stdio: [process.stdin, process.stdout, process.stderr] - }; + stdio: [process.stdin, process.stdout, process.stderr], + } - execSync('nyc mocha', options); + execSync('nyc mocha', options) } module.exports = { - coverage: coverage -}; \ No newline at end of file + coverage: coverage, +} diff --git a/scripts/init.js b/scripts/init.js index 3bdf92c54..9258e9264 100644 --- a/scripts/init.js +++ b/scripts/init.js @@ -11,21 +11,21 @@ * */ -const execSync = require('child_process').execSync; +const execSync = require('child_process').execSync function init() { const options = { env: { 'NODE_ENV': 'production', - "PATH": process.env.PATH + 'PATH': process.env.PATH, }, - stdio: [process.stdin, process.stdout, process.stderr] - }; + stdio: [process.stdin, process.stdout, process.stderr], + } - execSync('node ./src/main.js init', options); + execSync('node ./src/main.js init', options) } module.exports = { - init: init -}; \ No newline at end of file + init: init, +} diff --git a/scripts/postinstall.js b/scripts/postinstall.js index 98e21ad49..a7723b45c 100644 --- a/scripts/postinstall.js +++ b/scripts/postinstall.js @@ -8,172 +8,171 @@ * * * * SPDX-License-Identifier: EPL-2.0 * ******************************************************************************* - * + * */ -const sqlite3 = require('sqlite3');//.verbose(); //use verbose in dev to get stack traces -const os = require('os'); -const execSync = require('child_process').execSync; -const fs = require('fs'); -const semver = require('semver'); -const config = require('../src/config'); -const currentVersion = require('../package').version; -const {restoreDBs, restoreConfigs, INSTALLATION_VARIABLES_FILE} = require('./util'); + +const sqlite3 = require('sqlite3') // .verbose() //use verbose in dev to get stack traces +const execSync = require('child_process').execSync +const fs = require('fs') +const semver = require('semver') +const config = require('../src/config') +const currentVersion = require('../package').version +const {restoreDBs, restoreConfigs, INSTALLATION_VARIABLES_FILE} = require('./util') function postinstall() { -//restore all files - restoreDBs(); - restoreConfigs(); +// restore all files + restoreDBs() + restoreConfigs() -//process migrations + // process migrations try { - const installationVarsStr = fs.readFileSync(INSTALLATION_VARIABLES_FILE); - const installationVars = JSON.parse(installationVarsStr); - const prevVersion = installationVars.prevVer; + const installationVarsStr = fs.readFileSync(INSTALLATION_VARIABLES_FILE) + const installationVars = JSON.parse(installationVarsStr) + const prevVersion = installationVars.prevVer - console.log(`previous version - ${prevVersion}`); - console.log(`new version - ${currentVersion}`); + console.log(`previous version - ${prevVersion}`) + console.log(`new version - ${currentVersion}`) if (semver.satisfies(prevVersion, '<=1.0.0')) { - console.log('upgrading from version <= 1.0.0 :'); - insertSeeds(); + console.log('upgrading from version <= 1.0.0 :') + insertSeeds() } if (semver.satisfies(prevVersion, '<=1.0.30')) { - console.log('upgrading from version <= 1.0.30 :'); - updateEncryptionMethod(); + console.log('upgrading from version <= 1.0.30 :') + updateEncryptionMethod() } if (semver.satisfies(prevVersion, '<=1.0.37')) { - console.log('upgrading from version <= 1.0.37 :'); - updateLogName(); + console.log('upgrading from version <= 1.0.37 :') + updateLogName() } - fs.unlinkSync(INSTALLATION_VARIABLES_FILE); + fs.unlinkSync(INSTALLATION_VARIABLES_FILE) } catch (e) { - console.log('no previous version'); + console.log('no previous version') } -//init db + // init db const options = { env: { 'NODE_ENV': 'production', - "PATH": process.env.PATH + 'PATH': process.env.PATH, }, - stdio: [process.stdin, process.stdout, process.stderr] - }; + stdio: [process.stdin, process.stdout, process.stderr], + } - execSync('node ./src/main.js init', options); + execSync('node ./src/main.js init', options) } -//other functions definitions +// other functions definitions function insertSeeds() { - console.log(' inserting seeds meta info in db'); - const sqlite3ProdDb = new sqlite3.Database(prodDb); + console.log(' inserting seeds meta info in db') + const sqlite3ProdDb = new sqlite3.Database(prodDb) const seeds = [ '20180928110125-insert-registry.js', '20180928111532-insert-catalog-item.js', '20180928112152-insert-iofog-type.js', - '20180928121334-insert-catalog-item-image.js' - ]; + '20180928121334-insert-catalog-item-image.js', + ] sqlite3ProdDb.serialize(function() { - const stmt = sqlite3ProdDb.prepare("INSERT INTO SequelizeMeta (name) VALUES (?)"); - seeds.map(s => stmt.run(s)); - stmt.finalize(); - }); - sqlite3ProdDb.close(); + const stmt = sqlite3ProdDb.prepare('INSERT INTO SequelizeMeta (name) VALUES (?)') + seeds.map((s) => stmt.run(s)) + stmt.finalize() + }) + sqlite3ProdDb.close() } function updateEncryptionMethodForUsersPassword(decryptionFunc) { - console.log(' updating encryption in DB'); - const sqlite3ProdDb = new sqlite3.Database(prodDb); + console.log(' updating encryption in DB') + const sqlite3ProdDb = new sqlite3.Database(prodDb) sqlite3ProdDb.all('select id, email, password from Users', function(err, rows) { - const stmt = sqlite3ProdDb.prepare('update Users set password=? where id=?'); + const stmt = sqlite3ProdDb.prepare('update Users set password=? where id=?') - rows.map(user => { + rows.map((user) => { try { - const id = user.id; - const email = user.email; - const oldEncryptedPassword = user.password; + const id = user.id + const email = user.email + const oldEncryptedPassword = user.password - const decryptedPassword = decryptionFunc(oldEncryptedPassword, email); - const AppHelper = require('../src/helpers/app-helper'); - const newEncryptedPassword = AppHelper.encryptText(decryptedPassword, email); + const decryptedPassword = decryptionFunc(oldEncryptedPassword, email) + const AppHelper = require('../src/helpers/app-helper') + const newEncryptedPassword = AppHelper.encryptText(decryptedPassword, email) - stmt.run(newEncryptedPassword, id); + stmt.run(newEncryptedPassword, id) } catch (e) { - console.log('db problem'); - console.log(e); + console.log('db problem') + console.log(e) } - }); - stmt.finalize(); - }); - sqlite3ProdDb.close(); + }) + stmt.finalize() + }) + sqlite3ProdDb.close() } function updateEncryptionMethodForEmailService(configFile, decryptionFunc) { - console.log(configFile); + console.log(configFile) if (!configFile) { return } - const configObj = JSON.parse(fs.readFileSync(configFile, 'utf8')); - console.log(configObj); + const configObj = JSON.parse(fs.readFileSync(configFile, 'utf8')) + console.log(configObj) if (!configObj || !configObj.Email || !configObj.Email.Address || !configObj.Email.Password) { return } - const email = configObj.Email.Address; - const oldEncryptedPassword = configObj.Email.Password; + const email = configObj.Email.Address + const oldEncryptedPassword = configObj.Email.Password - const decryptedPassword = decryptionFunc(oldEncryptedPassword, email); + const decryptedPassword = decryptionFunc(oldEncryptedPassword, email) - const AppHelper = require('../src/helpers/app-helper'); - configObj.Email.Password = AppHelper.encryptText(decryptedPassword, email); + const AppHelper = require('../src/helpers/app-helper') + configObj.Email.Password = AppHelper.encryptText(decryptedPassword, email) - console.log(configObj); + console.log(configObj) try { - fs.writeFileSync(configFile, JSON.stringify(configObj, null, 2)); + fs.writeFileSync(configFile, JSON.stringify(configObj, null, 2)) } catch (e) { console.log(e) } } function updateEncryptionMethod() { - console.log(' updating encryption method for old users'); + console.log(' updating encryption method for old users') function decryptTextVer30(text, salt) { - const crypto = require('crypto'); - const ALGORITHM = 'aes-256-ctr'; + const crypto = require('crypto') + const ALGORITHM = 'aes-256-ctr' - const decipher = crypto.createDecipher(ALGORITHM, salt); - let dec = decipher.update(text, 'hex', 'utf8'); - dec += decipher.final('utf8'); + const decipher = crypto.createDecipher(ALGORITHM, salt) + let dec = decipher.update(text, 'hex', 'utf8') + dec += decipher.final('utf8') return dec } - updateEncryptionMethodForUsersPassword(decryptTextVer30); - console.log(' updating encryption for email services in configs'); - updateEncryptionMethodForEmailService(defConfig, decryptTextVer30); - updateEncryptionMethodForEmailService(devConfig, decryptTextVer30); - updateEncryptionMethodForEmailService(prodConfig, decryptTextVer30); + updateEncryptionMethodForUsersPassword(decryptTextVer30) + console.log(' updating encryption for email services in configs') + updateEncryptionMethodForEmailService(defConfig, decryptTextVer30) + updateEncryptionMethodForEmailService(devConfig, decryptTextVer30) + updateEncryptionMethodForEmailService(prodConfig, decryptTextVer30) } function updateLogName() { - console.log(' updating log name in '); + console.log(' updating log name in ') const dirname = config.get('Service:LogsDirectory') if (fs.existsSync(dirname)) { - fs.readdirSync(dirname).forEach(file => { + fs.readdirSync(dirname).forEach((file) => { const path = dirname + '/' + file if (fs.existsSync(path)) { fs.unlinkSync(path, function(err) { - if (err) return console.log(err); - console.log('log deleted successfully'); + if (err) return console.log(err) + console.log('log deleted successfully') }) } - }); + }) } - } module.exports = { - postinstall: postinstall -}; \ No newline at end of file + postinstall: postinstall, +} diff --git a/scripts/postmantest.js b/scripts/postmantest.js index b695a8926..dfc2d53c6 100644 --- a/scripts/postmantest.js +++ b/scripts/postmantest.js @@ -10,42 +10,41 @@ * ******************************************************************************* * */ - -const newman = require('newman'); -const {init} = require('./init'); -const {restoreDBs, backupDBs} = require('./util'); -const {start} = require('./start'); -const {stop} = require('./stop'); + +const newman = require('newman') +const {init} = require('./init') +const {restoreDBs, backupDBs} = require('./util') +const {start} = require('./start') +const {stop} = require('./stop') function postmanTest() { - stop(); - backupDBs(); -//create new DBs - init(); - start(); -// call newman.run to pass `options` object and wait for callback - newman.run({ - collection: require('../test/postman_collection.json'), - reporters: 'cli', - //abortOnError: true, - //abortOnFailure: true - }).on('start', function (err, args) { // on start of run, log to console - console.log('running a collection...'); - }).on('done', function (err, summary) { - if (err || summary.error || summary.run.failures.length != 0) { - restoreDBs(); - stop(); - console.error('collection run encountered an error. tests did not pass.'); - process.exitCode = 1; - } - else { - restoreDBs(); - stop(); - console.log('collection run completed.'); - } - }); + stop() + backupDBs() + // create new DBs + init() + start() + // call newman.run to pass `options` object and wait for callback + newman.run({ + collection: require('../test/postman_collection.json'), + reporters: 'cli', + // abortOnError: true, + // abortOnFailure: true + }).on('start', function(err, args) { // on start of run, log to console + console.log('running a collection...') + }).on('done', function(err, summary) { + if (err || summary.error || summary.run.failures.length != 0) { + restoreDBs() + stop() + console.error('collection run encountered an error. tests did not pass.') + process.exitCode = 1 + } else { + restoreDBs() + stop() + console.log('collection run completed.') + } + }) } module.exports = { - postmanTest: postmanTest -}; + postmanTest: postmanTest, +} diff --git a/scripts/preuninstall.js b/scripts/preuninstall.js index f77b84df5..5cbdb7aea 100644 --- a/scripts/preuninstall.js +++ b/scripts/preuninstall.js @@ -11,23 +11,21 @@ * */ -const os = require('os'); -const execSync = require('child_process').execSync; -const fs = require('fs'); -const version = require('../package').version; -const {backupDBs, backupConfigs, INSTALLATION_VARIABLES_FILE} = require('./util'); +const fs = require('fs') +const version = require('../package').version +const {backupDBs, backupConfigs, INSTALLATION_VARIABLES_FILE} = require('./util') function preuninstall() { const instalationVars = { - prevVer: version - }; + prevVer: version, + } - fs.writeFileSync(INSTALLATION_VARIABLES_FILE, JSON.stringify(instalationVars)); + fs.writeFileSync(INSTALLATION_VARIABLES_FILE, JSON.stringify(instalationVars)) - backupDBs(); - backupConfigs(); + backupDBs() + backupConfigs() } module.exports = { - preuninstall: preuninstall -} \ No newline at end of file + preuninstall: preuninstall, +} diff --git a/scripts/scripts-api.js b/scripts/scripts-api.js index 07428e991..2743bdf91 100644 --- a/scripts/scripts-api.js +++ b/scripts/scripts-api.js @@ -11,46 +11,46 @@ * */ -const {start} = require('./start'); -const {startDev} = require('./start-dev'); -const {init} = require('./init'); -const {preuninstall} = require('./preuninstall'); -const {postinstall} = require('./postinstall'); -const {test} = require('./test'); -const {cliTest} = require('./cli-tests'); -const {postmanTest} = require('./postmantest'); -const {coverage} = require('./coverage'); +const {start} = require('./start') +const {startDev} = require('./start-dev') +const {init} = require('./init') +const {preuninstall} = require('./preuninstall') +const {postinstall} = require('./postinstall') +const {test} = require('./test') +const {cliTest} = require('./cli-tests') +const {postmanTest} = require('./postmantest') +const {coverage} = require('./coverage') switch (process.argv[2]) { case 'start': - start(); - break; + start() + break case 'start-dev': - startDev(); - break; + startDev() + break case 'init': - init(); - break; + init() + break case 'preuninstall': - preuninstall(); - break; + preuninstall() + break case 'postinstall': - postinstall(); - break; + postinstall() + break case 'test': - test(); - cliTest(); - break; + test() + cliTest() + break case 'postmantest': - postmanTest(); - break; + postmanTest() + break case 'cli-tests': - cliTest(); - break; + cliTest() + break case 'coverage': - coverage(); - break; + coverage() + break default: - console.log('no script for this command'); - break; -} \ No newline at end of file + console.log('no script for this command') + break +} diff --git a/scripts/start-dev.js b/scripts/start-dev.js index 3a1416dc0..236443432 100644 --- a/scripts/start-dev.js +++ b/scripts/start-dev.js @@ -11,20 +11,20 @@ * */ -const execSync = require('child_process').execSync; +const execSync = require('child_process').execSync function startDev() { const options = { env: { 'NODE_ENV': 'development', - "PATH": process.env.PATH + 'PATH': process.env.PATH, }, - stdio: [process.stdin, process.stdout, process.stderr] - }; + stdio: [process.stdin, process.stdout, process.stderr], + } - execSync('node ./src/main.js start', options); + execSync('node ./src/main.js start', options) } module.exports = { - startDev: startDev -}; \ No newline at end of file + startDev: startDev, +} diff --git a/scripts/start.js b/scripts/start.js index 208fab4d4..cf9ec8378 100644 --- a/scripts/start.js +++ b/scripts/start.js @@ -11,20 +11,20 @@ * */ -const execSync = require('child_process').execSync; +const execSync = require('child_process').execSync function start() { const options = { env: { 'NODE_ENV': 'production', - "PATH": process.env.PATH + 'PATH': process.env.PATH, }, - stdio: [process.stdin, process.stdout, process.stderr] - }; + stdio: [process.stdin, process.stdout, process.stderr], + } - execSync('node ./src/main.js start', options); + execSync('node ./src/main.js start', options) } module.exports = { - start: start -}; \ No newline at end of file + start: start, +} diff --git a/scripts/stop.js b/scripts/stop.js index 1771f8735..f1758ae71 100644 --- a/scripts/stop.js +++ b/scripts/stop.js @@ -11,20 +11,20 @@ * */ -const execSync = require('child_process').execSync; +const execSync = require('child_process').execSync function stop() { const options = { env: { 'NODE_ENV': 'production', - "PATH": process.env.PATH + 'PATH': process.env.PATH, }, - stdio: [process.stdin, process.stdout, process.stderr] - }; + stdio: [process.stdin, process.stdout, process.stderr], + } - execSync('node ./src/main.js stop', options); + execSync('node ./src/main.js stop', options) } module.exports = { - stop: stop -}; \ No newline at end of file + stop: stop, +} diff --git a/scripts/test.js b/scripts/test.js index a185cdd73..7772cab8e 100644 --- a/scripts/test.js +++ b/scripts/test.js @@ -11,20 +11,20 @@ * */ -const execSync = require('child_process').execSync; +const execSync = require('child_process').execSync function test() { const options = { env: { 'NODE_ENV': 'test', - "PATH": process.env.PATH + 'PATH': process.env.PATH, }, - stdio: [process.stdin, process.stdout, process.stderr] - }; + stdio: [process.stdin, process.stdout, process.stderr], + } - execSync('mocha', options); + execSync('mocha', options) } module.exports = { - test: test -}; \ No newline at end of file + test: test, +} diff --git a/scripts/util.js b/scripts/util.js index 97d3f6d0a..8fd2e1434 100644 --- a/scripts/util.js +++ b/scripts/util.js @@ -11,36 +11,36 @@ * */ -const os = require('os'); -const fs = require('fs'); -const ROOT_DIR = `${__dirname}/..`; -const TEMP_DIR = getTempDir(); +const os = require('os') +const fs = require('fs') +const ROOT_DIR = `${__dirname}/..` +const TEMP_DIR = getTempDir() -const DEV_DB = `${ROOT_DIR}/src/sequelize/dev_database.sqlite`; -const DEV_DB_BACKUP = `${TEMP_DIR}/dev_database.sqlite`; +const DEV_DB = `${ROOT_DIR}/src/sequelize/dev_database.sqlite` +const DEV_DB_BACKUP = `${TEMP_DIR}/dev_database.sqlite` -const PROD_DB = `${ROOT_DIR}/src/sequelize/prod_database.sqlite`; -const PROD_DB_BACKUP = `${TEMP_DIR}/prod_database.sqlite`; +const PROD_DB = `${ROOT_DIR}/src/sequelize/prod_database.sqlite` +const PROD_DB_BACKUP = `${TEMP_DIR}/prod_database.sqlite` -const DEFAULT_CONFIG = `${ROOT_DIR}/src/config/default.json`; -const DEVELOP_CONFIG = `${ROOT_DIR}/src/config/development.json`; -const PRODUCTION_CONFIG = `${ROOT_DIR}/src/config/production.json`; +const DEFAULT_CONFIG = `${ROOT_DIR}/src/config/default.json` +const DEVELOP_CONFIG = `${ROOT_DIR}/src/config/development.json` +const PRODUCTION_CONFIG = `${ROOT_DIR}/src/config/production.json` -const DEFAULT_CONFIG_BACKUP = `${TEMP_DIR}/default_iofog_backup.json`; -const DEVELOP_CONFIG_BACKUP = `${TEMP_DIR}/development_iofog_backup.json`; -const PRODUCTION_CONFIG_BACKUP = `${TEMP_DIR}/production_iofog_backup.json`; +const DEFAULT_CONFIG_BACKUP = `${TEMP_DIR}/default_iofog_backup.json` +const DEVELOP_CONFIG_BACKUP = `${TEMP_DIR}/development_iofog_backup.json` +const PRODUCTION_CONFIG_BACKUP = `${TEMP_DIR}/production_iofog_backup.json` -const INSTALLATION_VARIABLES_FILE = TEMP_DIR + '/iofogcontroller_install_variables'; +const INSTALLATION_VARIABLES_FILE = TEMP_DIR + '/iofogcontroller_install_variables' function backupDBs() { - renameFile(DEV_DB, DEV_DB_BACKUP); - renameFile(PROD_DB, PROD_DB_BACKUP); + renameFile(DEV_DB, DEV_DB_BACKUP) + renameFile(PROD_DB, PROD_DB_BACKUP) } function restoreDBs() { - renameFile(DEV_DB_BACKUP, DEV_DB); - renameFile(PROD_DB_BACKUP, PROD_DB); + renameFile(DEV_DB_BACKUP, DEV_DB) + renameFile(PROD_DB_BACKUP, PROD_DB) } function renameFile(oldPath, newPath) { @@ -50,31 +50,31 @@ function renameFile(oldPath, newPath) { } function getTempDir() { - let tempDir; + let tempDir if (os.type() === 'Linux') { - tempDir = '/tmp'; + tempDir = '/tmp' } else if (os.type() === 'Darwin') { - tempDir = '/tmp'; + tempDir = '/tmp' } else if (os.type() === 'Windows_NT') { - tempDir = `${process.env.APPDATA}`; + tempDir = `${process.env.APPDATA}` } else { - throw new Error("Unsupported OS found: " + os.type()); + throw new Error('Unsupported OS found: ' + os.type()) } - return tempDir; + return tempDir } function backupConfigs() { - renameFile(DEFAULT_CONFIG, DEFAULT_CONFIG_BACKUP); - renameFile(DEVELOP_CONFIG, DEVELOP_CONFIG_BACKUP); - renameFile(PRODUCTION_CONFIG, PRODUCTION_CONFIG_BACKUP); + renameFile(DEFAULT_CONFIG, DEFAULT_CONFIG_BACKUP) + renameFile(DEVELOP_CONFIG, DEVELOP_CONFIG_BACKUP) + renameFile(PRODUCTION_CONFIG, PRODUCTION_CONFIG_BACKUP) } function restoreConfigs() { - renameFile(DEFAULT_CONFIG_BACKUP, DEFAULT_CONFIG); - renameFile(DEVELOP_CONFIG_BACKUP, DEVELOP_CONFIG); - renameFile(PRODUCTION_CONFIG_BACKUP, PRODUCTION_CONFIG); + renameFile(DEFAULT_CONFIG_BACKUP, DEFAULT_CONFIG) + renameFile(DEVELOP_CONFIG_BACKUP, DEVELOP_CONFIG) + renameFile(PRODUCTION_CONFIG_BACKUP, PRODUCTION_CONFIG) } module.exports = { @@ -86,5 +86,5 @@ module.exports = { getTempDir: getTempDir, TEMP_DIR: TEMP_DIR, - INSTALLATION_VARIABLES_FILE: INSTALLATION_VARIABLES_FILE -}; \ No newline at end of file + INSTALLATION_VARIABLES_FILE: INSTALLATION_VARIABLES_FILE, +} diff --git a/src/cli/base-cli-handler.js b/src/cli/base-cli-handler.js index f51315121..c5fb8dc4b 100644 --- a/src/cli/base-cli-handler.js +++ b/src/cli/base-cli-handler.js @@ -11,18 +11,17 @@ * */ -const commandLineArgs = require('command-line-args'); -const commandLineUsage = require('command-line-usage'); -const AppHelper = require('../helpers/app-helper'); -const Errors = require('../helpers/errors'); -const ErrorMessages = require('../helpers/error-messages'); -const constants = require('../helpers/constants'); +const commandLineArgs = require('command-line-args') +const commandLineUsage = require('command-line-usage') +const AppHelper = require('../helpers/app-helper') +const Errors = require('../helpers/errors') +const ErrorMessages = require('../helpers/error-messages') const logger = require('../logger') class CLIHandler { constructor() { - this.commandDefinitions = []; - this.commands = {}; + this.commandDefinitions = [] + this.commands = {} this.name = '' } @@ -31,59 +30,58 @@ class CLIHandler { } parseCommandLineArgs(commandDefinitions, options = {}) { - return commandLineArgs(commandDefinitions, Object.assign({camelCase: true, partial: true,}, options)) + return commandLineArgs(commandDefinitions, Object.assign({camelCase: true, partial: true}, options)) } help(show = [], showOptions = true, hasCommands = true, additionalSection = []) { - if (show.length === 0) { - //show all + // show all this.helpAll(show, showOptions, hasCommands, additionalSection) } else { - //show list + // show list this.helpSome(show, showOptions) } } helpSome(show = [], showOptions = true,) { const options = Object.keys(this.commands) - .filter((key) => show.indexOf(key) !== -1) - .map((key) => ({ - header: key, - optionList: this.commandDefinitions, - group: [key], - })); + .filter((key) => show.indexOf(key) !== -1) + .map((key) => ({ + header: key, + optionList: this.commandDefinitions, + group: [key], + })) const sections = [ { header: 'Usage', content: `$ iofog-controller ${this.name} ${show.length === 1 ? show : ''} `, }, - ].concat(showOptions ? options : []); + ].concat(showOptions ? options : []) const usage = [ { header: 'ioFogController', content: 'Fog Controller project for Eclipse IoFog @ iofog.org \\nCopyright (c) 2018 Edgeworx, Inc.', - } - ].concat(sections); + }, + ].concat(sections) logger.cliRes(commandLineUsage(usage)) } helpAll(show = [], showOptions = true, hasCommands = true, additionalSection = []) { const options = Object.keys(this.commands) - .map((key) => ({ - header: key, - optionList: this.commandDefinitions, - group: [key], - })); + .map((key) => ({ + header: key, + optionList: this.commandDefinitions, + group: [key], + })) const commandsList = { header: 'Command List', content: Object.keys(this.commands).map((key) => ({ name: key, summary: this.commands[key], })), - }; + } const sections = [ { @@ -91,204 +89,204 @@ class CLIHandler { content: `$ iofog-controller ${this.name}${hasCommands ? ' ' : ''} `, }, ].concat(hasCommands ? commandsList : []) - .concat(showOptions ? options : []) - .concat(additionalSection); + .concat(showOptions ? options : []) + .concat(additionalSection) const usage = [ { header: 'ioFogController', content: 'Fog Controller project for Eclipse IoFog @ iofog.org \\nCopyright (c) 2018 Edgeworx, Inc.', - } - ].concat(sections); + }, + ].concat(sections) logger.cliRes(commandLineUsage(usage)) } handleCLIError(error, args) { switch (error.name) { - case "UNKNOWN_OPTION": - logger.error("Invalid argument '" + error.optionName.split('-').join('') + "'"); - break; - case "UNKNOWN_VALUE": + case 'UNKNOWN_OPTION': + logger.error('Invalid argument \'' + error.optionName.split('-').join('') + '\'') + break + case 'UNKNOWN_VALUE': if (this.commands[args[0]] && args[1] === 'help') { - return this.helpSome([args[0]]); + return this.helpSome([args[0]]) } - logger.error("Invalid value " + error.value); - break; - case "InvalidArgumentError": - logger.error(error.message); - break; - case "InvalidArgumentTypeError": - logger.error(error.message); - break; - case "ALREADY_SET": - logger.error("Parameter '" + error.optionName + "' is used multiple times"); - break; + logger.error('Invalid value ' + error.value) + break + case 'InvalidArgumentError': + logger.error(error.message) + break + case 'InvalidArgumentTypeError': + logger.error(error.message) + break + case 'ALREADY_SET': + logger.error('Parameter \'' + error.optionName + '\' is used multiple times') + break case 'CLIArgsNotProvidedError': if (this.commands[args[0]]) { - return this.helpSome([args[0]]); + return this.helpSome([args[0]]) } - break; + break default: - logger.error(JSON.stringify(error)); - break; + logger.error(JSON.stringify(error)) + break } } validateParameters(command, commandDefinitions, pArgs) { // 1st argument = command - let args = pArgs.slice(); - args.shift(); + const args = pArgs.slice() + args.shift() - const possibleAliasesList = _getPossibleAliasesList(command, commandDefinitions); - const possibleArgsList = _getPossibleArgsList(command, commandDefinitions); + const possibleAliasesList = _getPossibleAliasesList(command, commandDefinitions) + const possibleArgsList = _getPossibleArgsList(command, commandDefinitions) if (possibleAliasesList.length === 0 && possibleArgsList.length === 0) { return } - let expectedValueType; - let currentArgName; + let expectedValueType + let currentArgName if (args.length === 0) { - throw new Errors.CLIArgsNotProvidedError(); + throw new Errors.CLIArgsNotProvidedError() } - const argsMap = argsArrayAsMap(args); + const argsMap = argsArrayAsMap(args) argsMap.forEach((values, key) => { - if (key.startsWith("--")) { // argument + if (key.startsWith('--')) { // argument // '--ssl-cert' format -> 'ssl-cert' format - const argument = key.substr(2); - _validateArg(argument, possibleArgsList); - currentArgName = argument; - expectedValueType = _getValType(argument, commandDefinitions); - } else if (key.startsWith("-")) { // alias + const argument = key.substr(2) + _validateArg(argument, possibleArgsList) + currentArgName = argument + expectedValueType = _getValType(argument, commandDefinitions) + } else if (key.startsWith('-')) { // alias // '-q' format -> 'q' format - const alias = key.substr(1); - _validateArg(alias, possibleAliasesList); - currentArgName = alias; - expectedValueType = _getValType(alias, commandDefinitions); + const alias = key.substr(1) + _validateArg(alias, possibleAliasesList) + currentArgName = alias + expectedValueType = _getValType(alias, commandDefinitions) } - const valType = _getCurrentValType(values); - //TODO else validate multiply parameters. Add after multiply parameters will be used in cli api + const valType = _getCurrentValType(values) + // TODO else validate multiply parameters. Add after multiply parameters will be used in cli api - let isValidType = _validateType(expectedValueType, valType); + const isValidType = _validateType(expectedValueType, valType) if (!isValidType) { - throw new Errors.InvalidArgumentTypeError(AppHelper.formatMessage(ErrorMessages.INVALID_CLI_ARGUMENT_TYPE, currentArgName, expectedValueType)); + throw new Errors.InvalidArgumentTypeError(AppHelper.formatMessage(ErrorMessages.INVALID_CLI_ARGUMENT_TYPE, + currentArgName, expectedValueType)) } }) } } function argsArrayAsMap(args) { - let argsVars = args.join(' ').split(/(?= -{1,2}[^-]+)/); - const argsMap = new Map(); + const argsVars = args.join(' ').split(/(?= -{1,2}[^-]+)/) + const argsMap = new Map() argsVars - .map(pair => pair.trim()) - .map(pair => { - const spaceIndex = pair.indexOf(' '); - let key, values; - if (spaceIndex !== -1) { - key = pair.substr(0, pair.indexOf(' ')); - values = pair.substr(pair.indexOf(' ')+1).split(' '); - argsMap.set(key, values); - } else { - key = pair; - values = []; - } - argsMap.set(key, values); - - }); - return argsMap; + .map((pair) => pair.trim()) + .map((pair) => { + const spaceIndex = pair.indexOf(' ') + let key; let values + if (spaceIndex !== -1) { + key = pair.substr(0, pair.indexOf(' ')) + values = pair.substr(pair.indexOf(' ')+1).split(' ') + argsMap.set(key, values) + } else { + key = pair + values = [] + } + argsMap.set(key, values) + }) + return argsMap } function _validateArg(arg, aliasesList) { - const valid = aliasesList.includes(arg); + const valid = aliasesList.includes(arg) if (!valid) { - throw new Errors.InvalidArgumentError("Invalid argument '" + arg + "'"); + throw new Errors.InvalidArgumentError('Invalid argument \'' + arg + '\'') } } function _getPossibleAliasesList(command, commandDefinitions) { - const possibleAliasesList = []; + const possibleAliasesList = [] for (const definition of commandDefinitions) { - const group = definition.group; - const isGroupArray = group.constructor === Array; + const group = definition.group + const isGroupArray = group.constructor === Array if (isGroupArray) { for (const gr of group) { if (gr === command) { - possibleAliasesList.push(definition.alias); - break; + possibleAliasesList.push(definition.alias) + break } } } else { if (group === command) { - possibleAliasesList.push(definition.alias); + possibleAliasesList.push(definition.alias) } } } - return possibleAliasesList; + return possibleAliasesList } function _getPossibleArgsList(command, commandDefinitions) { - const possibleArgsList = []; + const possibleArgsList = [] for (const definition of commandDefinitions) { - const group = definition.group; - const isGroupArray = group.constructor === Array; + const group = definition.group + const isGroupArray = group.constructor === Array if (isGroupArray) { for (const gr of group) { if (gr === command) { - possibleArgsList.push(definition.name); - break; + possibleArgsList.push(definition.name) + break } } } else { if (group === command) { - possibleArgsList.push(definition.name); + possibleArgsList.push(definition.name) } } } - return possibleArgsList; + return possibleArgsList } function _getValType(arg, commandDefinitions) { const command = commandDefinitions - .filter(def => def.name === arg || def.alias === arg)[0]; - return command.type.name.toLowerCase(); + .filter((def) => def.name === arg || def.alias === arg)[0] + return command.type.name.toLowerCase() } function _getCurrentValType(values) { - let valType; + let valType if (values.length === 0) { - valType = 'boolean'; + valType = 'boolean' } else if (values.length === 1) { - const firstVal = Number(values[0]); + const firstVal = Number(values[0]) if (Number.isNaN(firstVal.valueOf())) { - valType = 'string'; + valType = 'string' } else if (Number.isInteger(firstVal.valueOf())) { - valType = 'integer'; + valType = 'integer' } else { valType = 'float' } } - return valType; + return valType } function _validateType(expectedValueType, valType) { - let isValidType = true; + let isValidType = true if ((expectedValueType === 'float' || expectedValueType === 'number') && (valType !== 'float' && valType !== 'number' && valType !== 'integer')) { - isValidType = false; + isValidType = false } else if (expectedValueType === 'integer' && valType !== 'integer') { - isValidType = false; + isValidType = false } else if (expectedValueType === 'boolean' && valType !== 'boolean') { - isValidType = false; + isValidType = false } - return isValidType; + return isValidType } -module.exports = CLIHandler; \ No newline at end of file +module.exports = CLIHandler diff --git a/src/cli/catalog.js b/src/cli/catalog.js index 358458267..b00c581c4 100644 --- a/src/cli/catalog.js +++ b/src/cli/catalog.js @@ -11,138 +11,138 @@ * */ -const BaseCLIHandler = require('./base-cli-handler'); -const constants = require('../helpers/constants'); -const logger = require('../logger'); -const CatalogItemService = require('../services/catalog-service'); -const fs = require('fs'); -const AppHelper = require('../helpers/app-helper'); -const AuthDecorator = require('../decorators/cli-decorator'); -const Errors = require('../helpers/errors'); -const ErrorMessages = require('../helpers/error-messages'); -const CliDataTypes = require('./cli-data-types'); +const BaseCLIHandler = require('./base-cli-handler') +const constants = require('../helpers/constants') +const logger = require('../logger') +const CatalogItemService = require('../services/catalog-service') +const fs = require('fs') +const AppHelper = require('../helpers/app-helper') +const AuthDecorator = require('../decorators/cli-decorator') +const Errors = require('../helpers/errors') +const ErrorMessages = require('../helpers/error-messages') +const CliDataTypes = require('./cli-data-types') const JSON_SCHEMA = AppHelper.stringifyCliJsonSchema({ - name: "string", - description: "string", - category: "string", + name: 'string', + description: 'string', + category: 'string', images: [ { - containerImage: "string", - fogTypeId: 1 - } + containerImage: 'string', + fogTypeId: 1, + }, ], - publisher: "string", + publisher: 'string', diskRequired: 0, ramRequired: 0, - picture: "string", + picture: 'string', isPublic: true, registryId: 0, inputType: { - infoType: "string", - infoFormat: "string" + infoType: 'string', + infoFormat: 'string', }, outputType: { - infoType: "string", - infoFormat: "string" + infoType: 'string', + infoFormat: 'string', }, - configExample: "string" -}); + configExample: 'string', +}) class Catalog extends BaseCLIHandler { constructor() { - super(); + super() - this.name = constants.CMD_CATALOG; + this.name = constants.CMD_CATALOG this.commandDefinitions = [ { name: 'command', defaultOption: true, - group: [constants.CMD] + group: [constants.CMD], }, { name: 'file', alias: 'f', type: String, description: 'Path to catalog item settings JSON file', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'item-id', alias: 'i', type: CliDataTypes.Integer, description: 'Catalog item ID', - group: [constants.CMD_UPDATE, constants.CMD_REMOVE, constants.CMD_INFO] + group: [constants.CMD_UPDATE, constants.CMD_REMOVE, constants.CMD_INFO], }, { name: 'name', alias: 'n', type: String, description: 'Catalog item name', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'description', alias: 'd', type: String, description: 'Catalog item description', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'category', alias: 'c', type: String, description: 'Catalog item category', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'x86-image', alias: 'x', type: String, description: 'x86 docker image name', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'arm-image', alias: 'a', type: String, description: 'ARM docker image name', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'publisher', alias: 'p', type: String, description: 'Catalog item publisher name', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'disk-required', alias: 's', type: CliDataTypes.Integer, description: 'Amount of disk required to run the microservice (MB)', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'ram-required', alias: 'r', type: CliDataTypes.Integer, description: 'Amount of RAM required to run the microservice (MB)', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'picture', alias: 't', type: String, description: 'Catalog item picture', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'public', alias: 'P', type: Boolean, description: 'Public catalog item', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'private', alias: 'V', type: Boolean, description: 'Private catalog item', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'registry-id', alias: 'g', type: CliDataTypes.Integer, description: 'Catalog item docker registry ID', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'input-type', alias: 'I', type: String, description: 'Catalog item input type', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'input-format', alias: 'F', type: String, description: 'Catalog item input format', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'output-type', alias: 'O', type: String, description: 'Catalog item output type', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'output-format', alias: 'T', type: String, description: 'Catalog item output format', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'config-example', alias: 'X', type: String, description: 'Catalog item config example', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'user-id', alias: 'u', type: CliDataTypes.Integer, description: 'User\'s id', - group: [constants.CMD_ADD] + group: [constants.CMD_ADD], }, - ]; + ] this.commands = { [constants.CMD_ADD]: 'Add a new catalog item.', [constants.CMD_UPDATE]: 'Update existing catalog item.', @@ -154,34 +154,34 @@ class Catalog extends BaseCLIHandler { async run(args) { try { - const catalogCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}); + const catalogCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}) - const command = catalogCommand.command.command; + const command = catalogCommand.command.command - this.validateParameters(command, this.commandDefinitions, args.argv); + this.validateParameters(command, this.commandDefinitions, args.argv) switch (command) { case constants.CMD_ADD: - await _executeCase(catalogCommand, constants.CMD_ADD, _createCatalogItem, true); - break; + await _executeCase(catalogCommand, constants.CMD_ADD, _createCatalogItem, true) + break case constants.CMD_UPDATE: - await _executeCase(catalogCommand, constants.CMD_UPDATE, _updateCatalogItem, false); - break; + await _executeCase(catalogCommand, constants.CMD_UPDATE, _updateCatalogItem, false) + break case constants.CMD_REMOVE: - await _executeCase(catalogCommand, constants.CMD_REMOVE, _deleteCatalogItem, false); - break; + await _executeCase(catalogCommand, constants.CMD_REMOVE, _deleteCatalogItem, false) + break case constants.CMD_LIST: - await _executeCase(catalogCommand, constants.CMD_LIST, _listCatalogItems, false); - break; + await _executeCase(catalogCommand, constants.CMD_LIST, _listCatalogItems, false) + break case constants.CMD_INFO: - await _executeCase(catalogCommand, constants.CMD_INFO, _getCatalogItem, false); - break; + await _executeCase(catalogCommand, constants.CMD_INFO, _getCatalogItem, false) + break case constants.CMD_HELP: default: return this.help() } } catch (error) { - this.handleCLIError(error, args.argv); + this.handleCLIError(error, args.argv) } } @@ -192,72 +192,72 @@ class Catalog extends BaseCLIHandler { content: [ JSON_SCHEMA, ], - raw: true + raw: true, }, ]) } } -const _executeCase = async function (catalogCommand, commandName, f, isUserRequired) { +const _executeCase = async function(catalogCommand, commandName, f, isUserRequired) { try { - const item = catalogCommand[commandName]; + const item = catalogCommand[commandName] if (isUserRequired) { - const decoratedFunction = AuthDecorator.prepareUserById(f); - await decoratedFunction(item); + const decoratedFunction = AuthDecorator.prepareUserById(f) + await decoratedFunction(item) } else { - await f(item); + await f(item) } } catch (error) { - logger.error(error.message); + logger.error(error.message) } -}; +} -const _createCatalogItem = async function (obj, user) { +const _createCatalogItem = async function(obj, user) { const item = obj.file ? JSON.parse(fs.readFileSync(obj.file, 'utf8')) - : _createCatalogItemObject(obj); + : _createCatalogItemObject(obj) - logger.cliReq('catalog add', {args: item}); - const catalogItemIdObject = await CatalogItemService.createCatalogItem(item, user); + logger.cliReq('catalog add', {args: item}) + const catalogItemIdObject = await CatalogItemService.createCatalogItem(item, user) logger.cliRes(JSON.stringify({ - id: catalogItemIdObject.id - }, null, 2)); -}; + id: catalogItemIdObject.id, + }, null, 2)) +} -const _updateCatalogItem = async function (obj) { +const _updateCatalogItem = async function(obj) { const item = obj.file ? JSON.parse(fs.readFileSync(obj.file, 'utf8')) - : _createCatalogItemObject(obj); + : _createCatalogItemObject(obj) if (obj.itemId === undefined) { - throw new Errors.NotFoundError(ErrorMessages.CATALOG_UPDATE_REQUIRES_ID); + throw new Errors.NotFoundError(ErrorMessages.CATALOG_UPDATE_REQUIRES_ID) } - logger.cliReq('catalog update', {args: item}); - await CatalogItemService.updateCatalogItem(obj.itemId, item, {}, true); - logger.cliRes('Catalog item has been updated successfully.'); -}; + logger.cliReq('catalog update', {args: item}) + await CatalogItemService.updateCatalogItem(obj.itemId, item, {}, true) + logger.cliRes('Catalog item has been updated successfully.') +} -const _deleteCatalogItem = async function (obj) { - logger.cliReq('catalog remove', {args: {itemId: obj.itemId}}); - await CatalogItemService.deleteCatalogItem(obj.itemId, {}, true); - logger.cliRes('Catalog item has been removed successfully'); -}; +const _deleteCatalogItem = async function(obj) { + logger.cliReq('catalog remove', {args: {itemId: obj.itemId}}) + await CatalogItemService.deleteCatalogItem(obj.itemId, {}, true) + logger.cliRes('Catalog item has been removed successfully') +} -const _listCatalogItems = async function () { - logger.cliReq('catalog list'); - const result = await CatalogItemService.listCatalogItems({}, true); - logger.cliRes(JSON.stringify(result, null, 2)); -}; +const _listCatalogItems = async function() { + logger.cliReq('catalog list') + const result = await CatalogItemService.listCatalogItems({}, true) + logger.cliRes(JSON.stringify(result, null, 2)) +} -const _getCatalogItem = async function (obj) { - logger.cliReq('catalog info', {args: {itemId: obj.itemId}}); - const result = await CatalogItemService.getCatalogItem(obj.itemId, {}, true); - logger.cliRes(JSON.stringify(result, null, 2)); -}; +const _getCatalogItem = async function(obj) { + logger.cliReq('catalog info', {args: {itemId: obj.itemId}}) + const result = await CatalogItemService.getCatalogItem(obj.itemId, {}, true) + logger.cliRes(JSON.stringify(result, null, 2)) +} -const _createCatalogItemObject = function (catalogItem) { +const _createCatalogItemObject = function(catalogItem) { const catalogItemObj = { name: catalogItem.name, description: catalogItem.description, @@ -269,41 +269,41 @@ const _createCatalogItemObject = function (catalogItem) { picture: catalogItem.picture, isPublic: AppHelper.validateBooleanCliOptions(catalogItem.public, catalogItem.private), registryId: catalogItem.registryId, - images: [] - }; + images: [], + } if (catalogItem.x86Image) { catalogItemObj.images.push( - { - containerImage: catalogItem.x86Image, - fogTypeId: 1 - } - ); + { + containerImage: catalogItem.x86Image, + fogTypeId: 1, + } + ) } if (catalogItem.armImage) { catalogItemObj.images.push( - { - containerImage: catalogItem.armImage, - fogTypeId: 2 - } - ); + { + containerImage: catalogItem.armImage, + fogTypeId: 2, + } + ) } if (catalogItem.inputType) { catalogItemObj.inputType = { infoType: catalogItem.inputType, - infoFormat: catalogItem.inputFormat - }; + infoFormat: catalogItem.inputFormat, + } } if (catalogItem.outputType) { catalogItemObj.outputType = { infoType: catalogItem.outputType, - infoFormat: catalogItem.outputFormat - }; + infoFormat: catalogItem.outputFormat, + } } - return AppHelper.deleteUndefinedFields(catalogItemObj); -}; + return AppHelper.deleteUndefinedFields(catalogItemObj) +} -module.exports = new Catalog(); \ No newline at end of file +module.exports = new Catalog() diff --git a/src/cli/cli-data-types.js b/src/cli/cli-data-types.js index 700c3ecce..821299201 100644 --- a/src/cli/cli-data-types.js +++ b/src/cli/cli-data-types.js @@ -11,21 +11,15 @@ * */ -/** - * @return {number} - */ function Integer(value) { return Number(value) } -/** - * @return {number} - */ function Float(value) { return Number(value) } module.exports = { Integer: Integer, - Float: Float -} \ No newline at end of file + Float: Float, +} diff --git a/src/cli/config.js b/src/cli/config.js index 12dc57408..673d3ceda 100644 --- a/src/cli/config.js +++ b/src/cli/config.js @@ -11,82 +11,82 @@ * */ -const BaseCLIHandler = require('./base-cli-handler'); -const config = require('../config'); -const constants = require('../helpers/constants'); -const AppHelper = require('../helpers/app-helper'); -const ErrorMessages = require('../helpers/error-messages'); -const Validator = require('../schemas'); -const logger = require('../logger'); -const Tracking = require('../tracking'); -const TrackingEventType = require('../enums/tracking-event-type'); -const CliDataTypes = require('./cli-data-types'); +const BaseCLIHandler = require('./base-cli-handler') +const config = require('../config') +const constants = require('../helpers/constants') +const AppHelper = require('../helpers/app-helper') +const ErrorMessages = require('../helpers/error-messages') +const Validator = require('../schemas') +const logger = require('../logger') +const Tracking = require('../tracking') +const TrackingEventType = require('../enums/tracking-event-type') +const CliDataTypes = require('./cli-data-types') class Config extends BaseCLIHandler { constructor() { - super(); + super() - this.name = constants.CMD_CONFIG; + this.name = constants.CMD_CONFIG this.commandDefinitions = [ { name: 'command', defaultOption: true, - group: constants.CMD + group: constants.CMD, }, { name: 'port', alias: 'p', type: CliDataTypes.Integer, description: 'Port', - group: constants.CMD_ADD + group: constants.CMD_ADD, }, { name: 'ssl-cert', alias: 'c', type: String, description: 'Path to SSL certificate file', - group: constants.CMD_ADD + group: constants.CMD_ADD, }, { name: 'ssl-key', alias: 'k', type: String, description: 'Path to SSL key file', - group: constants.CMD_ADD + group: constants.CMD_ADD, }, { name: 'intermediate-cert', alias: 'i', type: String, description: 'Path to SSL intermediate certificate file', - group: constants.CMD_ADD + group: constants.CMD_ADD, }, { name: 'home-url', alias: 'h', type: String, description: 'Home page url for email activation links', - group: constants.CMD_ADD + group: constants.CMD_ADD, }, { name: 'email-address', alias: 'a', type: String, description: 'Email address to send activations from', - group: constants.CMD_ADD + group: constants.CMD_ADD, }, { name: 'email-password', alias: 'w', type: String, description: 'Email password to send activations from', - group: constants.CMD_ADD + group: constants.CMD_ADD, }, { name: 'email-service', alias: 's', type: String, description: 'Email service to send activations', - group: constants.CMD_ADD + group: constants.CMD_ADD, }, { name: 'log-dir', alias: 'd', type: String, description: 'Path to log files directory', - group: constants.CMD_ADD + group: constants.CMD_ADD, }, { name: 'log-size', alias: 'z', type: CliDataTypes.Integer, - description: 'Log files size (MB)', group: constants.CMD_ADD + description: 'Log files size (MB)', group: constants.CMD_ADD, }, { name: 'on', alias: 'o', type: Boolean, description: 'Enable', - group: [constants.CMD_DEV_MODE, constants.CMD_EMAIL_ACTIVATION] + group: [constants.CMD_DEV_MODE, constants.CMD_EMAIL_ACTIVATION], }, { name: 'off', alias: 'f', type: Boolean, description: 'Disable', - group: [constants.CMD_DEV_MODE, constants.CMD_EMAIL_ACTIVATION] + group: [constants.CMD_DEV_MODE, constants.CMD_EMAIL_ACTIVATION], }, - ]; + ] this.commands = { [constants.CMD_ADD]: 'Add a new config value.', [constants.CMD_LIST]: 'Display current config.', @@ -97,134 +97,134 @@ class Config extends BaseCLIHandler { async run(args) { try { - const configCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}); + const configCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}) - const command = configCommand.command.command; + const command = configCommand.command.command - this.validateParameters(command, this.commandDefinitions, args.argv); + this.validateParameters(command, this.commandDefinitions, args.argv) switch (command) { case constants.CMD_ADD: - await _executeCase(configCommand, constants.CMD_ADD, _addConfigOption); - break; + await _executeCase(configCommand, constants.CMD_ADD, _addConfigOption) + break case constants.CMD_LIST: - await _executeCase(configCommand, constants.CMD_LIST, _listConfigOptions); - break; + await _executeCase(configCommand, constants.CMD_LIST, _listConfigOptions) + break case constants.CMD_DEV_MODE: - await _executeCase(configCommand, constants.CMD_DEV_MODE, _changeDevModeState); - break; + await _executeCase(configCommand, constants.CMD_DEV_MODE, _changeDevModeState) + break case constants.CMD_EMAIL_ACTIVATION: - await _executeCase(configCommand, constants.CMD_EMAIL_ACTIVATION, _changeEmailActivationState); - break; + await _executeCase(configCommand, constants.CMD_EMAIL_ACTIVATION, _changeEmailActivationState) + break case constants.CMD_HELP: default: return this.help([], true, false) } } catch (error) { - this.handleCLIError(error, args.argv); + this.handleCLIError(error, args.argv) } } } -const _executeCase = async function (catalogCommand, commandName, f) { +const _executeCase = async function(catalogCommand, commandName, f) { try { - const item = catalogCommand[commandName]; - await f(item); + const item = catalogCommand[commandName] + await f(item) } catch (error) { - logger.error(error.message); + logger.error(error.message) } -}; +} -const _addConfigOption = async function (options) { - await Validator.validate(options, Validator.schemas.configUpdate); +const _addConfigOption = async function(options) { + await Validator.validate(options, Validator.schemas.configUpdate) await updateConfig(options.port, 'port', 'Server:Port', async (onSuccess) => { - const port = options.port; - const status = await AppHelper.checkPortAvailability(port); + const port = options.port + const status = await AppHelper.checkPortAvailability(port) if (status === 'closed') { - config.set('Server:Port', port); - onSuccess(); + config.set('Server:Port', port) + onSuccess() } else { - logger.error(AppHelper.formatMessage(ErrorMessages.PORT_NOT_AVAILABLE, port)); + logger.error(AppHelper.formatMessage(ErrorMessages.PORT_NOT_AVAILABLE, port)) } - }); + }) await updateConfig(options.sslCert, 'ssl-cert', 'Server:SslCert', (onSuccess) => { - const sslCert = options.sslCert; + const sslCert = options.sslCert if (!AppHelper.isFileExists(sslCert)) { - logger.error(ErrorMessages.INVALID_FILE_PATH); - return; + logger.error(ErrorMessages.INVALID_FILE_PATH) + return } - config.set('Server:SslCert', sslCert); - onSuccess(); - }); + config.set('Server:SslCert', sslCert) + onSuccess() + }) await updateConfig(options.sslKey, 'ssl-key', 'Server:SslKey', (onSuccess) => { - const sslKey = options.sslKey; + const sslKey = options.sslKey if (!AppHelper.isFileExists(sslKey)) { - logger.error(ErrorMessages.INVALID_FILE_PATH); - return; + logger.error(ErrorMessages.INVALID_FILE_PATH) + return } - config.set('Server:SslKey', sslKey); - onSuccess(); - }); + config.set('Server:SslKey', sslKey) + onSuccess() + }) await updateConfig(options.intermediateCert, 'intermediate-cert', 'Server:IntermediateCert', (onSuccess) => { - const intermediateCert = options.intermediateCert; + const intermediateCert = options.intermediateCert if (!AppHelper.isFileExists(intermediateCert)) { - logger.error(ErrorMessages.INVALID_FILE_PATH); - return; + logger.error(ErrorMessages.INVALID_FILE_PATH) + return } - config.set('Server:IntermediateCert', intermediateCert); - onSuccess(); - }); + config.set('Server:IntermediateCert', intermediateCert) + onSuccess() + }) await updateConfig(options.homeUrl, 'home-url', 'Email:HomeUrl', (onSuccess) => { - config.set('Email:HomeUrl', options.homeUrl); - onSuccess(); - }); + config.set('Email:HomeUrl', options.homeUrl) + onSuccess() + }) await updateConfig(options.emailAddress, 'email-address', 'Email:Address', (onSuccess) => { - config.set('Email:Address', options.emailAddress); - onSuccess(); - }); + config.set('Email:Address', options.emailAddress) + onSuccess() + }) if (options.emailPassword) { - config.set('Email:Password', AppHelper.encryptText(options.emailPassword, config.get('Email:Address'))); - logger.cliRes('Config option email-password has been updated.'); + config.set('Email:Password', AppHelper.encryptText(options.emailPassword, config.get('Email:Address'))) + logger.cliRes('Config option email-password has been updated.') } await updateConfig(options.emailService, 'email-service', 'Email:Service', (onSuccess) => { - config.set('Email:Service', options.emailService); - onSuccess(); - }); + config.set('Email:Service', options.emailService) + onSuccess() + }) await updateConfig(options.logDir, 'log-dir', 'Service:LogsDirectory', (onSuccess) => { - config.set('Service:LogsDirectory', options.logDir); - onSuccess(); - }); + config.set('Service:LogsDirectory', options.logDir) + onSuccess() + }) await updateConfig(options.logSize, 'log-size', 'Service:LogsFileSize', (onSuccess) => { - config.set('Service:LogsFileSize', options.logSize * 1024); - onSuccess(); + config.set('Service:LogsFileSize', options.logSize * 1024) + onSuccess() }) -}; +} -const updateConfig = async function (newConfigValue, cliConfigName, configName, fn) { +const updateConfig = async function(newConfigValue, cliConfigName, configName, fn) { if (newConfigValue) { - const oldConfigValue = config.get(configName); + const oldConfigValue = config.get(configName) if (newConfigValue !== oldConfigValue) { - await fn(function () { - const currentConfigValue = config.get(configName); - logger.cliRes(`Config option ${cliConfigName} has been set to ${currentConfigValue}`); - }); + await fn(function() { + const currentConfigValue = config.get(configName) + logger.cliRes(`Config option ${cliConfigName} has been set to ${currentConfigValue}`) + }) } else { - logger.cliRes(`Config option ${cliConfigName} is already set to ${newConfigValue}`); + logger.cliRes(`Config option ${cliConfigName} is already set to ${newConfigValue}`) } } -}; +} -const _listConfigOptions = function () { +const _listConfigOptions = function() { const configuration = { 'Port': config.get('Server:Port'), 'SSL key directory': config.get('Server:SslKey'), @@ -237,30 +237,30 @@ const _listConfigOptions = function () { 'Email service': config.get('Email:Service'), 'Log files directory': config.get('Service:LogsDirectory'), 'Log files size': config.get('Service:LogsFileSize'), - 'Dev mode': config.get('Server:DevMode') - }; + 'Dev mode': config.get('Server:DevMode'), + } const result = Object.keys(configuration) - .filter(key => configuration[key] != null) - .map(key => `${key}: ${configuration[key]}`) - .join('\n'); + .filter((key) => configuration[key] != null) + .map((key) => `${key}: ${configuration[key]}`) + .join('\n') console.log(result) -}; +} -const _changeDevModeState = async function (options) { - const enableDevMode = AppHelper.validateBooleanCliOptions(options.on, options.off); - config.set('Server:DevMode', enableDevMode); - logger.cliRes('Dev mode state updated successfully.'); +const _changeDevModeState = async function(options) { + const enableDevMode = AppHelper.validateBooleanCliOptions(options.on, options.off) + config.set('Server:DevMode', enableDevMode) + logger.cliRes('Dev mode state updated successfully.') - //example of tracking for other config - const event = Tracking.buildEvent(TrackingEventType.CONFIG_CHANGED, `devMode was set to ${enableDevMode}`); - await Tracking.processEvent(event); -}; + // example of tracking for other config + const event = Tracking.buildEvent(TrackingEventType.CONFIG_CHANGED, `devMode was set to ${enableDevMode}`) + await Tracking.processEvent(event) +} -const _changeEmailActivationState = function (options) { - const enableEmailActivation = AppHelper.validateBooleanCliOptions(options.on, options.off); - config.set('Email:ActivationEnabled', enableEmailActivation); +const _changeEmailActivationState = function(options) { + const enableEmailActivation = AppHelper.validateBooleanCliOptions(options.on, options.off) + config.set('Email:ActivationEnabled', enableEmailActivation) logger.cliRes('Email activation state updated successfully.') -}; +} -module.exports = new Config(); \ No newline at end of file +module.exports = new Config() diff --git a/src/cli/connector.js b/src/cli/connector.js index 83b1f2dcd..c13fae624 100644 --- a/src/cli/connector.js +++ b/src/cli/connector.js @@ -12,64 +12,64 @@ */ -const BaseCLIHandler = require('./base-cli-handler'); -const constants = require('../helpers/constants'); -const logger = require('../logger'); -const ConnectorService = require('../services/connector-service'); -const AppHelper = require('../helpers/app-helper'); -const CliDecorator = require("../decorators/cli-decorator"); +const BaseCLIHandler = require('./base-cli-handler') +const constants = require('../helpers/constants') +const logger = require('../logger') +const ConnectorService = require('../services/connector-service') +const AppHelper = require('../helpers/app-helper') +const CliDecorator = require('../decorators/cli-decorator') class Connector extends BaseCLIHandler { constructor() { - super(); + super() - this.name = constants.CMD_CONNECTOR; + this.name = constants.CMD_CONNECTOR this.commandDefinitions = [ { name: 'command', defaultOption: true, - group: [constants.CMD] + group: [constants.CMD], }, { name: 'name', alias: 'n', type: String, description: 'Connector name', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'domain', alias: 'd', type: String, description: 'Connector domain name', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'public-ip', alias: 'i', type: String, description: 'Connector public IP address', - group: [constants.CMD_ADD, constants.CMD_UPDATE, constants.CMD_REMOVE] + group: [constants.CMD_ADD, constants.CMD_UPDATE, constants.CMD_REMOVE], }, { name: 'cert', alias: 'c', type: String, description: 'Path to certificate file', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'self-signed-on', alias: 'S', type: Boolean, description: 'Switch on self-signed enabled', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'self-signed-off', alias: 's', type: Boolean, description: 'Switch off self-signed disabled', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'dev-mode-on', alias: 'H', type: Boolean, description: 'Switch on dev mode', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'dev-mode-off', alias: 'h', type: Boolean, description: 'Switch off dev mode', - group: [constants.CMD_ADD, constants.CMD_UPDATE] - } - ]; + group: [constants.CMD_ADD, constants.CMD_UPDATE], + }, + ] this.commands = { [constants.CMD_ADD]: 'Add a new Connector.', [constants.CMD_UPDATE]: 'Update existing Connector.', @@ -80,88 +80,87 @@ class Connector extends BaseCLIHandler { async run(args) { try { - const connectorCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}); + const connectorCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}) - const command = connectorCommand.command.command; + const command = connectorCommand.command.command - this.validateParameters(command, this.commandDefinitions, args.argv); + this.validateParameters(command, this.commandDefinitions, args.argv) switch (command) { case constants.CMD_ADD: - await _executeCase(connectorCommand, constants.CMD_ADD, _createConnector, false); - break; + await _executeCase(connectorCommand, constants.CMD_ADD, _createConnector, false) + break case constants.CMD_UPDATE: - await _executeCase(connectorCommand, constants.CMD_UPDATE, _updateConnector, false); - break; + await _executeCase(connectorCommand, constants.CMD_UPDATE, _updateConnector, false) + break case constants.CMD_REMOVE: - await _executeCase(connectorCommand, constants.CMD_REMOVE, _deleteConnector, false); - break; + await _executeCase(connectorCommand, constants.CMD_REMOVE, _deleteConnector, false) + break case constants.CMD_LIST: - await _executeCase(connectorCommand, constants.CMD_LIST, _getConnectorList, false); - break; + await _executeCase(connectorCommand, constants.CMD_LIST, _getConnectorList, false) + break case constants.CMD_HELP: default: return this.help([]) } } catch (error) { - this.handleCLIError(error, args.argv); + this.handleCLIError(error, args.argv) } } - } async function _executeCase(commands, commandName, f, isUserRequired) { try { - const obj = commands[commandName]; + const obj = commands[commandName] if (isUserRequired) { - const decoratedFunction = CliDecorator.prepareUserById(f); - await decoratedFunction(obj); + const decoratedFunction = CliDecorator.prepareUserById(f) + await decoratedFunction(obj) } else { - await f(obj); + await f(obj) } } catch (error) { - logger.error(error.message); + logger.error(error.message) } } async function _createConnector(obj) { - const connector = _createConnectorObject(obj); - logger.cliReq('connector add', {args: connector}); + const connector = _createConnectorObject(obj) + logger.cliReq('connector add', {args: connector}) try { - await ConnectorService.createConnector(connector); - logger.cliRes('Connector has been created successfully.'); + await ConnectorService.createConnector(connector) + logger.cliRes('Connector has been created successfully.') } catch (e) { logger.error(e.message) } } async function _updateConnector(obj) { - const connector = _createConnectorObject(obj); - logger.cliReq('connector update', {args: connector}); + const connector = _createConnectorObject(obj) + logger.cliReq('connector update', {args: connector}) try { - await ConnectorService.updateConnector(connector); - logger.cliRes('Connector has been updated successfully.'); + await ConnectorService.updateConnector(connector) + logger.cliRes('Connector has been updated successfully.') } catch (e) { logger.error(e.message) } } async function _deleteConnector(obj) { - const connector = _createConnectorObject(obj); - logger.cliReq('connector remove', {args: connector}); + const connector = _createConnectorObject(obj) + logger.cliReq('connector remove', {args: connector}) try { - await ConnectorService.deleteConnector(connector); - logger.cliRes('Connector has been removed successfully.'); + await ConnectorService.deleteConnector(connector) + logger.cliRes('Connector has been removed successfully.') } catch (e) { logger.error(e.message) } } async function _getConnectorList() { - logger.cliReq('connector list'); - const list = await ConnectorService.getConnectorList(); - logger.cliRes(JSON.stringify(list, null, 2)); + logger.cliReq('connector list') + const list = await ConnectorService.getConnectorList() + logger.cliRes(JSON.stringify(list, null, 2)) } function _createConnectorObject(cliData) { @@ -171,10 +170,10 @@ function _createConnectorObject(cliData) { publicIp: cliData.publicIp, cert: cliData.cert, isSelfSignedCert: AppHelper.validateBooleanCliOptions(cliData.selfSignedOn, cliData.selfSignedOff), - devMode: AppHelper.validateBooleanCliOptions(cliData.devModeOn, cliData.devModeOff) - }; + devMode: AppHelper.validateBooleanCliOptions(cliData.devModeOn, cliData.devModeOff), + } - return AppHelper.deleteUndefinedFields(connectorObj); + return AppHelper.deleteUndefinedFields(connectorObj) } -module.exports = new Connector(); \ No newline at end of file +module.exports = new Connector() diff --git a/src/cli/controller.js b/src/cli/controller.js index dda25a068..2d4750be9 100644 --- a/src/cli/controller.js +++ b/src/cli/controller.js @@ -11,27 +11,25 @@ * */ -const BaseCLIHandler = require('./base-cli-handler'); -const constants = require('../helpers/constants'); -const ControllerService = require('../services/controller-service'); -const logger = require('../logger'); -const AppHelper = require('../helpers/app-helper'); - +const BaseCLIHandler = require('./base-cli-handler') +const constants = require('../helpers/constants') +const ControllerService = require('../services/controller-service') +const logger = require('../logger') class Controller extends BaseCLIHandler { constructor() { - super(); + super() - this.name = constants.CMD_CONTROLLER; + this.name = constants.CMD_CONTROLLER this.commandDefinitions = [ { name: 'command', defaultOption: true, description: 'status, email-activation, fog-types, version', - group: constants.CMD - } - ]; + group: constants.CMD, + }, + ] this.commands = { [constants.CMD_STATUS]: 'Display iofog-controller service status.', [constants.CMD_EMAIL_ACTIVATION]: 'Is email activation.', @@ -42,73 +40,72 @@ class Controller extends BaseCLIHandler { async run(args) { try { - const controllerCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}); + const controllerCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}) - const command = controllerCommand.command.command; + const command = controllerCommand.command.command - this.validateParameters(command, this.commandDefinitions, args.argv); + this.validateParameters(command, this.commandDefinitions, args.argv) switch (command) { case constants.CMD_STATUS: - await _executeCase(controllerCommand, constants.CMD_STATUS, _getStatus, false); - break; + await _executeCase(controllerCommand, constants.CMD_STATUS, _getStatus, false) + break case constants.CMD_EMAIL_ACTIVATION: - await _executeCase(controllerCommand, constants.CMD_EMAIL_ACTIVATION, _emailActivation, false); - break; + await _executeCase(controllerCommand, constants.CMD_EMAIL_ACTIVATION, _emailActivation, false) + break case constants.CMD_FOG_TYPES: - await _executeCase(controllerCommand, constants.CMD_FOG_TYPES, _getFogTypes, false); - break; + await _executeCase(controllerCommand, constants.CMD_FOG_TYPES, _getFogTypes, false) + break case constants.CMD_VERSION: - await _executeCase(controllerCommand, constants.CMD_VERSION, _getVersion, false); - break; + await _executeCase(controllerCommand, constants.CMD_VERSION, _getVersion, false) + break case constants.CMD_HELP: default: return this.help([]) } } catch (error) { - this.handleCLIError(error, args.argv); + this.handleCLIError(error, args.argv) } } - } -const _executeCase = async function (userCommand, commandName, f, isUserRequired) { +const _executeCase = async function(userCommand, commandName, f, isUserRequired) { try { - const item = userCommand[commandName]; + const item = userCommand[commandName] if (isUserRequired) { - const decoratedFunction = AuthDecorator.prepareUserByEmail(f); - await decoratedFunction(item); + const decoratedFunction = AuthDecorator.prepareUserByEmail(f) + await decoratedFunction(item) } else { - await f(item); + await f(item) } } catch (error) { - logger.error(error.message); + logger.error(error.message) } -}; +} -const _getStatus = async function () { - const response = await ControllerService.statusController(true); - logger.cliRes(JSON.stringify(response, null, 2)); -}; +const _getStatus = async function() { + const response = await ControllerService.statusController(true) + logger.cliRes(JSON.stringify(response, null, 2)) +} -const _emailActivation = async function () { - logger.cliReq('controller email-activation'); - const response = await ControllerService.emailActivation(true); - logger.cliRes(JSON.stringify(response, null, 2)); -}; +const _emailActivation = async function() { + logger.cliReq('controller email-activation') + const response = await ControllerService.emailActivation(true) + logger.cliRes(JSON.stringify(response, null, 2)) +} -const _getFogTypes = async function () { - logger.cliReq('controller fog-types'); - const response = await ControllerService.getFogTypes(true); - logger.cliRes(JSON.stringify(response, null, 2)); -}; +const _getFogTypes = async function() { + logger.cliReq('controller fog-types') + const response = await ControllerService.getFogTypes(true) + logger.cliRes(JSON.stringify(response, null, 2)) +} -const _getVersion = async function () { - logger.cliReq('controller version'); - const response = await ControllerService.getVersion(true); - logger.cliRes(response, null, 2); -}; +const _getVersion = async function() { + logger.cliReq('controller version') + const response = await ControllerService.getVersion(true) + logger.cliRes(response, null, 2) +} -module.exports = new Controller(); \ No newline at end of file +module.exports = new Controller() diff --git a/src/cli/diagnostics.js b/src/cli/diagnostics.js index 62b08001d..a146907fa 100644 --- a/src/cli/diagnostics.js +++ b/src/cli/diagnostics.js @@ -11,20 +11,20 @@ * */ -const BaseCLIHandler = require('./base-cli-handler'); -const constants = require('../helpers/constants'); -const logger = require('../logger'); -const DiagnosticService = require('../services/diagnostic-service'); -const AppHelper = require('../helpers/app-helper'); -const AuthDecorator = require('../decorators/cli-decorator'); -const CliDataTypes = require('./cli-data-types'); +const BaseCLIHandler = require('./base-cli-handler') +const constants = require('../helpers/constants') +const logger = require('../logger') +const DiagnosticService = require('../services/diagnostic-service') +const AppHelper = require('../helpers/app-helper') +const AuthDecorator = require('../decorators/cli-decorator') +const CliDataTypes = require('./cli-data-types') class Diagnostics extends BaseCLIHandler { constructor() { - super(); + super() - this.name = constants.CMD_DIAGNOSTICS; + this.name = constants.CMD_DIAGNOSTICS this.commandDefinitions = [ { name: 'command', defaultOption: true, @@ -32,42 +32,42 @@ class Diagnostics extends BaseCLIHandler { }, { name: 'enable', alias: 'e', type: Boolean, description: 'Enable microservice strace', - group: [constants.CMD_STRACE_UPDATE] + group: [constants.CMD_STRACE_UPDATE], }, { name: 'disable', alias: 'o', type: Boolean, description: 'Disable microservice strace', - group: [constants.CMD_STRACE_UPDATE] + group: [constants.CMD_STRACE_UPDATE], }, { name: 'microservice-uuid', alias: 'i', type: String, description: 'Microservice UUID', group: [constants.CMD_STRACE_UPDATE, constants.CMD_STRACE_INFO, constants.CMD_STRACE_FTP_POST, - constants.CMD_IMAGE_SNAPSHOT_CREATE, constants.CMD_IMAGE_SNAPSHOT_GET] + constants.CMD_IMAGE_SNAPSHOT_CREATE, constants.CMD_IMAGE_SNAPSHOT_GET], }, { name: 'format', alias: 'f', type: String, description: 'Format of strace data to receive. Possible values: string, file', - group: [constants.CMD_STRACE_INFO] + group: [constants.CMD_STRACE_INFO], }, { name: 'ftpHost', alias: 'h', type: String, description: 'FTP host', - group: [constants.CMD_STRACE_FTP_POST] + group: [constants.CMD_STRACE_FTP_POST], }, { name: 'ftpPort', alias: 'p', type: CliDataTypes.Integer, description: 'FTP port', - group: [constants.CMD_STRACE_FTP_POST] + group: [constants.CMD_STRACE_FTP_POST], }, { name: 'ftpUser', alias: 'u', type: String, description: 'FTP user', - group: [constants.CMD_STRACE_FTP_POST] + group: [constants.CMD_STRACE_FTP_POST], }, { name: 'ftpPass', alias: 's', type: String, description: 'FTP user password', - group: [constants.CMD_STRACE_FTP_POST] + group: [constants.CMD_STRACE_FTP_POST], }, { name: 'ftpDestDir', alias: 'd', type: String, description: 'FTP destination directory', - group: [constants.CMD_STRACE_FTP_POST] + group: [constants.CMD_STRACE_FTP_POST], }, - ]; + ] this.commands = { [constants.CMD_STRACE_UPDATE]: 'Change microservice strace status to enabled or disabled.', [constants.CMD_STRACE_INFO]: 'Get microservice strace data.', @@ -79,86 +79,86 @@ class Diagnostics extends BaseCLIHandler { async run(args) { try { - const diagnosticCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}); + const diagnosticCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}) - const command = diagnosticCommand.command.command; + const command = diagnosticCommand.command.command - this.validateParameters(command, this.commandDefinitions, args.argv); + this.validateParameters(command, this.commandDefinitions, args.argv) switch (command) { case constants.CMD_STRACE_UPDATE: - await _executeCase(diagnosticCommand, constants.CMD_STRACE_UPDATE, _changeMicroserviceStraceState, false); - break; + await _executeCase(diagnosticCommand, constants.CMD_STRACE_UPDATE, _changeMicroserviceStraceState, false) + break case constants.CMD_STRACE_INFO: - await _executeCase(diagnosticCommand, constants.CMD_STRACE_INFO, _getMicroserviceStraceData, false); - break; + await _executeCase(diagnosticCommand, constants.CMD_STRACE_INFO, _getMicroserviceStraceData, false) + break case constants.CMD_STRACE_FTP_POST: - await _executeCase(diagnosticCommand, constants.CMD_STRACE_FTP_POST, _postMicroserviceStraceDataToFtp, false); - break; + await _executeCase(diagnosticCommand, constants.CMD_STRACE_FTP_POST, _postMicroserviceStraceDataToFtp, false) + break case constants.CMD_IMAGE_SNAPSHOT_CREATE: - await _executeCase(diagnosticCommand, constants.CMD_IMAGE_SNAPSHOT_CREATE, _postMicroserviceImageSnapshotCreate, false); - break; + await _executeCase(diagnosticCommand, constants.CMD_IMAGE_SNAPSHOT_CREATE, _postMicroserviceImageSnapshotCreate, false) + break case constants.CMD_IMAGE_SNAPSHOT_GET: - await _executeCase(diagnosticCommand, constants.CMD_IMAGE_SNAPSHOT_GET, _getMicroserviceImageSnapshot, false); - break; + await _executeCase(diagnosticCommand, constants.CMD_IMAGE_SNAPSHOT_GET, _getMicroserviceImageSnapshot, false) + break case constants.CMD_HELP: default: return this.help([]) } } catch (error) { - this.handleCLIError(error, args.argv); + this.handleCLIError(error, args.argv) } } } -const _executeCase = async function (diagnosticCommand, commandName, f, isUserRequired) { +const _executeCase = async function(diagnosticCommand, commandName, f, isUserRequired) { try { - const item = diagnosticCommand[commandName]; + const item = diagnosticCommand[commandName] if (isUserRequired) { - const decoratedFunction = AuthDecorator.prepareUserById(f); - await decoratedFunction(item); + const decoratedFunction = AuthDecorator.prepareUserById(f) + await decoratedFunction(item) } else { - await f(item); + await f(item) } } catch (error) { - logger.error(error.message); + logger.error(error.message) } -}; - -const _changeMicroserviceStraceState = async function (obj) { - const isEnable = AppHelper.validateBooleanCliOptions(obj.enable, obj.disable); - logger.cliReq('diagnostics strace-update', {args: {isEnable: isEnable}}); - await DiagnosticService.changeMicroserviceStraceState(obj.microserviceUuid, {enable: isEnable}, {}, true); - const msg = isEnable ? 'Microservice strace has been enabled' : 'Microservice strace has been disabled'; - logger.cliRes(msg); -}; - -const _getMicroserviceStraceData = async function (obj) { - logger.cliReq('diagnostics strace-info', {args: obj}); - const result = await DiagnosticService.getMicroserviceStraceData(obj.microserviceUuid, {format: obj.format}, {}, true); - logger.cliRes('Strace data:'); - logger.cliRes('============================='); - logger.cliRes(result.data); - logger.cliRes('Microservice strace data has been retrieved successfully.'); -}; - -const _postMicroserviceStraceDataToFtp = async function (obj) { - logger.cliReq('diagnostics strace-ftp-post', {args: obj}); - await DiagnosticService.postMicroserviceStraceDatatoFtp(obj.microserviceUuid, obj, {}, true); - logger.cliRes('Strace data has been posted to FTP successfully.'); -}; - -const _postMicroserviceImageSnapshotCreate = async function (obj) { - logger.cliReq('diagnostics image-snapshot-create'); - await DiagnosticService.postMicroserviceImageSnapshotCreate(obj.microserviceUuid, {}, true); - logger.cliRes('Microservice image snapshot has been created successfully.'); -}; - -const _getMicroserviceImageSnapshot = async function (obj) { - logger.cliReq('diagnostics image-snapshot-get'); - const filePath = await DiagnosticService.getMicroserviceImageSnapshot(obj.microserviceUuid, {}, true); - logger.cliRes('Microservice images path = ' + filePath); -}; - -module.exports = new Diagnostics(); \ No newline at end of file +} + +const _changeMicroserviceStraceState = async function(obj) { + const isEnable = AppHelper.validateBooleanCliOptions(obj.enable, obj.disable) + logger.cliReq('diagnostics strace-update', {args: {isEnable: isEnable}}) + await DiagnosticService.changeMicroserviceStraceState(obj.microserviceUuid, {enable: isEnable}, {}, true) + const msg = isEnable ? 'Microservice strace has been enabled' : 'Microservice strace has been disabled' + logger.cliRes(msg) +} + +const _getMicroserviceStraceData = async function(obj) { + logger.cliReq('diagnostics strace-info', {args: obj}) + const result = await DiagnosticService.getMicroserviceStraceData(obj.microserviceUuid, {format: obj.format}, {}, true) + logger.cliRes('Strace data:') + logger.cliRes('=============================') + logger.cliRes(result.data) + logger.cliRes('Microservice strace data has been retrieved successfully.') +} + +const _postMicroserviceStraceDataToFtp = async function(obj) { + logger.cliReq('diagnostics strace-ftp-post', {args: obj}) + await DiagnosticService.postMicroserviceStraceDatatoFtp(obj.microserviceUuid, obj, {}, true) + logger.cliRes('Strace data has been posted to FTP successfully.') +} + +const _postMicroserviceImageSnapshotCreate = async function(obj) { + logger.cliReq('diagnostics image-snapshot-create') + await DiagnosticService.postMicroserviceImageSnapshotCreate(obj.microserviceUuid, {}, true) + logger.cliRes('Microservice image snapshot has been created successfully.') +} + +const _getMicroserviceImageSnapshot = async function(obj) { + logger.cliReq('diagnostics image-snapshot-get') + const filePath = await DiagnosticService.getMicroserviceImageSnapshot(obj.microserviceUuid, {}, true) + logger.cliRes('Microservice images path = ' + filePath) +} + +module.exports = new Diagnostics() diff --git a/src/cli/flow.js b/src/cli/flow.js index 99bcfcbba..70227a2de 100644 --- a/src/cli/flow.js +++ b/src/cli/flow.js @@ -11,67 +11,67 @@ * */ -const BaseCLIHandler = require('./base-cli-handler'); -const constants = require('../helpers/constants'); -const AuthDecorator = require('../decorators/cli-decorator'); -const FlowService = require('../services/flow-service'); -const AppHelper = require('../helpers/app-helper'); -const logger = require('../logger'); -const fs = require('fs'); -const CliDataTypes = require('./cli-data-types'); +const BaseCLIHandler = require('./base-cli-handler') +const constants = require('../helpers/constants') +const AuthDecorator = require('../decorators/cli-decorator') +const FlowService = require('../services/flow-service') +const AppHelper = require('../helpers/app-helper') +const logger = require('../logger') +const fs = require('fs') +const CliDataTypes = require('./cli-data-types') const JSON_SCHEMA = AppHelper.stringifyCliJsonSchema({ - name: "string", - description: "string", - isActivated: true -}); + name: 'string', + description: 'string', + isActivated: true, +}) class Flow extends BaseCLIHandler { constructor() { - super(); + super() - this.name = constants.CMD_FLOW; + this.name = constants.CMD_FLOW this.commandDefinitions = [ { name: 'command', defaultOption: true, - group: [constants.CMD] + group: [constants.CMD], }, { name: 'file', alias: 'f', type: String, description: 'Path to application flow settings JSON file', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'flow-id', alias: 'i', type: CliDataTypes.Integer, description: 'Application flow ID', - group: [constants.CMD_UPDATE, constants.CMD_REMOVE, constants.CMD_INFO] + group: [constants.CMD_UPDATE, constants.CMD_REMOVE, constants.CMD_INFO], }, { name: 'name', alias: 'n', type: String, description: 'Application flow name', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'description', alias: 'd', type: String, description: 'Application flow description', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'activate', alias: 'a', type: Boolean, description: 'Activate application flow', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'deactivate', alias: 'D', type: Boolean, description: 'Deactivate application flow', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'user-id', alias: 'u', type: CliDataTypes.Integer, description: 'User\'s id', - group: [constants.CMD_ADD] - } - ]; + group: [constants.CMD_ADD], + }, + ] this.commands = { [constants.CMD_ADD]: 'Add a new flow.', [constants.CMD_UPDATE]: 'Update existing flow.', @@ -83,34 +83,34 @@ class Flow extends BaseCLIHandler { async run(args) { try { - const flowCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}); + const flowCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}) - const command = flowCommand.command.command; + const command = flowCommand.command.command - this.validateParameters(command, this.commandDefinitions, args.argv); + this.validateParameters(command, this.commandDefinitions, args.argv) switch (command) { case constants.CMD_ADD: - await _executeCase(flowCommand, constants.CMD_ADD, _createFlow, true); - break; + await _executeCase(flowCommand, constants.CMD_ADD, _createFlow, true) + break case constants.CMD_UPDATE: - await _executeCase(flowCommand, constants.CMD_UPDATE, _updateFlow, false); - break; + await _executeCase(flowCommand, constants.CMD_UPDATE, _updateFlow, false) + break case constants.CMD_REMOVE: - await _executeCase(flowCommand, constants.CMD_REMOVE, _deleteFlow, false); - break; + await _executeCase(flowCommand, constants.CMD_REMOVE, _deleteFlow, false) + break case constants.CMD_LIST: - await _executeCase(flowCommand, constants.CMD_LIST, _getAllFlows, false); - break; + await _executeCase(flowCommand, constants.CMD_LIST, _getAllFlows, false) + break case constants.CMD_INFO: - await _executeCase(flowCommand, constants.CMD_INFO, _getFlow, false); - break; + await _executeCase(flowCommand, constants.CMD_INFO, _getFlow, false) + break case constants.CMD_HELP: default: return this.help([]) } } catch (error) { - this.handleCLIError(error, args.argv); + this.handleCLIError(error, args.argv) } } @@ -121,78 +121,78 @@ class Flow extends BaseCLIHandler { content: [ JSON_SCHEMA, ], - raw: true + raw: true, }, ]) } } -const _executeCase = async function (flowCommand, commandName, f, isUserRequired) { +const _executeCase = async function(flowCommand, commandName, f, isUserRequired) { try { - const item = flowCommand[commandName]; + const item = flowCommand[commandName] if (isUserRequired) { - const decoratedFunction = AuthDecorator.prepareUserById(f); - await decoratedFunction(item); + const decoratedFunction = AuthDecorator.prepareUserById(f) + await decoratedFunction(item) } else { - await f(item); + await f(item) } } catch (error) { - logger.error(error.message); + logger.error(error.message) } -}; +} -const _createFlow = async function (flowData, user) { +const _createFlow = async function(flowData, user) { const flow = flowData.file ? JSON.parse(fs.readFileSync(flowData.file, 'utf8')) - : _createFlowObject(flowData); - logger.cliReq('flow add', {args: flow}); - const createdFlow = await FlowService.createFlow(flow, user, true); + : _createFlowObject(flowData) + logger.cliReq('flow add', {args: flow}) + const createdFlow = await FlowService.createFlow(flow, user, true) logger.cliRes(JSON.stringify({ - id: createdFlow.id - }, null, 2)); -}; + id: createdFlow.id, + }, null, 2)) +} -const _updateFlow = async function (flowData) { +const _updateFlow = async function(flowData) { const flow = flowData.file ? JSON.parse(fs.readFileSync(flowData.file, 'utf8')) - : _createFlowObject(flowData); - - const flowId = flowData.flowId; - logger.cliReq('flow update', {args: flow}); - await FlowService.updateFlow(flow, flowId, {}, true); - logger.cliRes('Flow updated successfully.'); -}; - -const _deleteFlow = async function (flowData) { - const flowId = flowData.flowId; - logger.cliReq('flow remove', {args: {flowId: flowId}}); - await FlowService.deleteFlow(flowId, {}, true); - logger.cliRes('Flow removed successfully.'); -}; - -const _getAllFlows = async function () { - logger.cliReq('flow list'); - const flows = await FlowService.getAllFlows(true); - logger.cliRes(JSON.stringify(flows, null, 2)); -}; - -const _getFlow = async function (flowData) { - const flowId = flowData.flowId; - logger.cliReq('flow info', {args: {flowId: flowId}}); - const flow = await FlowService.getFlowWithTransaction(flowId, {}, true); - logger.cliRes(JSON.stringify(flow, null, 2)); -}; + : _createFlowObject(flowData) + + const flowId = flowData.flowId + logger.cliReq('flow update', {args: flow}) + await FlowService.updateFlow(flow, flowId, {}, true) + logger.cliRes('Flow updated successfully.') +} + +const _deleteFlow = async function(flowData) { + const flowId = flowData.flowId + logger.cliReq('flow remove', {args: {flowId: flowId}}) + await FlowService.deleteFlow(flowId, {}, true) + logger.cliRes('Flow removed successfully.') +} + +const _getAllFlows = async function() { + logger.cliReq('flow list') + const flows = await FlowService.getAllFlows(true) + logger.cliRes(JSON.stringify(flows, null, 2)) +} + +const _getFlow = async function(flowData) { + const flowId = flowData.flowId + logger.cliReq('flow info', {args: {flowId: flowId}}) + const flow = await FlowService.getFlowWithTransaction(flowId, {}, true) + logger.cliRes(JSON.stringify(flow, null, 2)) +} function _createFlowObject(data) { const flow = { id: data.id, name: data.name, description: data.description, - isActivated: AppHelper.validateBooleanCliOptions(data.activate, data.deactivate) - }; + isActivated: AppHelper.validateBooleanCliOptions(data.activate, data.deactivate), + } - return AppHelper.deleteUndefinedFields(flow); + return AppHelper.deleteUndefinedFields(flow) } -module.exports = new Flow(); \ No newline at end of file +module.exports = new Flow() diff --git a/src/cli/index.js b/src/cli/index.js index 2b43c297f..c54a284d4 100644 --- a/src/cli/index.js +++ b/src/cli/index.js @@ -11,39 +11,39 @@ * */ -const BaseCLIHandler = require('./base-cli-handler'); -const Start = require('./start'); -const User = require('./user'); -const Connector = require('./connector'); -const Config = require('./config'); -const Tunnel = require('./tunnel'); -const IOFog = require('./iofog'); -const Catalog = require('./catalog'); -const Flow = require('./flow'); -const Microservice = require('./microservice'); -const Registry = require('./registry'); -const Controller = require('./controller'); -const Diagnostics = require('./diagnostics'); -const packageJson = require('./../../package'); +const BaseCLIHandler = require('./base-cli-handler') +const Start = require('./start') +const User = require('./user') +const Connector = require('./connector') +const Config = require('./config') +const Tunnel = require('./tunnel') +const IOFog = require('./iofog') +const Catalog = require('./catalog') +const Flow = require('./flow') +const Microservice = require('./microservice') +const Registry = require('./registry') +const Controller = require('./controller') +const Diagnostics = require('./diagnostics') +const packageJson = require('./../../package') -const constants = require('../helpers/constants'); +const constants = require('../helpers/constants') -const Sentry = require('@sentry/node'); -Sentry.init({ dsn: 'https://3213bc0b88db47ffb103075d7e1e254f@sentry.io/1378606' }); -Sentry.configureScope(scope => { - scope.setExtra('version', packageJson.version); -}); +const Sentry = require('@sentry/node') +Sentry.init({dsn: 'https://3213bc0b88db47ffb103075d7e1e254f@sentry.io/1378606'}) +Sentry.configureScope((scope) => { + scope.setExtra('version', packageJson.version) +}) class Cli extends BaseCLIHandler { constructor() { - super(); + super() this.commandDefinitions = [ - { name: 'command', defaultOption: true }, - ]; + {name: 'command', defaultOption: true}, + ] this.commands = { [constants.CMD_START]: 'Start iofog-controller service.', [constants.CMD_STOP]: 'Stop iofog-controller service.', - //init db is hidden command + // init db is hidden command // [constants.CMD_INIT_DB]: 'Init sqlite db for iofog-controller.', [constants.CMD_CONTROLLER]: 'Display iofog-controller service information.', [constants.CMD_HELP]: 'Display usage information.', @@ -61,38 +61,38 @@ class Cli extends BaseCLIHandler { } run(daemon) { - const mainCommand = this.parseCommandLineArgs(this.commandDefinitions); - const argv = mainCommand._unknown || []; + const mainCommand = this.parseCommandLineArgs(this.commandDefinitions) + const argv = mainCommand._unknown || [] switch (mainCommand.command) { case constants.CMD_START: - return Start.run({ daemon }); + return Start.run({daemon}) case constants.CMD_STOP: - return daemon.stop(); + return daemon.stop() case constants.CMD_INIT_DB: - return Start.initDB(); + return Start.initDB() case constants.CMD_CONTROLLER: - return Controller.run({ argv }); + return Controller.run({argv}) case constants.CMD_USER: - return User.run({ argv }); + return User.run({argv}) case constants.CMD_CONFIG: - return Config.run({ argv }); + return Config.run({argv}) case constants.CMD_CONNECTOR: - return Connector.run({ argv }); + return Connector.run({argv}) case constants.CMD_TUNNEL: - return Tunnel.run({ argv }); + return Tunnel.run({argv}) case constants.CMD_IOFOG: - return IOFog.run({ argv }); + return IOFog.run({argv}) case constants.CMD_CATALOG: - return Catalog.run({ argv }); + return Catalog.run({argv}) case constants.CMD_FLOW: - return Flow.run({ argv }); + return Flow.run({argv}) case constants.CMD_MICROSERVICE: - return Microservice.run({ argv }); + return Microservice.run({argv}) case constants.CMD_REGISTRY: - return Registry.run({ argv }); + return Registry.run({argv}) case constants.CMD_DIAGNOSTICS: - return Diagnostics.run({ argv }); + return Diagnostics.run({argv}) case constants.CMD_HELP: default: return this.help([], false) @@ -100,4 +100,4 @@ class Cli extends BaseCLIHandler { } } -module.exports = Cli; \ No newline at end of file +module.exports = Cli diff --git a/src/cli/iofog.js b/src/cli/iofog.js index 287001514..5f56c3129 100644 --- a/src/cli/iofog.js +++ b/src/cli/iofog.js @@ -11,28 +11,28 @@ * */ -const BaseCLIHandler = require('./base-cli-handler'); -const constants = require('../helpers/constants'); -const logger = require('../logger'); -const fs = require('fs'); -const CliDecorator = require('../decorators/cli-decorator'); -const AppHelper = require('../helpers/app-helper'); -const FogService = require('../services/iofog-service'); -const CliDataTypes = require('./cli-data-types'); +const BaseCLIHandler = require('./base-cli-handler') +const constants = require('../helpers/constants') +const logger = require('../logger') +const fs = require('fs') +const CliDecorator = require('../decorators/cli-decorator') +const AppHelper = require('../helpers/app-helper') +const FogService = require('../services/iofog-service') +const CliDataTypes = require('./cli-data-types') const JSON_SCHEMA = AppHelper.stringifyCliJsonSchema({ - name: "string", - location: "string", + name: 'string', + location: 'string', latitude: 0, longitude: 0, - description: "string", - dockerUrl: "string", + description: 'string', + dockerUrl: 'string', diskLimit: 0, - diskDirectory: "string", + diskDirectory: 'string', memoryLimit: 0, cpuLimit: 0, logLimit: 0, - logDirectory: "string", + logDirectory: 'string', logFileCount: 0, statusFrequency: 0, changeFrequency: 0, @@ -40,161 +40,161 @@ const JSON_SCHEMA = AppHelper.stringifyCliJsonSchema({ bluetoothEnabled: false, watchdogEnabled: true, abstractedHardwareEnabled: false, - fogType: 0 -}); + fogType: 0, +}) class IOFog extends BaseCLIHandler { constructor() { - super(); + super() - this.name = constants.CMD_IOFOG; + this.name = constants.CMD_IOFOG this.commandDefinitions = [ { name: 'command', defaultOption: true, - group: [constants.CMD] + group: [constants.CMD], }, { name: 'file', alias: 'f', type: String, description: 'Path to ioFog settings JSON file', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'iofog-uuid', alias: 'i', type: String, description: 'ioFog node UUID', group: [constants.CMD_UPDATE, constants.CMD_REMOVE, constants.CMD_INFO, constants.CMD_PROVISIONING_KEY, - constants.CMD_IOFOG_REBOOT, constants.CMD_VERSION, constants.CMD_HAL_HW, constants.CMD_HAL_USB] + constants.CMD_IOFOG_REBOOT, constants.CMD_VERSION, constants.CMD_HAL_HW, constants.CMD_HAL_USB], }, { name: 'name', alias: 'n', type: String, description: 'ioFog node name', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'location', alias: 'l', type: String, description: 'ioFog node location', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'latitude', alias: 't', type: CliDataTypes.Float, description: 'ioFog node latitude', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'longitude', alias: 'g', type: CliDataTypes.Float, description: 'ioFog node longitude', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'description', alias: 'd', type: String, description: 'ioFog node description', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'docker-url', alias: 'D', type: String, description: 'ioFog node docker url', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'disk-limit', alias: 'M', type: CliDataTypes.Float, description: 'ioFog node disk usage limit (MB)', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'disk-directory', alias: 'T', type: String, description: 'Path to ioFog node disk directory', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'memory-limit', alias: 'm', type: CliDataTypes.Float, description: 'ioFog node memory usage limit (MB)', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'cpu-limit', alias: 'c', type: CliDataTypes.Float, description: 'ioFog node CPU usage limit (%)', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'log-limit', alias: 'G', type: CliDataTypes.Float, description: 'ioFog node log size limit (MB)', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'log-directory', alias: 'Y', type: String, description: 'Path to ioFog node log files directory', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'log-file-count', alias: 'C', type: CliDataTypes.Integer, description: 'ioFog node log files count', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'status-frequency', alias: 's', type: CliDataTypes.Integer, description: 'ioFog node status check frequency (seconds)', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'change-frequency', alias: 'F', type: CliDataTypes.Integer, description: 'ioFog node configuration change check frequency (seconds)', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'device-frequency', alias: 'Q', type: CliDataTypes.Integer, description: 'ioFog node device scan frequency (seconds)', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'bluetooth-enable', alias: 'B', type: Boolean, description: 'Enable bluetooth on ioFog node', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'bluetooth-disable', alias: 'b', type: Boolean, description: 'Disable bluetooth on ioFog node', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'watchdog-enable', alias: 'W', type: Boolean, description: 'Enable watchdog on ioFog node', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'watchdog-disable', alias: 'w', type: Boolean, description: 'Disable watchdog on ioFog node', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'abs-hw-enable', alias: 'A', type: Boolean, description: 'Enable hardware abstraction on ioFog node', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'abs-hw-disable', alias: 'a', type: Boolean, description: 'Disable hardware abstraction on ioFog node', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'reboot', alias: 'o', type: Boolean, description: 'Reboot ioFog node', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'fog-type', alias: 'y', type: CliDataTypes.Integer, description: 'ioFog node architecture type', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'version-command', alias: 'v', type: String, description: 'ioFog version command ', - group: [constants.CMD_VERSION] + group: [constants.CMD_VERSION], }, { name: 'user-id', alias: 'u', type: CliDataTypes.Integer, description: 'User\'s id', - group: [constants.CMD_ADD] - } - ]; + group: [constants.CMD_ADD], + }, + ] this.commands = { [constants.CMD_ADD]: 'Add a new ioFog node.', [constants.CMD_UPDATE]: 'Update existing ioFog node.', @@ -205,55 +205,55 @@ class IOFog extends BaseCLIHandler { [constants.CMD_IOFOG_REBOOT]: 'Reboot ioFog node', [constants.CMD_VERSION]: 'Change agent version of ioFog node', [constants.CMD_HAL_HW]: 'Get HAL Hardware ioFog node data', - [constants.CMD_HAL_USB]: 'Get HAL USB ioFog node data' + [constants.CMD_HAL_USB]: 'Get HAL USB ioFog node data', } } async run(args) { try { - const iofogCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}); + const iofogCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}) - const command = iofogCommand.command.command; + const command = iofogCommand.command.command - this.validateParameters(command, this.commandDefinitions, args.argv); + this.validateParameters(command, this.commandDefinitions, args.argv) switch (command) { case constants.CMD_ADD: - await _executeCase(iofogCommand, constants.CMD_ADD, _createFog, true); - break; + await _executeCase(iofogCommand, constants.CMD_ADD, _createFog, true) + break case constants.CMD_UPDATE: - await _executeCase(iofogCommand, constants.CMD_UPDATE, _updateFog, false); - break; + await _executeCase(iofogCommand, constants.CMD_UPDATE, _updateFog, false) + break case constants.CMD_REMOVE: - await _executeCase(iofogCommand, constants.CMD_REMOVE, _deleteFog, false); - break; + await _executeCase(iofogCommand, constants.CMD_REMOVE, _deleteFog, false) + break case constants.CMD_LIST: - await _executeCase(iofogCommand, constants.CMD_LIST, _getFogList, false); - break; + await _executeCase(iofogCommand, constants.CMD_LIST, _getFogList, false) + break case constants.CMD_INFO: - await _executeCase(iofogCommand, constants.CMD_INFO, _getFog, false); - break; + await _executeCase(iofogCommand, constants.CMD_INFO, _getFog, false) + break case constants.CMD_PROVISIONING_KEY: - await _executeCase(iofogCommand, constants.CMD_PROVISIONING_KEY, _generateProvision, false); - break; + await _executeCase(iofogCommand, constants.CMD_PROVISIONING_KEY, _generateProvision, false) + break case constants.CMD_IOFOG_REBOOT: - await _executeCase(iofogCommand, constants.CMD_IOFOG_REBOOT, _setFogRebootCommand, false); - break; + await _executeCase(iofogCommand, constants.CMD_IOFOG_REBOOT, _setFogRebootCommand, false) + break case constants.CMD_VERSION: - await _executeCase(iofogCommand, constants.CMD_VERSION, _setFogVersionCommand, false); - break; + await _executeCase(iofogCommand, constants.CMD_VERSION, _setFogVersionCommand, false) + break case constants.CMD_HAL_HW: - await _executeCase(iofogCommand, constants.CMD_HAL_HW, _getHalHardwareInfo, false); - break; + await _executeCase(iofogCommand, constants.CMD_HAL_HW, _getHalHardwareInfo, false) + break case constants.CMD_HAL_USB: - await _executeCase(iofogCommand, constants.CMD_HAL_USB, _getHalUsbInfo, false); - break; + await _executeCase(iofogCommand, constants.CMD_HAL_USB, _getHalUsbInfo, false) + break case constants.CMD_HELP: default: return this.help() } } catch (error) { - this.handleCLIError(error, args.argv); + this.handleCLIError(error, args.argv) } } @@ -263,7 +263,7 @@ class IOFog extends BaseCLIHandler { header: 'JSON File Schema', content: [ JSON_SCHEMA, - ] + ], }, ]) } @@ -271,116 +271,115 @@ class IOFog extends BaseCLIHandler { async function _executeCase(commands, commandName, f, isUserRequired) { try { - const obj = commands[commandName]; + const obj = commands[commandName] if (isUserRequired) { - const decoratedFunction = CliDecorator.prepareUserById(f); - await decoratedFunction(obj); + const decoratedFunction = CliDecorator.prepareUserById(f) + await decoratedFunction(obj) } else { - await f(obj); + await f(obj) } } catch (error) { - logger.error(error.message); + logger.error(error.message) } } async function _createFog(obj, user) { const fog = obj.file ? JSON.parse(fs.readFileSync(obj.file, 'utf8')) - : _createFogObject(obj); + : _createFogObject(obj) - logger.cliReq('fog add', {args: fog}); - const result = await FogService.createFog(fog, user, true); + logger.cliReq('fog add', {args: fog}) + const result = await FogService.createFog(fog, user, true) logger.cliRes(JSON.stringify({ - uuid: result.uuid - }, null, 2)); + uuid: result.uuid, + }, null, 2)) } async function _updateFog(obj, user) { const fog = obj.file ? JSON.parse(fs.readFileSync(obj.file, 'utf8')) - : _createFogObject(obj); + : _createFogObject(obj) - fog.uuid = obj.iofogUuid; + fog.uuid = obj.iofogUuid - logger.cliReq('fog update', {args: fog}); - await FogService.updateFog(fog, user, true); - logger.cliRes('ioFog node has been updated successfully.'); + logger.cliReq('fog update', {args: fog}) + await FogService.updateFog(fog, user, true) + logger.cliRes('ioFog node has been updated successfully.') } async function _deleteFog(obj, user) { - const fog = _createFogObject(obj); - logger.cliReq('fog remove', {args: fog}); - await FogService.deleteFog(fog, user, true); - logger.cliRes('ioFog node has been removed successfully'); + const fog = _createFogObject(obj) + logger.cliReq('fog remove', {args: fog}) + await FogService.deleteFog(fog, user, true) + logger.cliRes('ioFog node has been removed successfully') } async function _getFogList(obj, user) { - logger.cliReq('fog list'); - const emptyFilters = []; - const list = await FogService.getFogList(emptyFilters, user, true); - logger.cliRes(JSON.stringify(list, null, 2)); + logger.cliReq('fog list') + const emptyFilters = [] + const list = await FogService.getFogList(emptyFilters, user, true) + logger.cliRes(JSON.stringify(list, null, 2)) } async function _getFog(obj, user) { - const fog = _createFogObject(obj); - logger.cliReq('fog info', {args: fog}); - const res = await FogService.getFogWithTransaction(fog, user, true); - logger.cliRes(JSON.stringify(res, null, 2)); + const fog = _createFogObject(obj) + logger.cliReq('fog info', {args: fog}) + const res = await FogService.getFogWithTransaction(fog, user, true) + logger.cliRes(JSON.stringify(res, null, 2)) } async function _generateProvision(obj, user) { - const fog = _createFogObject(obj); - logger.cliReq('fog provisioning-key', {args: fog}); - const response = await FogService.generateProvisioningKey(fog, user, true); - logger.cliRes(JSON.stringify(response), null, 2); + const fog = _createFogObject(obj) + logger.cliReq('fog provisioning-key', {args: fog}) + const response = await FogService.generateProvisioningKey(fog, user, true) + logger.cliRes(JSON.stringify(response), null, 2) } async function _setFogRebootCommand(obj, user) { - const fog = _createFogObject(obj); - logger.cliReq('fog reboot', {args: fog}); - await FogService.setFogRebootCommand(fog, user, true); - logger.cliRes('ioFog reboot command has been set successfully'); + const fog = _createFogObject(obj) + logger.cliReq('fog reboot', {args: fog}) + await FogService.setFogRebootCommand(fog, user, true) + logger.cliRes('ioFog reboot command has been set successfully') } async function _setFogVersionCommand(obj, user) { const fog = { uuid: obj.iofogUuid, - versionCommand: obj.versionCommand - }; - logger.cliReq('fog version', {args: fog}); - await FogService.setFogVersionCommand(fog, user, true); - logger.cliRes('ioFog version command has been set successfully'); + versionCommand: obj.versionCommand, + } + logger.cliReq('fog version', {args: fog}) + await FogService.setFogVersionCommand(fog, user, true) + logger.cliRes('ioFog version command has been set successfully') } async function _getHalHardwareInfo(obj) { const uuidObj = { - uuid: obj.iofogUuid - }; - logger.cliReq('fog hal-hw', {args: uuidObj}); - const data = await FogService.getHalHardwareInfo(uuidObj, {}, true); + uuid: obj.iofogUuid, + } + logger.cliReq('fog hal-hw', {args: uuidObj}) + const data = await FogService.getHalHardwareInfo(uuidObj, {}, true) if (data) { if (data.hasOwnProperty('info')) { - data.info = JSON.parse(data.info); + data.info = JSON.parse(data.info) } - - logger.cliRes(JSON.stringify(data, null, 2)); - } + logger.cliRes(JSON.stringify(data, null, 2)) + } } async function _getHalUsbInfo(obj) { const uuidObj = { - uuid: obj.iofogUuid - }; - logger.cliReq('fog hal-usb', {args: uuidObj}); - const data = await FogService.getHalUsbInfo(uuidObj, {}, true); + uuid: obj.iofogUuid, + } + logger.cliReq('fog hal-usb', {args: uuidObj}) + const data = await FogService.getHalUsbInfo(uuidObj, {}, true) if (data) { if (data.hasOwnProperty('info')) { - data.info = JSON.parse(data.info); + data.info = JSON.parse(data.info) } - logger.cliRes(JSON.stringify(data, null, 2)); + logger.cliRes(JSON.stringify(data, null, 2)) } } @@ -408,10 +407,10 @@ function _createFogObject(cliData) { abstractedHardwareEnabled: AppHelper.validateBooleanCliOptions(cliData.absHwEnable, cliData.absHwDisable), fogType: cliData.fogType, - userId: cliData.userId - }; + userId: cliData.userId, + } - return AppHelper.deleteUndefinedFields(fogObj); + return AppHelper.deleteUndefinedFields(fogObj) } -module.exports = new IOFog(); \ No newline at end of file +module.exports = new IOFog() diff --git a/src/cli/microservice.js b/src/cli/microservice.js index 42ce9b48e..2c5813e02 100644 --- a/src/cli/microservice.js +++ b/src/cli/microservice.js @@ -11,158 +11,158 @@ * */ -const BaseCLIHandler = require('./base-cli-handler'); -const constants = require('../helpers/constants'); -const ErrorMessages = require('../helpers/error-messages'); -const logger = require('../logger'); -const MicroserviceService = require('../services/microservices-service'); -const fs = require('fs'); -const AppHelper = require('../helpers/app-helper'); -const CliDecorator = require('../decorators/cli-decorator'); -const CliDataTypes = require('./cli-data-types'); +const BaseCLIHandler = require('./base-cli-handler') +const constants = require('../helpers/constants') +const ErrorMessages = require('../helpers/error-messages') +const logger = require('../logger') +const MicroserviceService = require('../services/microservices-service') +const fs = require('fs') +const AppHelper = require('../helpers/app-helper') +const CliDecorator = require('../decorators/cli-decorator') +const CliDataTypes = require('./cli-data-types') const JSON_SCHEMA_ADD = AppHelper.stringifyCliJsonSchema( - { - name: "string", - config: "string", - catalogItemId: 0, - flowId: 0, - iofogUuid: "string", - rootHostAccess: true, - logSize: 0, - volumeMappings: [ - { - hostDestination: "/var/dest", - containerDestination: "/var/dest", - accessMode: "rw" - } - ], - ports: [ - { - internal: 0, - external: 0, - publicMode: true - } - ], - routes: [ - "string" - ] - } -); + { + name: 'string', + config: 'string', + catalogItemId: 0, + flowId: 0, + iofogUuid: 'string', + rootHostAccess: true, + logSize: 0, + volumeMappings: [ + { + hostDestination: '/var/dest', + containerDestination: '/var/dest', + accessMode: 'rw', + }, + ], + ports: [ + { + internal: 0, + external: 0, + publicMode: true, + }, + ], + routes: [ + 'string', + ], + } +) const JSON_SCHEMA_UPDATE = AppHelper.stringifyCliJsonSchema( - { - name: "string", - config: "string", - rebuild: true, - iofogUuid: "string", - rootHostAccess: true, - logSize: 0, - volumeMappings: [ - { - hostDestination: "/var/dest", - containerDestination: "/var/dest", - accessMode: "rw" - } - ] - } -); + { + name: 'string', + config: 'string', + rebuild: true, + iofogUuid: 'string', + rootHostAccess: true, + logSize: 0, + volumeMappings: [ + { + hostDestination: '/var/dest', + containerDestination: '/var/dest', + accessMode: 'rw', + }, + ], + } +) class Microservice extends BaseCLIHandler { constructor() { - super(); + super() - this.name = constants.CMD_MICROSERVICE; + this.name = constants.CMD_MICROSERVICE this.commandDefinitions = [ { name: 'command', defaultOption: true, - group: [constants.CMD] + group: [constants.CMD], }, { name: 'file', alias: 'f', type: String, description: 'Path to microservice settings JSON file', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'microservice-uuid', alias: 'i', type: String, description: 'Microservice UUID', group: [constants.CMD_UPDATE, constants.CMD_REMOVE, constants.CMD_INFO, constants.CMD_PORT_MAPPING_CREATE, constants.CMD_PORT_MAPPING_REMOVE, constants.CMD_PORT_MAPPING_LIST, constants.CMD_VOLUME_MAPPING_CREATE, - constants.CMD_VOLUME_MAPPING_REMOVE, constants.CMD_VOLUME_MAPPING_LIST] + constants.CMD_VOLUME_MAPPING_REMOVE, constants.CMD_VOLUME_MAPPING_LIST], }, { name: 'name', alias: 'n', type: String, description: 'Microservice name', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { - name: 'catalog-id', alias: 'c', type: CliDataTypes.Integer, description: 'Catalog item ID', - group: [constants.CMD_ADD] + name: 'catalog-id', alias: 'c', type: CliDataTypes.Integer, description: 'Catalog item ID', + group: [constants.CMD_ADD], }, { name: 'flow-id', alias: 'F', type: CliDataTypes.Integer, description: 'Application flow ID', - group: [constants.CMD_ADD] + group: [constants.CMD_ADD], }, { name: 'iofog-uuid', alias: 'I', type: String, description: 'ioFog node UUID', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'config', alias: 'g', type: String, description: 'Microservice config', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'volumes', alias: 'v', type: String, description: 'Microservice volume mapping(s)', multiple: true, - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { - name: 'log-size', alias: 'l', type: CliDataTypes.Integer, description: 'Log file size limit (MB)', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + name: 'log-size', alias: 'l', type: CliDataTypes.Integer, description: 'Log file size limit (MB)', + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'root-enable', alias: 'r', type: Boolean, description: 'Enable root access', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'root-disable', alias: 'R', type: Boolean, description: 'Disable root access', - group: [constants.CMD_UPDATE, constants.CMD_ADD] + group: [constants.CMD_UPDATE, constants.CMD_ADD], }, { name: 'ports', alias: 'p', type: String, description: 'Container ports', multiple: true, - group: [constants.CMD_ADD] + group: [constants.CMD_ADD], }, { name: 'mapping', alias: 'P', type: String, description: 'Container port mapping', - group: [constants.CMD_PORT_MAPPING_CREATE, constants.CMD_VOLUME_MAPPING_CREATE] + group: [constants.CMD_PORT_MAPPING_CREATE, constants.CMD_VOLUME_MAPPING_CREATE], }, { name: 'routes', alias: 't', type: String, description: 'Microservice route(s) (receiving microservices)', multiple: true, - group: [constants.CMD_ADD] + group: [constants.CMD_ADD], }, { name: 'route', alias: 'T', type: String, description: 'Microservice route (receiving microservices)', - group: [constants.CMD_ROUTE_CREATE, constants.CMD_ROUTE_REMOVE] + group: [constants.CMD_ROUTE_CREATE, constants.CMD_ROUTE_REMOVE], }, { name: 'internal-port', alias: 'b', type: CliDataTypes.Integer, description: 'Internal port', - group: [constants.CMD_PORT_MAPPING_REMOVE] + group: [constants.CMD_PORT_MAPPING_REMOVE], }, { name: 'rebuild', alias: 'w', type: Boolean, description: 'Rebuild microservice image on fog agent', - group: [constants.CMD_UPDATE] + group: [constants.CMD_UPDATE], }, { name: 'cleanup', alias: 'z', type: Boolean, description: 'Delete microservice with cleanup', - group: [constants.CMD_REMOVE] + group: [constants.CMD_REMOVE], }, { name: 'user-id', alias: 'u', type: CliDataTypes.Integer, description: 'User\'s id', - group: [constants.CMD_ADD] + group: [constants.CMD_ADD], }, { name: 'mapping-id', alias: 'a', type: CliDataTypes.Integer, description: 'Volume mapping id', - group: [constants.CMD_VOLUME_MAPPING_REMOVE] - } - ]; + group: [constants.CMD_VOLUME_MAPPING_REMOVE], + }, + ] this.commands = { [constants.CMD_ADD]: 'Add a new microservice.', [constants.CMD_UPDATE]: 'Update existing microservice.', @@ -182,58 +182,58 @@ class Microservice extends BaseCLIHandler { async run(args) { try { - const microserviceCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}); + const microserviceCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}) - const command = microserviceCommand.command.command; + const command = microserviceCommand.command.command - this.validateParameters(command, this.commandDefinitions, args.argv); + this.validateParameters(command, this.commandDefinitions, args.argv) switch (command) { case constants.CMD_ADD: - await _executeCase(microserviceCommand, constants.CMD_ADD, _createMicroservice, true); - break; + await _executeCase(microserviceCommand, constants.CMD_ADD, _createMicroservice, true) + break case constants.CMD_UPDATE: - await _executeCase(microserviceCommand, constants.CMD_UPDATE, _updateMicroservice, false); - break; + await _executeCase(microserviceCommand, constants.CMD_UPDATE, _updateMicroservice, false) + break case constants.CMD_REMOVE: - await _executeCase(microserviceCommand, constants.CMD_REMOVE, _removeMicroservice, false); - break; + await _executeCase(microserviceCommand, constants.CMD_REMOVE, _removeMicroservice, false) + break case constants.CMD_LIST: - await _executeCase(microserviceCommand, constants.CMD_LIST, _listMicroservices, false); - break; + await _executeCase(microserviceCommand, constants.CMD_LIST, _listMicroservices, false) + break case constants.CMD_INFO: - await _executeCase(microserviceCommand, constants.CMD_INFO, _getMicroservice, false); - break; + await _executeCase(microserviceCommand, constants.CMD_INFO, _getMicroservice, false) + break case constants.CMD_ROUTE_CREATE: - await _executeCase(microserviceCommand, constants.CMD_ROUTE_CREATE, _createRoute, false); - break; + await _executeCase(microserviceCommand, constants.CMD_ROUTE_CREATE, _createRoute, false) + break case constants.CMD_ROUTE_REMOVE: - await _executeCase(microserviceCommand, constants.CMD_ROUTE_REMOVE, _removeRoute, false); - break; + await _executeCase(microserviceCommand, constants.CMD_ROUTE_REMOVE, _removeRoute, false) + break case constants.CMD_PORT_MAPPING_CREATE: - await _executeCase(microserviceCommand, constants.CMD_PORT_MAPPING_CREATE, _createPortMapping, false); - break; + await _executeCase(microserviceCommand, constants.CMD_PORT_MAPPING_CREATE, _createPortMapping, false) + break case constants.CMD_PORT_MAPPING_REMOVE: - await _executeCase(microserviceCommand, constants.CMD_PORT_MAPPING_REMOVE, _removePortMapping, false); - break; + await _executeCase(microserviceCommand, constants.CMD_PORT_MAPPING_REMOVE, _removePortMapping, false) + break case constants.CMD_PORT_MAPPING_LIST: - await _executeCase(microserviceCommand, constants.CMD_PORT_MAPPING_LIST, _listPortMappings, false); - break; + await _executeCase(microserviceCommand, constants.CMD_PORT_MAPPING_LIST, _listPortMappings, false) + break case constants.CMD_VOLUME_MAPPING_CREATE: - await _executeCase(microserviceCommand, constants.CMD_VOLUME_MAPPING_CREATE, _createVolumeMapping, false); - break; + await _executeCase(microserviceCommand, constants.CMD_VOLUME_MAPPING_CREATE, _createVolumeMapping, false) + break case constants.CMD_VOLUME_MAPPING_REMOVE: - await _executeCase(microserviceCommand, constants.CMD_VOLUME_MAPPING_REMOVE, _removeVolumeMapping, false); - break; + await _executeCase(microserviceCommand, constants.CMD_VOLUME_MAPPING_REMOVE, _removeVolumeMapping, false) + break case constants.CMD_VOLUME_MAPPING_LIST: - await _executeCase(microserviceCommand, constants.CMD_VOLUME_MAPPING_LIST, _listVolumeMappings, false); - break; + await _executeCase(microserviceCommand, constants.CMD_VOLUME_MAPPING_LIST, _listVolumeMappings, false) + break case constants.CMD_HELP: default: return this.help() } } catch (error) { - this.handleCLIError(error, args.argv); + this.handleCLIError(error, args.argv) } } @@ -249,7 +249,7 @@ class Microservice extends BaseCLIHandler { { header: 'JSON UPDATE File Schema', content: [ - JSON_SCHEMA_UPDATE + JSON_SCHEMA_UPDATE, ], raw: true, }, @@ -262,7 +262,8 @@ class Microservice extends BaseCLIHandler { }, { desc: '2. Multiple mappings', - example: '$ iofog-controller microservice add [other required options] --volumes /host_src:/container_src:rw /host_bin:/container_bin:r', + example: '$ iofog-controller microservice add [other required options] --volumes /host_src:/container_src:rw ' + + '/host_bin:/container_bin:r', }, { desc: '3. Port mapping (80:8080:false - internal port : external port : public mode)', @@ -270,7 +271,7 @@ class Microservice extends BaseCLIHandler { }, { desc: '4. Add routes (ABC:DEF - source microservice uuid : dest microservice uuid)', - example: '$ iofog-controller microservice add [other required options] --routes ABC:DEF RFG:HJK' + example: '$ iofog-controller microservice add [other required options] --routes ABC:DEF RFG:HJK', }, { desc: '5. Add route (ABC:DEF - source microservice uuid : dest microservice uuid)', @@ -282,20 +283,20 @@ class Microservice extends BaseCLIHandler { }, { desc: '7. Create port mapping (80:8080:false - internal port : external port : public mode, ABC - microservice)', - example: '$ iofog-controller microservice port-mapping-create --mapping 80:8080:false -i ABC' + example: '$ iofog-controller microservice port-mapping-create --mapping 80:8080:false -i ABC', }, { desc: '8. Delete port mapping (80 - internal port, ABC - microservice uuid)', - example: '$ iofog-controller microservice port-mapping-remove --internal-port 80 -i ABC' + example: '$ iofog-controller microservice port-mapping-remove --internal-port 80 -i ABC', }, { desc: '9. Create volume mapping', - example: '$ iofog-controller microservice volume-mapping-create --mapping /host_src:/container_src:rw -i ABC' + example: '$ iofog-controller microservice volume-mapping-create --mapping /host_src:/container_src:rw -i ABC', }, { desc: '10. Delete volume mapping', - example: '$ iofog-controller microservice volume-mapping-remove -i ABC -a 1' - } + example: '$ iofog-controller microservice volume-mapping-remove -i ABC -a 1', + }, ], }, ]) @@ -304,157 +305,157 @@ class Microservice extends BaseCLIHandler { async function _executeCase(commands, commandName, f, isUserRequired) { try { - const obj = commands[commandName]; + const obj = commands[commandName] if (isUserRequired) { - const decoratedFunction = CliDecorator.prepareUserById(f); - await decoratedFunction(obj); + const decoratedFunction = CliDecorator.prepareUserById(f) + await decoratedFunction(obj) } else { - await f(obj); + await f(obj) } } catch (error) { - logger.error(error.message); + logger.error(error.message) } } -const _createRoute = async function (obj, user) { +const _createRoute = async function(obj, user) { try { - const arr = obj.route.split(':'); - const sourceMicroserviceUuid = arr[0]; - const destMicroserviceUuid = arr[1]; - logger.cliReq('microservice route-create', {args: {source: sourceMicroserviceUuid, dest: destMicroserviceUuid}}); - await MicroserviceService.createRoute(sourceMicroserviceUuid, destMicroserviceUuid, user, true); + const arr = obj.route.split(':') + const sourceMicroserviceUuid = arr[0] + const destMicroserviceUuid = arr[1] + logger.cliReq('microservice route-create', {args: {source: sourceMicroserviceUuid, dest: destMicroserviceUuid}}) + await MicroserviceService.createRoute(sourceMicroserviceUuid, destMicroserviceUuid, user, true) logger.cliRes(`Microservice route with source microservice ${sourceMicroserviceUuid} and dest microservice ${destMicroserviceUuid} has been created successfully.`) } catch (e) { - logger.error(ErrorMessages.CLI.INVALID_ROUTE); + logger.error(ErrorMessages.CLI.INVALID_ROUTE) } -}; +} -const _removeRoute = async function (obj, user) { +const _removeRoute = async function(obj, user) { try { - const arr = obj.route.split(':'); - const sourceMicroserviceUuid = arr[0]; - const destMicroserviceUuid = arr[1]; + const arr = obj.route.split(':') + const sourceMicroserviceUuid = arr[0] + const destMicroserviceUuid = arr[1] logger.cliReq('microservice route-remove', {args: {source: sourceMicroserviceUuid, dest: destMicroserviceUuid}}) - await MicroserviceService.deleteRoute(sourceMicroserviceUuid, destMicroserviceUuid, user, true); + await MicroserviceService.deleteRoute(sourceMicroserviceUuid, destMicroserviceUuid, user, true) logger.cliRes('Microservice route with source microservice ' + sourceMicroserviceUuid + - ' and dest microservice ' + destMicroserviceUuid + 'has been removed successfully.'); + ' and dest microservice ' + destMicroserviceUuid + 'has been removed successfully.') } catch (e) { - logger.error(ErrorMessages.CLI.INVALID_ROUTE); + logger.error(ErrorMessages.CLI.INVALID_ROUTE) } -}; - -const _createPortMapping = async function (obj, user) { - const mapping = parsePortMappingObject(obj.mapping, ErrorMessages.CLI.INVALID_PORT_MAPPING); - logger.cliReq('microservice port-mapping-create', {args: mapping}); - await MicroserviceService.createPortMapping(obj.microserviceUuid, mapping, user, true); - logger.cliRes('Port mapping has been created successfully.'); -}; - -const _createVolumeMapping = async function (obj, user) { - const mapping = parseVolumeMappingObject(obj.mapping, ErrorMessages.CLI.INVALID_VOLUME_MAPPING); - logger.cliReq('microservice volume-mapping-create', {args: mapping}); - const result = await MicroserviceService.createVolumeMapping(obj.microserviceUuid, mapping, user, true); +} + +const _createPortMapping = async function(obj, user) { + const mapping = parsePortMappingObject(obj.mapping, ErrorMessages.CLI.INVALID_PORT_MAPPING) + logger.cliReq('microservice port-mapping-create', {args: mapping}) + await MicroserviceService.createPortMapping(obj.microserviceUuid, mapping, user, true) + logger.cliRes('Port mapping has been created successfully.') +} + +const _createVolumeMapping = async function(obj, user) { + const mapping = parseVolumeMappingObject(obj.mapping, ErrorMessages.CLI.INVALID_VOLUME_MAPPING) + logger.cliReq('microservice volume-mapping-create', {args: mapping}) + const result = await MicroserviceService.createVolumeMapping(obj.microserviceUuid, mapping, user, true) logger.cliRes(JSON.stringify({ - id: result.id - }, null, 2)); -}; + id: result.id, + }, null, 2)) +} -const _removePortMapping = async function (obj, user) { +const _removePortMapping = async function(obj, user) { try { - logger.cliReq('microservice port-mapping-remove', {args: obj}); - await MicroserviceService.deletePortMapping(obj.microserviceUuid, obj.internalPort, user, true); - logger.cliRes('Port mapping has been removed successfully.'); + logger.cliReq('microservice port-mapping-remove', {args: obj}) + await MicroserviceService.deletePortMapping(obj.microserviceUuid, obj.internalPort, user, true) + logger.cliRes('Port mapping has been removed successfully.') } catch (e) { - logger.error(e.message); + logger.error(e.message) } -}; +} -const _removeVolumeMapping = async function (obj, user) { +const _removeVolumeMapping = async function(obj, user) { try { - logger.cliReq('microservice volume-mapping-remove', {args: obj}); - await MicroserviceService.deleteVolumeMapping(obj.microserviceUuid, obj.mappingId, user, true); - logger.cliRes('Volume mapping has been deleted successfully.'); + logger.cliReq('microservice volume-mapping-remove', {args: obj}) + await MicroserviceService.deleteVolumeMapping(obj.microserviceUuid, obj.mappingId, user, true) + logger.cliRes('Volume mapping has been deleted successfully.') } catch (e) { - logger.error(e.message); + logger.error(e.message) } -}; +} -const _listPortMappings = async function (obj, user) { - logger.cliReq('microservice port-mapping-list', {args: {microserviceUuid: obj.microserviceUuid}}); - const result = await MicroserviceService.listMicroservicePortMappings(obj.microserviceUuid, user, true); - logger.cliRes(JSON.stringify(result, null, 2)); -}; +const _listPortMappings = async function(obj, user) { + logger.cliReq('microservice port-mapping-list', {args: {microserviceUuid: obj.microserviceUuid}}) + const result = await MicroserviceService.listMicroservicePortMappings(obj.microserviceUuid, user, true) + logger.cliRes(JSON.stringify(result, null, 2)) +} -const _listVolumeMappings = async function (obj, user) { - logger.cliReq('microservice volume-mapping-list', {args: {microserviceUuid: obj.microserviceUuid}}); - const result = await MicroserviceService.listVolumeMappings(obj.microserviceUuid, user, true); - logger.cliRes(JSON.stringify(result, null, 2)); -}; +const _listVolumeMappings = async function(obj, user) { + logger.cliReq('microservice volume-mapping-list', {args: {microserviceUuid: obj.microserviceUuid}}) + const result = await MicroserviceService.listVolumeMappings(obj.microserviceUuid, user, true) + logger.cliRes(JSON.stringify(result, null, 2)) +} -const _removeMicroservice = async function (obj, user) { +const _removeMicroservice = async function(obj, user) { const microserviceData = { - withCleanup: obj.cleanup - }; + withCleanup: obj.cleanup, + } - logger.cliReq('microservice remove', {args: {microserviceUuid: obj.microserviceUuid, withCleanup: obj.cleanup}}); - await MicroserviceService.deleteMicroservice(obj.microserviceUuid, microserviceData, user, true); + logger.cliReq('microservice remove', {args: {microserviceUuid: obj.microserviceUuid, withCleanup: obj.cleanup}}) + await MicroserviceService.deleteMicroservice(obj.microserviceUuid, microserviceData, user, true) logger.cliRes('Microservice has been removed successfully.') -}; +} -const _listMicroservices = async function () { - logger.cliReq('microservice list'); - const result = await MicroserviceService.listMicroservices({}, {}, true); - logger.cliRes(JSON.stringify(result, null, 2)); -}; +const _listMicroservices = async function() { + logger.cliReq('microservice list') + const result = await MicroserviceService.listMicroservices({}, {}, true) + logger.cliRes(JSON.stringify(result, null, 2)) +} -const _getMicroservice = async function (obj, user) { - logger.cliReq('microservice info', {args: {microserviceUuid: obj.microserviceUuid}}); - const result = await MicroserviceService.getMicroservice(obj.microserviceUuid, user, true); - logger.cliRes(JSON.stringify(result, null, 2)); -}; +const _getMicroservice = async function(obj, user) { + logger.cliReq('microservice info', {args: {microserviceUuid: obj.microserviceUuid}}) + const result = await MicroserviceService.getMicroservice(obj.microserviceUuid, user, true) + logger.cliRes(JSON.stringify(result, null, 2)) +} -const _createMicroservice = async function (obj, user) { +const _createMicroservice = async function(obj, user) { const microservice = obj.file ? JSON.parse(fs.readFileSync(obj.file, 'utf8')) - : _createMicroserviceObject(obj); + : _createMicroserviceObject(obj) - logger.cliReq('microservice add', {args: microservice}); - const result = await MicroserviceService.createMicroservice(microservice, user, true); + logger.cliReq('microservice add', {args: microservice}) + const result = await MicroserviceService.createMicroservice(microservice, user, true) logger.cliRes(JSON.stringify({ - uuid: result.uuid + uuid: result.uuid, }, null, 2)) -}; +} -const _updateMicroservice = async function (obj, user) { +const _updateMicroservice = async function(obj, user) { const microservice = obj.file ? JSON.parse(fs.readFileSync(obj.file, 'utf8')) - : _updateMicroserviceObject(obj); + : _updateMicroserviceObject(obj) - logger.cliReq('microservice update', {args: microservice}); - await MicroserviceService.updateMicroservice(obj.microserviceUuid, microservice, user, true); - logger.cliRes('Microservice has been updated successfully.'); -}; + logger.cliReq('microservice update', {args: microservice}) + await MicroserviceService.updateMicroservice(obj.microserviceUuid, microservice, user, true) + logger.cliRes('Microservice has been updated successfully.') +} -const _updateMicroserviceObject = function (obj) { +const _updateMicroserviceObject = function(obj) { const microserviceObj = { name: obj.name, config: obj.config, iofogUuid: obj.iofogUuid, rootHostAccess: AppHelper.validateBooleanCliOptions(obj.rootEnable, obj.rootDisable), logSize: obj.logSize, - rebuild: obj.rebuild - }; + rebuild: obj.rebuild, + } if (obj.volumes) { - microserviceObj.volumeMappings = parseVolumeMappingArray(obj.volumes, 'Error during parsing of volume mapping option.'); + microserviceObj.volumeMappings = parseVolumeMappingArray(obj.volumes, 'Error during parsing of volume mapping option.') } - return AppHelper.deleteUndefinedFields(microserviceObj); -}; + return AppHelper.deleteUndefinedFields(microserviceObj) +} -const _createMicroserviceObject = function (obj) { +const _createMicroserviceObject = function(obj) { const microserviceObj = { name: obj.name, config: obj.config, @@ -463,55 +464,55 @@ const _createMicroserviceObject = function (obj) { iofogUuid: obj.iofogUuid, rootHostAccess: AppHelper.validateBooleanCliOptions(obj.rootEnable, obj.rootDisable), logSize: obj.logSize, - routes: obj.routes - }; + routes: obj.routes, + } if (obj.volumes) { - microserviceObj.volumeMappings = parseVolumeMappingArray(obj.volumes, ErrorMessages.CLI.INVALID_VOLUME_MAPPING); + microserviceObj.volumeMappings = parseVolumeMappingArray(obj.volumes, ErrorMessages.CLI.INVALID_VOLUME_MAPPING) } if (obj.ports) { - microserviceObj.ports = parsePortMappingArray(obj.ports, ErrorMessages.CLI.INVALID_PORT_MAPPING); + microserviceObj.ports = parsePortMappingArray(obj.ports, ErrorMessages.CLI.INVALID_PORT_MAPPING) } - return AppHelper.deleteUndefinedFields(microserviceObj); -}; + return AppHelper.deleteUndefinedFields(microserviceObj) +} -const parseVolumeMappingObject = function (obj, errMsg) { - let result = {}; +const parseVolumeMappingObject = function(obj, errMsg) { + let result = {} try { - const props = obj.split(':'); + const props = obj.split(':') result = { hostDestination: props[0], containerDestination: props[1], - accessMode: props[2] + accessMode: props[2], } } catch (e) { - logger.warn(errMsg); + logger.warn(errMsg) } - return result; -}; + return result +} -const parseVolumeMappingArray = function (arr, errMsg) { - return arr.map(obj => parseVolumeMappingObject(obj, errMsg)); -}; +const parseVolumeMappingArray = function(arr, errMsg) { + return arr.map((obj) => parseVolumeMappingObject(obj, errMsg)) +} -const parsePortMappingObject = function (obj, errMsg) { - let result = {}; +const parsePortMappingObject = function(obj, errMsg) { + let result = {} try { - const props = obj.split(':'); + const props = obj.split(':') result = { internal: parseInt(props[0]), external: parseInt(props[1]), - publicMode: props[2] === 'true' + publicMode: props[2] === 'true', } } catch (e) { - logger.warn(errMsg); + logger.warn(errMsg) } - return result; -}; + return result +} -const parsePortMappingArray = function (arr, errMsg) { - return arr.map(obj => parsePortMappingObject(obj, errMsg)); -}; +const parsePortMappingArray = function(arr, errMsg) { + return arr.map((obj) => parsePortMappingObject(obj, errMsg)) +} -module.exports = new Microservice(); \ No newline at end of file +module.exports = new Microservice() diff --git a/src/cli/registry.js b/src/cli/registry.js index 59ba006ab..2e57c1b7e 100644 --- a/src/cli/registry.js +++ b/src/cli/registry.js @@ -11,75 +11,75 @@ * */ -const BaseCLIHandler = require('./base-cli-handler'); -const constants = require('../helpers/constants'); -const logger = require('../logger'); -const CliDecorator = require('../decorators/cli-decorator'); -const RegistryService = require('../services/registry-service'); -const AppHelper = require('../helpers/app-helper'); -const CliDataTypes = require('./cli-data-types'); +const BaseCLIHandler = require('./base-cli-handler') +const constants = require('../helpers/constants') +const logger = require('../logger') +const CliDecorator = require('../decorators/cli-decorator') +const RegistryService = require('../services/registry-service') +const AppHelper = require('../helpers/app-helper') +const CliDataTypes = require('./cli-data-types') class Registry extends BaseCLIHandler { constructor() { - super(); + super() - this.name = constants.CMD_REGISTRY; + this.name = constants.CMD_REGISTRY this.commandDefinitions = [ { name: 'command', defaultOption: true, - group: [constants.CMD] + group: [constants.CMD], }, { name: 'uri', alias: 'U', type: String, description: 'Registry URI', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'public', alias: 'b', type: Boolean, description: 'Set registry as public', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'private', alias: 'r', type: Boolean, description: 'Set registry as private', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'username', alias: 'l', type: String, description: 'Registry\'s user name', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'password', alias: 'p', type: String, description: 'Password', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'requires-certificate', alias: 'c', type: Boolean, description: 'Requires certificate', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'certificate', alias: 'C', type: String, description: 'Certificate', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'email', alias: 'e', type: String, description: 'Email address', - group: [constants.CMD_ADD, constants.CMD_UPDATE] + group: [constants.CMD_ADD, constants.CMD_UPDATE], }, { name: 'user-id', alias: 'u', type: CliDataTypes.Integer, description: 'User\'s id', - group: [constants.CMD_ADD] + group: [constants.CMD_ADD], }, { name: 'item-id', alias: 'i', type: CliDataTypes.Integer, description: 'Item\'s id', - group: [constants.CMD_REMOVE, constants.CMD_UPDATE] - } - ]; + group: [constants.CMD_REMOVE, constants.CMD_UPDATE], + }, + ] this.commands = { [constants.CMD_ADD]: 'Add a new Registry.', [constants.CMD_REMOVE]: 'Delete a Registry.', @@ -90,76 +90,75 @@ class Registry extends BaseCLIHandler { async run(args) { try { - const registryCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}); + const registryCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}) - const command = registryCommand.command.command; + const command = registryCommand.command.command - this.validateParameters(command, this.commandDefinitions, args.argv); + this.validateParameters(command, this.commandDefinitions, args.argv) switch (command) { case constants.CMD_ADD: - await _executeCase(registryCommand, constants.CMD_ADD, _createRegistry, true); - break; + await _executeCase(registryCommand, constants.CMD_ADD, _createRegistry, true) + break case constants.CMD_REMOVE: - await _executeCase(registryCommand, constants.CMD_REMOVE, _deleteRegistry, false); - break; + await _executeCase(registryCommand, constants.CMD_REMOVE, _deleteRegistry, false) + break case constants.CMD_UPDATE: - await _executeCase(registryCommand, constants.CMD_UPDATE, _updateRegistry, false); - break; + await _executeCase(registryCommand, constants.CMD_UPDATE, _updateRegistry, false) + break case constants.CMD_LIST: - await _executeCase(registryCommand, constants.CMD_LIST, _getRegistries, false); - break; + await _executeCase(registryCommand, constants.CMD_LIST, _getRegistries, false) + break case constants.CMD_HELP: default: return this.help([]) } } catch (error) { - this.handleCLIError(error, args.argv); + this.handleCLIError(error, args.argv) } } - } async function _createRegistry(obj, user) { - const registry = _createRegistryObject(obj); - logger.cliReq('registry add', {args: registry}); - const response = await RegistryService.createRegistry(registry, user); + const registry = _createRegistryObject(obj) + logger.cliReq('registry add', {args: registry}) + const response = await RegistryService.createRegistry(registry, user) logger.cliRes(JSON.stringify({ - id: response.id - }, null, 2)); + id: response.id, + }, null, 2)) } async function _getRegistries(obj, user) { - logger.cliReq('registry list'); - const result = await RegistryService.findRegistries(user, true); - logger.cliRes(JSON.stringify(result, null, 2)); + logger.cliReq('registry list') + const result = await RegistryService.findRegistries(user, true) + logger.cliRes(JSON.stringify(result, null, 2)) } async function _deleteRegistry(obj, user) { - logger.cliReq('registry remove', {args: {id: obj.itemId}}); - await RegistryService.deleteRegistry({id: obj.itemId}, user, true); - logger.cliRes('Registry has been removed successfully.'); + logger.cliReq('registry remove', {args: {id: obj.itemId}}) + await RegistryService.deleteRegistry({id: obj.itemId}, user, true) + logger.cliRes('Registry has been removed successfully.') } async function _updateRegistry(obj) { - const registry = _createRegistryObject(obj); - logger.cliReq('registry update', {args: registry}); - await RegistryService.updateRegistry(registry, obj.itemId, {}, true); - logger.cliRes('Registry has been updated successfully.'); + const registry = _createRegistryObject(obj) + logger.cliReq('registry update', {args: registry}) + await RegistryService.updateRegistry(registry, obj.itemId, {}, true) + logger.cliRes('Registry has been updated successfully.') } async function _executeCase(commands, commandName, f, isUserRequired) { try { - const obj = commands[commandName]; + const obj = commands[commandName] if (isUserRequired) { - const decoratedFunction = CliDecorator.prepareUserById(f); - await decoratedFunction(obj); + const decoratedFunction = CliDecorator.prepareUserById(f) + await decoratedFunction(obj) } else { - await f(obj); + await f(obj) } } catch (error) { - logger.error(error.message); + logger.error(error.message) } } @@ -171,8 +170,8 @@ function _createRegistryObject(cliData) { isPublic: AppHelper.validateBooleanCliOptions(cliData.public, cliData.private), email: cliData.email, requiresCert: cliData.requiresCertificate, - certificate: cliData.certificate - }; + certificate: cliData.certificate, + } } -module.exports = new Registry(); \ No newline at end of file +module.exports = new Registry() diff --git a/src/cli/start.js b/src/cli/start.js index 5c318f1a8..313f47969 100644 --- a/src/cli/start.js +++ b/src/cli/start.js @@ -11,26 +11,26 @@ * */ -const BaseCLIHandler = require('./base-cli-handler'); -const config = require('../config'); -const logger = require('../logger'); -const db = require('../sequelize/models'); +const BaseCLIHandler = require('./base-cli-handler') +const config = require('../config') +const logger = require('../logger') +const db = require('../sequelize/models') class Start extends BaseCLIHandler { async run(args) { - const daemon = args.daemon; + const daemon = args.daemon const configuration = { devMode: config.get('Server:DevMode'), port: config.get('Server:Port'), sslKey: config.get('Server:SslKey'), sslCert: config.get('Server:SslCert'), intermedKey: config.get('Server:IntermediateCert'), - }; - const pid = daemon.status(); + } + const pid = daemon.status() if (pid === 0) { - this.initDB(); - daemon.start(); + this.initDB() + daemon.start() checkDaemon(daemon, configuration) } else { logger.cliRes(`iofog-controller already running. PID: ${pid}`) @@ -39,37 +39,38 @@ class Start extends BaseCLIHandler { async initDB() { try { - await db.migrate(); - await db.seed(); + await db.migrate() + await db.seed() } catch (err) { - logger.error('Unable to initialize the database.', err); + logger.error('Unable to initialize the database.', err) process.exit(1) } } } function checkDaemon(daemon, configuration) { - let iterationsCount = 0; + let iterationsCount = 0 const check = () => { - iterationsCount++; - let pid = daemon.status(); + iterationsCount++ + const pid = daemon.status() if (pid === 0) { - return logger.error('Error: port is probably allocated, or ssl_key or ssl_cert or intermediate_cert is either missing or invalid.') + return logger.error('Error: port is probably allocated, or ssl_key or ssl_cert or intermediate_cert ' + + 'is either missing or invalid.') } if (iterationsCount === 5) { - checkServerProtocol(configuration); + checkServerProtocol(configuration) return logger.cliRes(`ioFog-Controller has started at pid: ${pid}`) } setTimeout(check, 1000) - }; + } setTimeout(check, 1000) } function checkServerProtocol(configuration) { - const { devMode, port, sslKey, sslCert, intermedKey } = configuration; + const {devMode, port, sslKey, sslCert, intermedKey} = configuration if (!devMode && sslKey && sslCert && intermedKey) { logger.cliRes(`==> 🌎 HTTPS server listening on port ${port}. Open up https://localhost:${port}/ in your browser.`) } else { @@ -77,4 +78,4 @@ function checkServerProtocol(configuration) { } } -module.exports = new Start(); \ No newline at end of file +module.exports = new Start() diff --git a/src/cli/tunnel.js b/src/cli/tunnel.js index cc24be082..aa7c01861 100644 --- a/src/cli/tunnel.js +++ b/src/cli/tunnel.js @@ -11,64 +11,63 @@ * */ -const BaseCLIHandler = require('./base-cli-handler'); -const constants = require('../helpers/constants'); -const fs = require('fs'); -const logger = require('../logger'); -const TunnelService = require('../services/tunnel-service'); -const CliDecorator = require('../decorators/cli-decorator'); -const Errors = require('../helpers/errors'); -const ErrorMessages = require('../helpers/error-messages'); -const AppHelper = require('../helpers/app-helper'); -const CliDataTypes = require('./cli-data-types'); +const BaseCLIHandler = require('./base-cli-handler') +const constants = require('../helpers/constants') +const fs = require('fs') +const logger = require('../logger') +const TunnelService = require('../services/tunnel-service') +const CliDecorator = require('../decorators/cli-decorator') +const Errors = require('../helpers/errors') +const ErrorMessages = require('../helpers/error-messages') +const CliDataTypes = require('./cli-data-types') class Tunnel extends BaseCLIHandler { constructor() { - super(); + super() - this.name = constants.CMD_TUNNEL; + this.name = constants.CMD_TUNNEL this.commandDefinitions = [ { name: 'command', defaultOption: true, description: 'update, list', - group: constants.CMD + group: constants.CMD, }, { name: 'username', alias: 'u', type: String, description: 'Tunnel username', - group: [constants.CMD_UPDATE] + group: [constants.CMD_UPDATE], }, { name: 'password', alias: 'p', type: String, description: 'Tunnel password', - group: [constants.CMD_UPDATE] + group: [constants.CMD_UPDATE], }, { name: 'host', alias: 's', type: String, description: 'Tunnel host address', - group: [constants.CMD_UPDATE] + group: [constants.CMD_UPDATE], }, { name: 'rsa-key', alias: 'k', type: String, description: 'Path to tunnel RSA key', - group: [constants.CMD_UPDATE] + group: [constants.CMD_UPDATE], }, { name: 'port', alias: 'o', type: CliDataTypes.Integer, description: 'Tunnel port', - group: [constants.CMD_UPDATE] + group: [constants.CMD_UPDATE], }, { name: 'iofog-uuid', alias: 'i', type: String, description: 'ioFog node UUID', - group: [constants.CMD_UPDATE] + group: [constants.CMD_UPDATE], }, { name: 'action', alias: 'a', type: String, description: 'Type of action. Can be "open" or "close"', - group: [constants.CMD_UPDATE] - } - ]; + group: [constants.CMD_UPDATE], + }, + ] this.commands = { [constants.CMD_UPDATE]: 'Update existing tunnel.', [constants.CMD_LIST]: 'List all tunnels.', @@ -77,82 +76,82 @@ class Tunnel extends BaseCLIHandler { async run(args) { try { - const tunnelCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}); + const tunnelCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}) - const command = tunnelCommand.command.command; + const command = tunnelCommand.command.command - this.validateParameters(command, this.commandDefinitions, args.argv); + this.validateParameters(command, this.commandDefinitions, args.argv) switch (command) { case constants.CMD_UPDATE: - await _executeCase(tunnelCommand, constants.CMD_UPDATE, _updateTunnel, false); - break; + await _executeCase(tunnelCommand, constants.CMD_UPDATE, _updateTunnel, false) + break case constants.CMD_LIST: - await _executeCase(tunnelCommand, constants.CMD_LIST, _tunnelList, false); - break; + await _executeCase(tunnelCommand, constants.CMD_LIST, _tunnelList, false) + break default: return this.help([]) } } catch (error) { - this.handleCLIError(error, args.argv); + this.handleCLIError(error, args.argv) } } } async function _updateTunnel(obj, user) { - const action = obj.action; - const tunnel = _createTunnelObject(obj); + const action = obj.action + const tunnel = _createTunnelObject(obj) - logger.cliReq('tunnel update', {args: tunnel}); + logger.cliReq('tunnel update', {args: tunnel}) if (tunnel.iofogUuid === undefined) { - throw new Error("Required field 'ioFog UUID' is missing."); + throw new Error('Required field \'ioFog UUID\' is missing.') } switch (action) { case 'open': - await TunnelService.openTunnel(tunnel, user, true); - break; + await TunnelService.openTunnel(tunnel, user, true) + break case 'close': - await TunnelService.closeTunnel({iofogUuid: tunnel.iofogUuid}, user); - break; + await TunnelService.closeTunnel({iofogUuid: tunnel.iofogUuid}, user) + break default: - throw new Errors.ValidationError(ErrorMessages.INVALID_ACTION_PROPERTY); + throw new Errors.ValidationError(ErrorMessages.INVALID_ACTION_PROPERTY) } - logger.cliRes('Tunnel has been updated successfully.'); + logger.cliRes('Tunnel has been updated successfully.') } async function _tunnelList() { - logger.cliReq('tunnel list'); - const tunnels = await TunnelService.findAll(); - logger.cliRes(JSON.stringify(tunnels, null, 2)); + logger.cliReq('tunnel list') + const tunnels = await TunnelService.findAll() + logger.cliRes(JSON.stringify(tunnels, null, 2)) } async function _executeCase(commands, commandName, f, isUserRequired) { try { - const obj = commands[commandName]; + const obj = commands[commandName] if (isUserRequired) { - const decoratedFunction = CliDecorator.prepareUserById(f); - await decoratedFunction(obj); + const decoratedFunction = CliDecorator.prepareUserById(f) + await decoratedFunction(obj) } else { - await f(obj); + await f(obj) } } catch (error) { - logger.error(error.message); + logger.error(error.message) } } function _createTunnelObject(cliData) { - const rsa = cliData.rsaKey ? fs.readFileSync(cliData.rsaKey, 'utf8') : ""; + const rsa = cliData.rsaKey ? fs.readFileSync(cliData.rsaKey, 'utf8') : '' return { host: cliData.host, username: cliData.username, password: cliData.password, rsakey: rsa, lport: cliData.port, - iofogUuid: cliData.iofogUuid - }; + iofogUuid: cliData.iofogUuid, + } } -module.exports = new Tunnel(); \ No newline at end of file +module.exports = new Tunnel() diff --git a/src/cli/user.js b/src/cli/user.js index d858c4f37..d94e86253 100644 --- a/src/cli/user.js +++ b/src/cli/user.js @@ -11,20 +11,20 @@ * */ -const BaseCLIHandler = require('./base-cli-handler'); -const constants = require('../helpers/constants'); -const UserService = require('../services/user-service'); -const logger = require('../logger'); -const AppHelper = require('../helpers/app-helper'); -const AuthDecorator = require('../decorators/cli-decorator'); -const Validator = require('../schemas'); +const BaseCLIHandler = require('./base-cli-handler') +const constants = require('../helpers/constants') +const UserService = require('../services/user-service') +const logger = require('../logger') +const AppHelper = require('../helpers/app-helper') +const AuthDecorator = require('../decorators/cli-decorator') +const Validator = require('../schemas') class User extends BaseCLIHandler { constructor() { - super(); + super() - this.name = constants.CMD_USER; + this.name = constants.CMD_USER this.commandDefinitions = [ { name: 'command', defaultOption: true, @@ -56,8 +56,8 @@ class User extends BaseCLIHandler { name: 'force', alias: 'F', type: Boolean, description: 'User\'s force delete', group: [constants.CMD_REMOVE], - } - ]; + }, + ] this.commands = { [constants.CMD_ADD]: 'Add a new user.', [constants.CMD_UPDATE]: 'Update existing user.', @@ -71,110 +71,109 @@ class User extends BaseCLIHandler { async run(args) { try { - const userCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}); + const userCommand = this.parseCommandLineArgs(this.commandDefinitions, {argv: args.argv, partial: false}) - const command = userCommand.command.command; + const command = userCommand.command.command - this.validateParameters(command, this.commandDefinitions, args.argv); + this.validateParameters(command, this.commandDefinitions, args.argv) switch (command) { case constants.CMD_ADD: - await _executeCase(userCommand, constants.CMD_ADD, _createUser, false); - break; + await _executeCase(userCommand, constants.CMD_ADD, _createUser, false) + break case constants.CMD_UPDATE: - await _executeCase(userCommand, constants.CMD_UPDATE, _updateUserDetails, true); - break; + await _executeCase(userCommand, constants.CMD_UPDATE, _updateUserDetails, true) + break case constants.CMD_REMOVE: - await _executeCase(userCommand, constants.CMD_REMOVE, _deleteUser, true); - break; + await _executeCase(userCommand, constants.CMD_REMOVE, _deleteUser, true) + break case constants.CMD_LIST: - await _executeCase(userCommand, constants.CMD_LIST, _getAllUsers, false); - break; + await _executeCase(userCommand, constants.CMD_LIST, _getAllUsers, false) + break case constants.CMD_GENERATE_TOKEN: - await _executeCase(userCommand, constants.CMD_GENERATE_TOKEN, _generateToken, true); - break; + await _executeCase(userCommand, constants.CMD_GENERATE_TOKEN, _generateToken, true) + break case constants.CMD_ACTIVATE: - await _executeCase(userCommand, constants.CMD_ACTIVATE, _activateUser, true); - break; + await _executeCase(userCommand, constants.CMD_ACTIVATE, _activateUser, true) + break case constants.CMD_SUSPEND: - await _executeCase(userCommand, constants.CMD_SUSPEND, _suspendUser, true); - break; + await _executeCase(userCommand, constants.CMD_SUSPEND, _suspendUser, true) + break case constants.CMD_HELP: default: return this.help([]) } } catch (error) { - this.handleCLIError(error, args.argv); + this.handleCLIError(error, args.argv) } } - } -const _executeCase = async function (userCommand, commandName, f, isUserRequired) { +const _executeCase = async function(userCommand, commandName, f, isUserRequired) { try { - const item = userCommand[commandName]; + const item = userCommand[commandName] if (isUserRequired) { - const decoratedFunction = AuthDecorator.prepareUserByEmail(f); - await decoratedFunction(item); + const decoratedFunction = AuthDecorator.prepareUserByEmail(f) + await decoratedFunction(item) } else { - await f(item); + await f(item) } } catch (error) { - logger.error(error.message); + logger.error(error.message) } -}; +} -const _createUser = async function (user) { - logger.cliReq('user add', {args: user}); - await Validator.validate(user, Validator.schemas.signUp); +const _createUser = async function(user) { + logger.cliReq('user add', {args: user}) + await Validator.validate(user, Validator.schemas.signUp) - user.password = AppHelper.encryptText(user.password, user.email); + user.password = AppHelper.encryptText(user.password, user.email) - const response = await UserService.signUp(user, true); + const response = await UserService.signUp(user, true) logger.cliRes(JSON.stringify({ - id: response.userId + id: response.userId, }), null, 2) -}; - -const _updateUserDetails = async function (userDetails, user) { - logger.cliReq('user update', {args: userDetails}); - await UserService.updateUserDetails(user, userDetails, true); - logger.cliRes('User updated successfully.'); -}; - -const _deleteUser = async function (obj, user) { - logger.cliReq('user remove', {args: {user: user.dataValues, force: obj.force}}); - await UserService.deleteUser(obj.force, user, true); - logger.cliRes('User removed successfully.'); -}; - -const _getAllUsers = async function () { - logger.cliReq('user list'); - const users = await UserService.list(true); - logger.cliRes(JSON.stringify(users, null, 2)); -}; - -const _generateToken = async function (emailObj, user) { - logger.cliReq('user generate-token', {args: user.dataValues}); - const response = await UserService.login(user, true); - logger.cliRes(JSON.stringify(response, null, 2)); -}; - -const _activateUser = async function (emailObj, user) { +} + +const _updateUserDetails = async function(userDetails, user) { + logger.cliReq('user update', {args: userDetails}) + await UserService.updateUserDetails(user, userDetails, true) + logger.cliRes('User updated successfully.') +} + +const _deleteUser = async function(obj, user) { + logger.cliReq('user remove', {args: {user: user.dataValues, force: obj.force}}) + await UserService.deleteUser(obj.force, user, true) + logger.cliRes('User removed successfully.') +} + +const _getAllUsers = async function() { + logger.cliReq('user list') + const users = await UserService.list(true) + logger.cliRes(JSON.stringify(users, null, 2)) +} + +const _generateToken = async function(emailObj, user) { + logger.cliReq('user generate-token', {args: user.dataValues}) + const response = await UserService.login(user, true) + logger.cliRes(JSON.stringify(response, null, 2)) +} + +const _activateUser = async function(emailObj, user) { const codeData = { - userId: user.id - }; - logger.cliReq('user activate', {args: codeData}); - await UserService.activateUser(codeData, true); - logger.cliRes('User activated successfully.'); -}; + userId: user.id, + } + logger.cliReq('user activate', {args: codeData}) + await UserService.activateUser(codeData, true) + logger.cliRes('User activated successfully.') +} -const _suspendUser = async function (emailObj, user) { - logger.cliReq('user suspend', {args: user.dataValues}); - await UserService.suspendUser(user, true); - logger.cliRes('User suspended successfully.'); -}; +const _suspendUser = async function(emailObj, user) { + logger.cliReq('user suspend', {args: user.dataValues}) + await UserService.suspendUser(user, true) + logger.cliRes('User suspended successfully.') +} -module.exports = new User(); +module.exports = new User() diff --git a/src/config/constants.js b/src/config/constants.js index 21dc6e958..5295095d4 100644 --- a/src/config/constants.js +++ b/src/config/constants.js @@ -30,4 +30,4 @@ module.exports = { 'Settings:FogStatusFrequencySeconds': 60, 'Diagnostics:DiagnosticDir': 'diagnostic', -} \ No newline at end of file +} diff --git a/src/config/index.js b/src/config/index.js index bc5897449..d8f8dcdc7 100644 --- a/src/config/index.js +++ b/src/config/index.js @@ -13,11 +13,11 @@ const nconf = require('nconf') const path = require('path') -const constants = require('./constants'); +const constants = require('./constants') class Config { constructor() { - nconf.env({ separator: '_', }) + nconf.env({separator: '_'}) const environment = nconf.get('NODE:ENV') || 'production' this.load(environment) } @@ -39,4 +39,4 @@ class Config { } } -module.exports = new Config() \ No newline at end of file +module.exports = new Config() diff --git a/src/controllers/agent-controller.js b/src/controllers/agent-controller.js index 7d23b7ead..c1de8c7d8 100644 --- a/src/controllers/agent-controller.js +++ b/src/controllers/agent-controller.js @@ -11,99 +11,99 @@ * */ -const AgentService = require('../services/agent-service'); -const AuthDecorator = require('../decorators/authorization-decorator'); +const AgentService = require('../services/agent-service') +const AuthDecorator = require('../decorators/authorization-decorator') -const agentProvisionEndPoint = async function (req) { - const provisionData = req.body; +const agentProvisionEndPoint = async function(req) { + const provisionData = req.body - return await AgentService.agentProvision(provisionData); -}; + return await AgentService.agentProvision(provisionData) +} -const agentDeprovisionEndPoint = async function (req, fog) { - const deprovisionData = req.body; +const agentDeprovisionEndPoint = async function(req, fog) { + const deprovisionData = req.body - return await AgentService.agentDeprovision(deprovisionData, fog); -}; + return await AgentService.agentDeprovision(deprovisionData, fog) +} -const getAgentConfigEndPoint = async function (req, fog) { - return await AgentService.getAgentConfig(fog); -}; +const getAgentConfigEndPoint = async function(req, fog) { + return await AgentService.getAgentConfig(fog) +} -const updateAgentConfigEndPoint = async function (req, fog) { - const updateData = req.body; +const updateAgentConfigEndPoint = async function(req, fog) { + const updateData = req.body - return await AgentService.updateAgentConfig(updateData, fog); -}; + return await AgentService.updateAgentConfig(updateData, fog) +} -const getAgentConfigChangesEndPoint = async function (req, fog) { - return await AgentService.getAgentConfigChanges(fog); -}; +const getAgentConfigChangesEndPoint = async function(req, fog) { + return await AgentService.getAgentConfigChanges(fog) +} -const updateAgentStatusEndPoint = async function (req, fog) { - const agentStatus = req.body; +const updateAgentStatusEndPoint = async function(req, fog) { + const agentStatus = req.body - return await AgentService.updateAgentStatus(agentStatus, fog); -}; + return await AgentService.updateAgentStatus(agentStatus, fog) +} -const getAgentMicroservicesEndPoint = async function (req, fog) { - return await AgentService.getAgentMicroservices(fog); -}; +const getAgentMicroservicesEndPoint = async function(req, fog) { + return await AgentService.getAgentMicroservices(fog) +} -const getAgentMicroserviceEndPoint = async function (req, fog) { - const microserviceUuid = req.params.microserviceUuid; +const getAgentMicroserviceEndPoint = async function(req, fog) { + const microserviceUuid = req.params.microserviceUuid - return await AgentService.getAgentMicroservice(microserviceUuid, fog); -}; + return await AgentService.getAgentMicroservice(microserviceUuid, fog) +} -const getAgentRegistriesEndPoint = async function (req, fog) { - return await AgentService.getAgentRegistries(fog); -}; +const getAgentRegistriesEndPoint = async function(req, fog) { + return await AgentService.getAgentRegistries(fog) +} -const getAgentTunnelEndPoint = async function (req, fog) { - return await AgentService.getAgentTunnel(fog); -}; +const getAgentTunnelEndPoint = async function(req, fog) { + return await AgentService.getAgentTunnel(fog) +} -const getAgentStraceEndPoint = async function (req, fog) { - return await AgentService.getAgentStrace(fog); -}; +const getAgentStraceEndPoint = async function(req, fog) { + return await AgentService.getAgentStrace(fog) +} -const updateAgentStraceEndPoint = async function (req, fog) { - const straceData = req.body; +const updateAgentStraceEndPoint = async function(req, fog) { + const straceData = req.body - return await AgentService.updateAgentStrace(straceData, fog); -}; + return await AgentService.updateAgentStrace(straceData, fog) +} -const getAgentChangeVersionCommandEndPoint = async function (req, fog) { - return await AgentService.getAgentChangeVersionCommand(fog); -}; +const getAgentChangeVersionCommandEndPoint = async function(req, fog) { + return await AgentService.getAgentChangeVersionCommand(fog) +} -const updateHalHardwareInfoEndPoint = async function (req, fog) { - const hardwareData = req.body; +const updateHalHardwareInfoEndPoint = async function(req, fog) { + const hardwareData = req.body - return await AgentService.updateHalHardwareInfo(hardwareData, fog); -}; + return await AgentService.updateHalHardwareInfo(hardwareData, fog) +} -const updateHalUsbInfoEndPoint = async function (req, fog) { - const usbData = req.body; +const updateHalUsbInfoEndPoint = async function(req, fog) { + const usbData = req.body - return await AgentService.updateHalUsbInfo(usbData, fog); -}; + return await AgentService.updateHalUsbInfo(usbData, fog) +} -const deleteNodeEndPoint = async function (req, fog) { - return await AgentService.deleteNode(fog); -}; +const deleteNodeEndPoint = async function(req, fog) { + return await AgentService.deleteNode(fog) +} -const getImageSnapshotEndPoint = async function (req, fog) { - return await AgentService.getImageSnapshot(fog); -}; +const getImageSnapshotEndPoint = async function(req, fog) { + return await AgentService.getImageSnapshot(fog) +} -const putImageSnapshotEndPoint = async function (req, fog) { - return await AgentService.putImageSnapshot(req, fog); -}; +const putImageSnapshotEndPoint = async function(req, fog) { + return await AgentService.putImageSnapshot(req, fog) +} async function postTrackingEndPoint(req, fog) { - const events = req.body.events; + const events = req.body.events return await AgentService.postTracking(events, fog) } @@ -126,5 +126,5 @@ module.exports = { deleteNodeEndPoint: AuthDecorator.checkFogToken(deleteNodeEndPoint), getImageSnapshotEndPoint: AuthDecorator.checkFogToken(getImageSnapshotEndPoint), putImageSnapshotEndPoint: AuthDecorator.checkFogToken(putImageSnapshotEndPoint), - postTrackingEndPoint: AuthDecorator.checkFogToken(postTrackingEndPoint) -}; \ No newline at end of file + postTrackingEndPoint: AuthDecorator.checkFogToken(postTrackingEndPoint), +} diff --git a/src/controllers/catalog-controller.js b/src/controllers/catalog-controller.js index de38287b2..e5fb4e484 100644 --- a/src/controllers/catalog-controller.js +++ b/src/controllers/catalog-controller.js @@ -11,33 +11,33 @@ * */ -const CatalogService = require('../services/catalog-service'); -const AuthDecorator = require('./../decorators/authorization-decorator'); +const CatalogService = require('../services/catalog-service') +const AuthDecorator = require('./../decorators/authorization-decorator') -const createCatalogItemEndPoint = async function (req, user) { - return await CatalogService.createCatalogItem(req.body, user); -}; +const createCatalogItemEndPoint = async function(req, user) { + return await CatalogService.createCatalogItem(req.body, user) +} -const listCatalogItemsEndPoint = async function (req, user) { - return await CatalogService.listCatalogItems(user, false); -}; +const listCatalogItemsEndPoint = async function(req, user) { + return await CatalogService.listCatalogItems(user, false) +} -const listCatalogItemEndPoint = async function (req, user) { - return await CatalogService.getCatalogItem(req.params.id, user, false); -}; +const listCatalogItemEndPoint = async function(req, user) { + return await CatalogService.getCatalogItem(req.params.id, user, false) +} -const deleteCatalogItemEndPoint = async function (req, user) { - await CatalogService.deleteCatalogItem(req.params.id, user, false); -}; +const deleteCatalogItemEndPoint = async function(req, user) { + await CatalogService.deleteCatalogItem(req.params.id, user, false) +} -const updateCatalogItemEndPoint = async function (req, user) { - await CatalogService.updateCatalogItem(req.params.id, req.body, user, false); -}; +const updateCatalogItemEndPoint = async function(req, user) { + await CatalogService.updateCatalogItem(req.params.id, req.body, user, false) +} module.exports = { createCatalogItemEndPoint: AuthDecorator.checkAuthToken(createCatalogItemEndPoint), listCatalogItemsEndPoint: AuthDecorator.checkAuthToken(listCatalogItemsEndPoint), listCatalogItemEndPoint: AuthDecorator.checkAuthToken(listCatalogItemEndPoint), deleteCatalogItemEndPoint: AuthDecorator.checkAuthToken(deleteCatalogItemEndPoint), - updateCatalogItemEndPoint: AuthDecorator.checkAuthToken(updateCatalogItemEndPoint) -}; \ No newline at end of file + updateCatalogItemEndPoint: AuthDecorator.checkAuthToken(updateCatalogItemEndPoint), +} diff --git a/src/controllers/controller.js b/src/controllers/controller.js index 00b7e0990..a8952225e 100644 --- a/src/controllers/controller.js +++ b/src/controllers/controller.js @@ -11,24 +11,24 @@ * */ -const ControllerService = require('../services/controller-service'); +const ControllerService = require('../services/controller-service') -const statusControllerEndPoint = async function (req) { - return await ControllerService.statusController(false); -}; +const statusControllerEndPoint = async function(req) { + return await ControllerService.statusController(false) +} -const emailActivationEndPoint = async function (req) { - return await ControllerService.emailActivation(false); -}; +const emailActivationEndPoint = async function(req) { + return await ControllerService.emailActivation(false) +} -const fogTypesEndPoint = async function (req) { - return await ControllerService.getFogTypes(false); -}; +const fogTypesEndPoint = async function(req) { + return await ControllerService.getFogTypes(false) +} module.exports = { statusControllerEndPoint: statusControllerEndPoint, emailActivationEndPoint: emailActivationEndPoint, - fogTypesEndPoint: fogTypesEndPoint -}; \ No newline at end of file + fogTypesEndPoint: fogTypesEndPoint, +} diff --git a/src/controllers/diagnostic-controller.js b/src/controllers/diagnostic-controller.js index 2f54409fe..c1fbf6b56 100644 --- a/src/controllers/diagnostic-controller.js +++ b/src/controllers/diagnostic-controller.js @@ -11,33 +11,33 @@ * */ -const DiagnosticService = require('../services/diagnostic-service'); -const AuthDecorator = require('./../decorators/authorization-decorator'); +const DiagnosticService = require('../services/diagnostic-service') +const AuthDecorator = require('./../decorators/authorization-decorator') -const changeMicroserviceStraceStateEndPoint = async function (req, user) { - return await DiagnosticService.changeMicroserviceStraceState(req.params.uuid, req.body, user, false); -}; +const changeMicroserviceStraceStateEndPoint = async function(req, user) { + return await DiagnosticService.changeMicroserviceStraceState(req.params.uuid, req.body, user, false) +} -const getMicroserviceStraceDataEndPoint = async function (req, user) { - return await DiagnosticService.getMicroserviceStraceData(req.params.uuid, req.query, user, false); -}; +const getMicroserviceStraceDataEndPoint = async function(req, user) { + return await DiagnosticService.getMicroserviceStraceData(req.params.uuid, req.query, user, false) +} -const postMicroserviceStraceDataToFtpEndPoint = async function (req, user) { - return await DiagnosticService.postMicroserviceStraceDatatoFtp(req.params.uuid, req.body, user, false); -}; +const postMicroserviceStraceDataToFtpEndPoint = async function(req, user) { + return await DiagnosticService.postMicroserviceStraceDatatoFtp(req.params.uuid, req.body, user, false) +} -const createMicroserviceImageSnapshotEndPoint = async function (req, user) { - return await DiagnosticService.postMicroserviceImageSnapshotCreate(req.params.uuid, user, false); -}; +const createMicroserviceImageSnapshotEndPoint = async function(req, user) { + return await DiagnosticService.postMicroserviceImageSnapshotCreate(req.params.uuid, user, false) +} -const getMicroserviceImageSnapshotEndPoint = async function (req, user) { - return await DiagnosticService.getMicroserviceImageSnapshot(req.params.uuid, user, false); -}; +const getMicroserviceImageSnapshotEndPoint = async function(req, user) { + return await DiagnosticService.getMicroserviceImageSnapshot(req.params.uuid, user, false) +} module.exports = { changeMicroserviceStraceStateEndPoint: AuthDecorator.checkAuthToken(changeMicroserviceStraceStateEndPoint), getMicroserviceStraceDataEndPoint: AuthDecorator.checkAuthToken(getMicroserviceStraceDataEndPoint), postMicroserviceStraceDataToFtpEndPoint: AuthDecorator.checkAuthToken(postMicroserviceStraceDataToFtpEndPoint), createMicroserviceImageSnapshotEndPoint: AuthDecorator.checkAuthToken(createMicroserviceImageSnapshotEndPoint), - getMicroserviceImageSnapshotEndPoint: AuthDecorator.checkAuthToken(getMicroserviceImageSnapshotEndPoint) -}; + getMicroserviceImageSnapshotEndPoint: AuthDecorator.checkAuthToken(getMicroserviceImageSnapshotEndPoint), +} diff --git a/src/controllers/flow-controller.js b/src/controllers/flow-controller.js index c243f953b..b53d44f2a 100644 --- a/src/controllers/flow-controller.js +++ b/src/controllers/flow-controller.js @@ -11,42 +11,42 @@ * */ -const AuthDecorator = require('./../decorators/authorization-decorator'); -const FlowService = require('../services/flow-service'); +const AuthDecorator = require('./../decorators/authorization-decorator') +const FlowService = require('../services/flow-service') -const createFlowEndPoint = async function (req, user) { - const flow = req.body; +const createFlowEndPoint = async function(req, user) { + const flow = req.body return await FlowService.createFlow(flow, user, false) -}; +} -const getFlowsByUserEndPoint = async function (req, user) { +const getFlowsByUserEndPoint = async function(req, user) { return await FlowService.getUserFlows(user, false) -}; +} -const getFlowEndPoint = async function (req, user) { - const flowId = req.params.id; +const getFlowEndPoint = async function(req, user) { + const flowId = req.params.id return await FlowService.getFlowWithTransaction(flowId, user, false) -}; +} -const updateFlowEndPoint = async function (req, user) { - const flow = req.body; - const flowId = req.params.id; +const updateFlowEndPoint = async function(req, user) { + const flow = req.body + const flowId = req.params.id return await FlowService.updateFlow(flow, flowId, user, false) -}; +} -const deleteFlowEndPoint = async function (req, user) { - const flowId = req.params.id; +const deleteFlowEndPoint = async function(req, user) { + const flowId = req.params.id return await FlowService.deleteFlow(flowId, user, false) -}; +} module.exports = { createFlowEndPoint: AuthDecorator.checkAuthToken(createFlowEndPoint), getFlowsByUserEndPoint: AuthDecorator.checkAuthToken(getFlowsByUserEndPoint), getFlowEndPoint: AuthDecorator.checkAuthToken(getFlowEndPoint), updateFlowEndPoint: AuthDecorator.checkAuthToken(updateFlowEndPoint), - deleteFlowEndPoint: AuthDecorator.checkAuthToken(deleteFlowEndPoint) -}; \ No newline at end of file + deleteFlowEndPoint: AuthDecorator.checkAuthToken(deleteFlowEndPoint), +} diff --git a/src/controllers/iofog-controller.js b/src/controllers/iofog-controller.js index b323a6584..c1795aa74 100644 --- a/src/controllers/iofog-controller.js +++ b/src/controllers/iofog-controller.js @@ -11,45 +11,45 @@ * */ -const AuthDecorator = require('../decorators/authorization-decorator'); -const FogService = require('../services/iofog-service'); -const qs = require('qs'); +const AuthDecorator = require('../decorators/authorization-decorator') +const FogService = require('../services/iofog-service') +const qs = require('qs') async function createFogEndPoint(req, user) { - const newFog = req.body; + const newFog = req.body return await FogService.createFog(newFog, user, false) } async function updateFogEndPoint(req, user) { - const updateFog = req.body; - updateFog.uuid = req.params.uuid; + const updateFog = req.body + updateFog.uuid = req.params.uuid return await FogService.updateFog(updateFog, user, false) } async function deleteFogEndPoint(req, user) { const deleteFog = { - uuid: req.params.uuid - }; + uuid: req.params.uuid, + } return await FogService.deleteFog(deleteFog, user, false) } async function getFogEndPoint(req, user) { const getFog = { - uuid: req.params.uuid - }; + uuid: req.params.uuid, + } return await FogService.getFogWithTransaction(getFog, user, false) } async function getFogListEndPoint(req, user) { - const query = qs.parse(req.query); + const query = qs.parse(req.query) return await FogService.getFogList(query.filters, user, false) } async function generateProvisionKeyEndPoint(req, user) { const fog = { - uuid: req.params.uuid - }; + uuid: req.params.uuid, + } return await FogService.generateProvisioningKey(fog, user, false) } @@ -57,32 +57,32 @@ async function generateProvisionKeyEndPoint(req, user) { async function setFogVersionCommandEndPoint(req, user) { const fogVersionCommand = { uuid: req.params.uuid, - versionCommand: req.params.versionCommand - }; + versionCommand: req.params.versionCommand, + } return await FogService.setFogVersionCommand(fogVersionCommand, user, false) } async function setFogRebootCommandEndPoint(req, user) { const fog = { - uuid: req.params.uuid - }; + uuid: req.params.uuid, + } return await FogService.setFogRebootCommand(fog, user, false) } async function getHalHardwareInfoEndPoint(req, user) { const uuidObj = { - uuid: req.params.uuid - }; - return await FogService.getHalHardwareInfo(uuidObj, user, false); + uuid: req.params.uuid, + } + return await FogService.getHalHardwareInfo(uuidObj, user, false) } async function getHalUsbInfoEndPoint(req, user) { const uuidObj = { - uuid: req.params.uuid - }; - return await FogService.getHalUsbInfo(uuidObj, user, false); + uuid: req.params.uuid, + } + return await FogService.getHalUsbInfo(uuidObj, user, false) } module.exports = { @@ -95,5 +95,5 @@ module.exports = { setFogVersionCommandEndPoint: AuthDecorator.checkAuthToken(setFogVersionCommandEndPoint), setFogRebootCommandEndPoint: AuthDecorator.checkAuthToken(setFogRebootCommandEndPoint), getHalHardwareInfoEndPoint: AuthDecorator.checkAuthToken(getHalHardwareInfoEndPoint), - getHalUsbInfoEndPoint: AuthDecorator.checkAuthToken(getHalUsbInfoEndPoint) -}; \ No newline at end of file + getHalUsbInfoEndPoint: AuthDecorator.checkAuthToken(getHalUsbInfoEndPoint), +} diff --git a/src/controllers/microservices-controller.js b/src/controllers/microservices-controller.js index d33db4f99..12a27b7ec 100644 --- a/src/controllers/microservices-controller.js +++ b/src/controllers/microservices-controller.js @@ -11,90 +11,90 @@ * */ -const AuthDecorator = require('./../decorators/authorization-decorator'); -const MicroservicesService = require('../services/microservices-service'); +const AuthDecorator = require('./../decorators/authorization-decorator') +const MicroservicesService = require('../services/microservices-service') -const createMicroserviceOnFogEndPoint = async function (req, user) { - const microservice = req.body; +const createMicroserviceOnFogEndPoint = async function(req, user) { + const microservice = req.body return await MicroservicesService.createMicroservice(microservice, user, false) -}; +} -const getMicroserviceEndPoint = async function (req, user) { - const microserviceUuid = req.params.uuid; +const getMicroserviceEndPoint = async function(req, user) { + const microserviceUuid = req.params.uuid return await MicroservicesService.getMicroservice(microserviceUuid, user, false) -}; +} -const updateMicroserviceEndPoint = async function (req, user) { - const microservice = req.body; - const microserviceUuid = req.params.uuid; +const updateMicroserviceEndPoint = async function(req, user) { + const microservice = req.body + const microserviceUuid = req.params.uuid return await MicroservicesService.updateMicroservice(microserviceUuid, microservice, user, false) -}; +} -const deleteMicroserviceEndPoint = async function (req, user) { - const microserviceUuid = req.params.uuid; - const microserviceData = req.body || {}; +const deleteMicroserviceEndPoint = async function(req, user) { + const microserviceUuid = req.params.uuid + const microserviceData = req.body || {} return await MicroservicesService.deleteMicroservice(microserviceUuid, microserviceData, user, false) -}; +} -const getMicroservicesByFlowEndPoint = async function (req, user) { - const flowId = req.query.flowId; +const getMicroservicesByFlowEndPoint = async function(req, user) { + const flowId = req.query.flowId return await MicroservicesService.listMicroservices(flowId, user, false) -}; +} -const createMicroserviceRouteEndPoint = async function (req, user) { - const sourceUuid = req.params.uuid; - const destUuid = req.params.receiverUuid; +const createMicroserviceRouteEndPoint = async function(req, user) { + const sourceUuid = req.params.uuid + const destUuid = req.params.receiverUuid return await MicroservicesService.createRoute(sourceUuid, destUuid, user, false) -}; +} -const deleteMicroserviceRouteEndPoint = async function (req, user) { - const sourceUuid = req.params.uuid; - const destUuid = req.params.receiverUuid; +const deleteMicroserviceRouteEndPoint = async function(req, user) { + const sourceUuid = req.params.uuid + const destUuid = req.params.receiverUuid return await MicroservicesService.deleteRoute(sourceUuid, destUuid, user, false) -}; +} -const createMicroservicePortMappingEndPoint = async function (req, user) { - const uuid = req.params.uuid; - const portMappingData = req.body; +const createMicroservicePortMappingEndPoint = async function(req, user) { + const uuid = req.params.uuid + const portMappingData = req.body return await MicroservicesService.createPortMapping(uuid, portMappingData, user, false) -}; +} -const deleteMicroservicePortMappingEndPoint = async function (req, user) { - const uuid = req.params.uuid; - const internalPort = req.params.internalPort; +const deleteMicroservicePortMappingEndPoint = async function(req, user) { + const uuid = req.params.uuid + const internalPort = req.params.internalPort return await MicroservicesService.deletePortMapping(uuid, internalPort, user, false) -}; +} -const listMicroservicePortMappingsEndPoint = async function (req, user) { - const uuid = req.params.uuid; - const ports = await MicroservicesService.listMicroservicePortMappings(uuid, user, false); +const listMicroservicePortMappingsEndPoint = async function(req, user) { + const uuid = req.params.uuid + const ports = await MicroservicesService.listMicroservicePortMappings(uuid, user, false) return { - ports: ports + ports: ports, } -}; +} -const createMicroserviceVolumeMappingEndPoint = async function (req, user) { - const microserviceUuid = req.params.uuid; - const volumeMappingData = req.body; - const volumeMapping = await MicroservicesService.createVolumeMapping(microserviceUuid, volumeMappingData, user, false); +const createMicroserviceVolumeMappingEndPoint = async function(req, user) { + const microserviceUuid = req.params.uuid + const volumeMappingData = req.body + const volumeMapping = await MicroservicesService.createVolumeMapping(microserviceUuid, volumeMappingData, user, false) return { - id: volumeMapping.id + id: volumeMapping.id, } -}; +} -const listMicroserviceVolumeMappingsEndPoint = async function (req, user) { - const uuid = req.params.uuid; - const volumeMappings = await MicroservicesService.listVolumeMappings(uuid, user, false); +const listMicroserviceVolumeMappingsEndPoint = async function(req, user) { + const uuid = req.params.uuid + const volumeMappings = await MicroservicesService.listVolumeMappings(uuid, user, false) return { - volumeMappings: volumeMappings + volumeMappings: volumeMappings, } -}; +} -const deleteMicroserviceVolumeMappingEndPoint = async function (req, user) { - const uuid = req.params.uuid; - const id = req.params.id; - return await MicroservicesService.deleteVolumeMapping(uuid, id, user, false); -}; +const deleteMicroserviceVolumeMappingEndPoint = async function(req, user) { + const uuid = req.params.uuid + const id = req.params.id + return await MicroservicesService.deleteVolumeMapping(uuid, id, user, false) +} module.exports = { createMicroserviceOnFogEndPoint: AuthDecorator.checkAuthToken(createMicroserviceOnFogEndPoint), @@ -109,5 +109,5 @@ module.exports = { getMicroservicePortMappingListEndPoint: AuthDecorator.checkAuthToken(listMicroservicePortMappingsEndPoint), createMicroserviceVolumeMappingEndPoint: AuthDecorator.checkAuthToken(createMicroserviceVolumeMappingEndPoint), listMicroserviceVolumeMappingsEndPoint: AuthDecorator.checkAuthToken(listMicroserviceVolumeMappingsEndPoint), - deleteMicroserviceVolumeMappingEndPoint: AuthDecorator.checkAuthToken(deleteMicroserviceVolumeMappingEndPoint) -}; \ No newline at end of file + deleteMicroserviceVolumeMappingEndPoint: AuthDecorator.checkAuthToken(deleteMicroserviceVolumeMappingEndPoint), +} diff --git a/src/controllers/registry-controller.js b/src/controllers/registry-controller.js index 8fc14e832..01f43be12 100644 --- a/src/controllers/registry-controller.js +++ b/src/controllers/registry-controller.js @@ -11,34 +11,34 @@ * */ -const AuthDecorator = require('../decorators/authorization-decorator'); -const RegistryService = require('../services/registry-service'); +const AuthDecorator = require('../decorators/authorization-decorator') +const RegistryService = require('../services/registry-service') -const createRegistryEndPoint = async function (req, user) { - const registry = req.body; - return await RegistryService.createRegistry(registry, user); -}; +const createRegistryEndPoint = async function(req, user) { + const registry = req.body + return await RegistryService.createRegistry(registry, user) +} -const getRegistriesEndPoint = async function (req, user) { - return await RegistryService.findRegistries(user, false); -}; +const getRegistriesEndPoint = async function(req, user) { + return await RegistryService.findRegistries(user, false) +} -const deleteRegistryEndPoint = async function (req, user) { +const deleteRegistryEndPoint = async function(req, user) { const deleteRegistry = { - id: parseInt(req.params.id) - }; - return await RegistryService.deleteRegistry(deleteRegistry, user, false); -}; + id: parseInt(req.params.id), + } + return await RegistryService.deleteRegistry(deleteRegistry, user, false) +} -const updateRegistryEndPoint = async function (req, user) { - const registry = req.body; - const registryId = req.params.id; +const updateRegistryEndPoint = async function(req, user) { + const registry = req.body + const registryId = req.params.id return await RegistryService.updateRegistry(registry, registryId, user, false) -}; +} module.exports = { createRegistryEndPoint: AuthDecorator.checkAuthToken(createRegistryEndPoint), getRegistriesEndPoint: AuthDecorator.checkAuthToken(getRegistriesEndPoint), deleteRegistryEndPoint: AuthDecorator.checkAuthToken(deleteRegistryEndPoint), - updateRegistryEndPoint: AuthDecorator.checkAuthToken(updateRegistryEndPoint) -}; \ No newline at end of file + updateRegistryEndPoint: AuthDecorator.checkAuthToken(updateRegistryEndPoint), +} diff --git a/src/controllers/tunnel-controller.js b/src/controllers/tunnel-controller.js index c8a1825b7..162127790 100644 --- a/src/controllers/tunnel-controller.js +++ b/src/controllers/tunnel-controller.js @@ -11,37 +11,37 @@ * */ -const AuthDecorator = require('../decorators/authorization-decorator'); -const TunnelService = require('../services/tunnel-service'); -const Errors = require('../helpers/errors'); -const ErrorMessages = require('../helpers/error-messages'); +const AuthDecorator = require('../decorators/authorization-decorator') +const TunnelService = require('../services/tunnel-service') +const Errors = require('../helpers/errors') +const ErrorMessages = require('../helpers/error-messages') -const manageTunnelEndPoint = async function (req, user) { - const action = req.body.action; +const manageTunnelEndPoint = async function(req, user) { + const action = req.body.action const tunnelData = { - iofogUuid: req.params.id - }; + iofogUuid: req.params.id, + } switch (action) { case 'open': - await TunnelService.openTunnel(tunnelData, user, false); - break; + await TunnelService.openTunnel(tunnelData, user, false) + break case 'close': - await TunnelService.closeTunnel(tunnelData, user); - break; + await TunnelService.closeTunnel(tunnelData, user) + break default: - throw new Errors.ValidationError(ErrorMessages.INVALID_ACTION_PROPERTY); + throw new Errors.ValidationError(ErrorMessages.INVALID_ACTION_PROPERTY) } -}; +} -const getTunnelEndPoint = async function (req, user) { +const getTunnelEndPoint = async function(req, user) { const tunnelData = { - iofogUuid: req.params.id - }; - return await TunnelService.findTunnel(tunnelData, user); -}; + iofogUuid: req.params.id, + } + return await TunnelService.findTunnel(tunnelData, user) +} module.exports = { manageTunnelEndPoint: AuthDecorator.checkAuthToken(manageTunnelEndPoint), getTunnelEndPoint: AuthDecorator.checkAuthToken(getTunnelEndPoint), -}; \ No newline at end of file +} diff --git a/src/controllers/user-controller.js b/src/controllers/user-controller.js index 79496fe35..0acaf709b 100644 --- a/src/controllers/user-controller.js +++ b/src/controllers/user-controller.js @@ -11,84 +11,84 @@ * */ -const UserService = require('../services/user-service'); -const AuthDecorator = require('../decorators/authorization-decorator'); -const AppHelper = require('../helpers/app-helper'); +const UserService = require('../services/user-service') +const AuthDecorator = require('../decorators/authorization-decorator') +const AppHelper = require('../helpers/app-helper') -const Validator = require('../schemas'); +const Validator = require('../schemas') -const userSignupEndPoint = async function (req) { - const user = req.body; +const userSignupEndPoint = async function(req) { + const user = req.body - await Validator.validate(user, Validator.schemas.signUp); + await Validator.validate(user, Validator.schemas.signUp) - const encryptedPassword = AppHelper.encryptText(user.password, user.email); + const encryptedPassword = AppHelper.encryptText(user.password, user.email) const newUser = { firstName: user.firstName, lastName: user.lastName, email: user.email, - password: encryptedPassword - }; - return await UserService.signUp(newUser, false); -}; + password: encryptedPassword, + } + return await UserService.signUp(newUser, false) +} -const userLoginEndPoint = async function (req) { - const user = req.body; +const userLoginEndPoint = async function(req) { + const user = req.body - await Validator.validate(user, Validator.schemas.login); + await Validator.validate(user, Validator.schemas.login) const credentials = { email: user.email, - password: user.password - }; + password: user.password, + } - return await UserService.login(credentials, false); -}; + return await UserService.login(credentials, false) +} -const resendActivationEndPoint = async function (req) { - const emailData = req.query; - return await UserService.resendActivation(emailData, false); -}; +const resendActivationEndPoint = async function(req) { + const emailData = req.query + return await UserService.resendActivation(emailData, false) +} -const activateUserAccountEndPoint = async function (req) { - const codeData = req.body; +const activateUserAccountEndPoint = async function(req) { + const codeData = req.body - await UserService.activateUser(codeData, false); -}; + await UserService.activateUser(codeData, false) +} -const userLogoutEndPoint = async function (req, user) { - return await UserService.logout(user, false); -}; +const userLogoutEndPoint = async function(req, user) { + return await UserService.logout(user, false) +} -const getUserProfileEndPoint = async function (req, user) { +const getUserProfileEndPoint = async function(req, user) { return { firstName: user.firstName, lastName: user.lastName, - email: user.email + email: user.email, } -}; +} -const updateUserProfileEndPoint = async function (req, user) { - const profileData = req.body; - return await UserService.updateUserDetails(user, profileData, false); -}; +const updateUserProfileEndPoint = async function(req, user) { + const profileData = req.body + return await UserService.updateUserDetails(user, profileData, false) +} -const deleteUserProfileEndPoint = async function (req, user) { - return await UserService.deleteUser(req.body.force, user, false); -}; +const deleteUserProfileEndPoint = async function(req, user) { + return await UserService.deleteUser(req.body.force, user, false) +} -const updateUserPasswordEndPoint = async function (req, user) { - const passwordUpdates = req.body; +const updateUserPasswordEndPoint = async function(req, user) { + const passwordUpdates = req.body - await Validator.validate(passwordUpdates, Validator.schemas.updatePassword); + await Validator.validate(passwordUpdates, Validator.schemas.updatePassword) - return await UserService.updateUserPassword(passwordUpdates, user, false); -}; + return await UserService.updateUserPassword(passwordUpdates, user, false) +} -const resetUserPasswordEndPoint = async function (req) { - const emailObj = req.body; - return await UserService.resetUserPassword(emailObj, false); -}; +const resetUserPasswordEndPoint = async function(req) { + const emailObj = req.body + return await UserService.resetUserPassword(emailObj, false) +} module.exports = { userSignupEndPoint: userSignupEndPoint, @@ -100,5 +100,5 @@ module.exports = { updateUserProfileEndPoint: AuthDecorator.checkAuthToken(updateUserProfileEndPoint), deleteUserProfileEndPoint: AuthDecorator.checkAuthToken(deleteUserProfileEndPoint), updateUserPasswordEndPoint: AuthDecorator.checkAuthToken(updateUserPasswordEndPoint), - resetUserPasswordEndPoint: resetUserPasswordEndPoint -}; \ No newline at end of file + resetUserPasswordEndPoint: resetUserPasswordEndPoint, +} diff --git a/src/daemon.js b/src/daemon.js index 355bc118a..ccf1abd35 100644 --- a/src/daemon.js +++ b/src/daemon.js @@ -11,35 +11,35 @@ * */ -const daemonize = require('daemonize2'); -const logger = require('./logger'); +const daemonize = require('daemonize2') +const logger = require('./logger') const daemon = daemonize.setup({ main: 'server.js', name: 'iofog-controller', pidfile: 'iofog-controller.pid', silent: true, -}); +}) daemon - .on('starting', async () => { - logger.info('Starting iofog-controller...'); - }) - .on('stopping', () => { - logger.info('Stopping iofog-controller...') - }) - .on('stopped', (pid) => { - logger.info('iofog-controller stopped.') - }) - .on('running', (pid) => { - logger.info('iofog-controller already running. PID: ' + pid) - }) - .on('notrunning', () => { - logger.info('iofog-controller is not running') - }) - .on('error', (err) => { - logger.error('iofog-controller failed to start: ' + err.message) - }); + .on('starting', async () => { + logger.info('Starting iofog-controller...') + }) + .on('stopping', () => { + logger.info('Stopping iofog-controller...') + }) + .on('stopped', (pid) => { + logger.info('iofog-controller stopped.') + }) + .on('running', (pid) => { + logger.info('iofog-controller already running. PID: ' + pid) + }) + .on('notrunning', () => { + logger.info('iofog-controller is not running') + }) + .on('error', (err) => { + logger.error('iofog-controller failed to start: ' + err.message) + }) -module.exports = daemon; \ No newline at end of file +module.exports = daemon diff --git a/src/decorators/authorization-decorator.js b/src/decorators/authorization-decorator.js index 578456d54..3c03ebcb4 100644 --- a/src/decorators/authorization-decorator.js +++ b/src/decorators/authorization-decorator.js @@ -17,68 +17,68 @@ const AccessTokenManager = require('../sequelize/managers/access-token-manager') const FogManager = require('../sequelize/managers/iofog-manager') const FogAccessTokenManager = require('../sequelize/managers/iofog-access-token-manager') const Errors = require('../helpers/errors') -const { isTest } = require('../helpers/app-helper'); +const {isTest} = require('../helpers/app-helper') function checkAuthToken(f) { - return async function() { + return async function(...fArgs) { if (isTest()) { - return await f.apply(this, arguments); + return await f.apply(this, fArgs) } - const fArgs = Array.prototype.slice.call(arguments); - const req = fArgs[0]; - const token = req.headers.authorization; + const req = fArgs[0] + const token = req.headers.authorization - const user = await UserManager.checkAuthentication(token); + const user = await UserManager.checkAuthentication(token) if (!user) { - logger.error('token ' + token + ' incorrect'); - throw new Errors.AuthenticationError('authorization failed'); + logger.error('token ' + token + ' incorrect') + throw new Errors.AuthenticationError('authorization failed') } if (Date.now() > user.accessToken.expirationTime) { - logger.error('token ' + token + ' expired'); - throw new Errors.AuthenticationError('token expired'); + logger.error('token ' + token + ' expired') + throw new Errors.AuthenticationError('token expired') } - fArgs.push(user); - AccessTokenManager.updateExpirationTime(user.accessToken.id, user.accessToken.expirationTime + config.get('Settings:UserTokenExpirationIntervalSeconds') * 1000); - return await f.apply(this, fArgs); + fArgs.push(user) + AccessTokenManager.updateExpirationTime(user.accessToken.id, user.accessToken.expirationTime + + config.get('Settings:UserTokenExpirationIntervalSeconds') * 1000) + return await f.apply(this, fArgs) } } function checkFogToken(f) { - return async function() { + return async function(...fArgs) { if (isTest()) { - return await f.apply(this, arguments); + return await f.apply(this, fArgs) } - const fArgs = Array.prototype.slice.call(arguments); - const req = fArgs[0]; - const token = req.headers.authorization; + const req = fArgs[0] + const token = req.headers.authorization - const fog = await FogManager.checkToken(token); + const fog = await FogManager.checkToken(token) if (!fog) { - logger.error('token ' + token + ' incorrect'); - throw new Errors.AuthenticationError('authorization failed'); + logger.error('token ' + token + ' incorrect') + throw new Errors.AuthenticationError('authorization failed') } if (Date.now() > fog.accessToken.expirationTime) { - logger.error('token ' + token + ' expired'); - throw new Errors.AuthenticationError('token expired'); + logger.error('token ' + token + ' expired') + throw new Errors.AuthenticationError('token expired') } - fArgs.push(fog); + fArgs.push(fog) - FogAccessTokenManager.updateExpirationTime(fog.accessToken.id, fog.accessToken.expirationTime + config.get('Settings:FogTokenExpirationIntervalSeconds') * 1000); + FogAccessTokenManager.updateExpirationTime(fog.accessToken.id, fog.accessToken.expirationTime + + config.get('Settings:FogTokenExpirationIntervalSeconds') * 1000) - const timestamp = Date.now(); - await FogManager.updateLastActive(fog.uuid, timestamp); + const timestamp = Date.now() + await FogManager.updateLastActive(fog.uuid, timestamp) - return await f.apply(this, fArgs); + return await f.apply(this, fArgs) } } module.exports = { checkAuthToken: checkAuthToken, - checkFogToken: checkFogToken -}; \ No newline at end of file + checkFogToken: checkFogToken, +} diff --git a/src/decorators/cli-decorator.js b/src/decorators/cli-decorator.js index 5e5efb53e..12f9fa76c 100644 --- a/src/decorators/cli-decorator.js +++ b/src/decorators/cli-decorator.js @@ -11,20 +11,18 @@ * */ -const logger = require('../logger'); -const config = require('../config'); -const UserManager = require('../sequelize/managers/user-manager'); -const AccessTokenManager = require('../sequelize/managers/access-token-manager'); -const Errors = require('../helpers/errors'); -const { isTest } = require('../helpers/app-helper'); +const logger = require('../logger') +const UserManager = require('../sequelize/managers/user-manager') +const Errors = require('../helpers/errors') +const {isTest} = require('../helpers/app-helper') function prepareUserById(f) { - return async function() { + return async function(...args) { if (isTest()) { - return await f.apply(this, arguments); + return await f.apply(this, args) } - const fArgs = Array.prototype.slice.call(arguments) + const fArgs = Array.prototype.slice.call(args) const obj = fArgs[0] const userId = obj.userId @@ -33,7 +31,7 @@ function prepareUserById(f) { throw new Errors.AuthenticationError('user id does not exist') } - delete obj.userId + delete obj.userId fArgs.push(user) return await f.apply(this, fArgs) @@ -41,12 +39,12 @@ function prepareUserById(f) { } function prepareUserByEmail(f) { - return async function() { + return async function(...args) { if (isTest()) { - return await f.apply(this, arguments); + return await f.apply(this, args) } - const fArgs = Array.prototype.slice.call(arguments) + const fArgs = Array.prototype.slice.call(args) const obj = fArgs[0] const email = obj.email @@ -57,7 +55,7 @@ function prepareUserByEmail(f) { throw new Errors.AuthenticationError('user email does not exist') } - delete obj.email + delete obj.email fArgs.push(user) return await f.apply(this, fArgs) @@ -66,6 +64,6 @@ function prepareUserByEmail(f) { module.exports = { prepareUserById: prepareUserById, - prepareUserByEmail: prepareUserByEmail + prepareUserByEmail: prepareUserByEmail, -} \ No newline at end of file +} diff --git a/src/decorators/response-decorator.js b/src/decorators/response-decorator.js index 2b2a8b448..1faa92b93 100644 --- a/src/decorators/response-decorator.js +++ b/src/decorators/response-decorator.js @@ -10,63 +10,63 @@ * ******************************************************************************* * */ -const logger = require('../logger'); -const { isTest } = require('../helpers/app-helper'); +const logger = require('../logger') +const {isTest} = require('../helpers/app-helper') function handleErrors(f, successCode, errorsCodes) { - return async function() { + return async function(...args) { if (isTest()) { - return await f.apply(this, arguments); + return await f.apply(this, args) } - let responseObject = {}; + let responseObject = {} try { - const responseBody = await f.apply(this, arguments); + const responseBody = await f.apply(this, args) responseObject = {code: successCode, body: responseBody} } catch (err) { - logger.error('error: ' + err); + logger.error('error: ' + err) - //checking is err just string or Error object and wrapping it by new obj - let errorObj = {}; + // checking is err just string or Error object and wrapping it by new obj + let errorObj = {} if (!err.message) { - errorObj.message = err; + errorObj.message = err } else { - errorObj = err; + errorObj = err } - let code; + let code if (errorsCodes) { errorsCodes.some((errCodeDescr) => { const isCurrentCode = errCodeDescr.errors.some((err) => { if (errorObj instanceof err) { - return true; + return true } - }); + }) if (isCurrentCode) { - code = errCodeDescr.code; - return true; + code = errCodeDescr.code + return true } - }); + }) } - code = code ? code : 500; + code = code ? code : 500 responseObject = { code: code, body: { name: errorObj.name, message: errorObj.message, - stack: errorObj.stack - } + stack: errorObj.stack, + }, } if (code !== 500) { delete responseObject.body.stack } } - return responseObject; + return responseObject } } module.exports = { - handleErrors: handleErrors + handleErrors: handleErrors, } diff --git a/src/decorators/tracking-decorator.js b/src/decorators/tracking-decorator.js index e4083af07..763ff5a40 100644 --- a/src/decorators/tracking-decorator.js +++ b/src/decorators/tracking-decorator.js @@ -11,25 +11,23 @@ * */ -const { isTest} = require('../helpers/app-helper'); -const Tracking = require('../tracking'); +const {isTest} = require('../helpers/app-helper') +const Tracking = require('../tracking') function trackEvent(f, eventType) { - return async function() { + return async function(...fArgs) { if (isTest()) { - return await f.apply(this, arguments); + return await f.apply(this, fArgs) } - const fArgs = Array.prototype.slice.call(arguments); - const res = await f.apply(this, arguments); - const event = Tracking.buildEvent(eventType, res, fArgs, f.name); - await Tracking.processEvent(event, fArgs, res); - return res; - + const res = await f.apply(this, fArgs) + const event = Tracking.buildEvent(eventType, res, fArgs, f.name) + await Tracking.processEvent(event, fArgs, res) + return res } } module.exports = { - trackEvent: trackEvent -}; \ No newline at end of file + trackEvent: trackEvent, +} diff --git a/src/decorators/transaction-decorator.js b/src/decorators/transaction-decorator.js index 3f8aca59f..10aa70d07 100644 --- a/src/decorators/transaction-decorator.js +++ b/src/decorators/transaction-decorator.js @@ -11,73 +11,70 @@ * */ -const db = require('./../sequelize/models'); -const retry = require('retry-as-promised'); -const sequelize = db.sequelize; -const Transaction = require('sequelize/lib/transaction'); -const { isTest } = require('../helpers/app-helper'); +const db = require('./../sequelize/models') +const retry = require('retry-as-promised') +const sequelize = db.sequelize +const Transaction = require('sequelize/lib/transaction') +const {isTest} = require('../helpers/app-helper') function transaction(f) { - return async function() { + return async function(...fArgs) { if (isTest()) { - return await f.apply(this, arguments); + return await f.apply(this, fArgs) } - const fArgs = Array.prototype.slice.call(arguments); - //TODO [when transactions concurrency issue fixed]: Remove 'fArgs[fArgs.length - 1].fakeTransaction' - if (fArgs.length > 0 && fArgs[fArgs.length - 1] && (fArgs[fArgs.length - 1] instanceof Transaction || fArgs[fArgs.length - 1].fakeTransaction)) { - return await f.apply(this, fArgs); + // TODO [when transactions concurrency issue fixed]: Remove 'fArgs[fArgs.length - 1].fakeTransaction' + if (fArgs.length > 0 && fArgs[fArgs.length - 1] + && (fArgs[fArgs.length - 1] instanceof Transaction || fArgs[fArgs.length - 1].fakeTransaction)) { + return await f.apply(this, fArgs) } else { - //return f.apply(this, fArgs) + // return f.apply(this, fArgs) return sequelize.transaction(async (t) => { - fArgs.push(t); - return await f.apply(this, fArgs); + fArgs.push(t) + return await f.apply(this, fArgs) }) } } } function generateTransaction(f) { - return function () { - const args = Array.prototype.slice.call(arguments); + return function(...args) { return retry(() => { - const t = transaction(f); - return t.apply(this, args); + const t = transaction(f) + return t.apply(this, args) }, { - max: 5, - match: [ - sequelize.ConnectionError, - 'SQLITE_BUSY', - ], - }) + max: 5, + match: [ + sequelize.ConnectionError, + 'SQLITE_BUSY', + ], + }) } } function fakeTransaction(f) { const fakeTransactionObject = {fakeTransaction: true} - return async function() { + return async function(...fArgs) { if (isTest()) { - return await f.apply(this, arguments); + return await f.apply(this, fArgs) } - const fArgs = Array.prototype.slice.call(arguments); if (fArgs.length > 0 && fArgs[fArgs.length - 1] instanceof Transaction) { - fArgs[fArgs.length - 1] = fakeTransactionObject; - return await f.apply(this, fArgs); + fArgs[fArgs.length - 1] = fakeTransactionObject + return await f.apply(this, fArgs) } else { - fArgs.push(fakeTransactionObject); - return await f.apply(this, fArgs); + fArgs.push(fakeTransactionObject) + return await f.apply(this, fArgs) } } } -//TODO [when transactions concurrency issue fixed]: Remove +// TODO [when transactions concurrency issue fixed]: Remove function generateFakeTransaction(f) { - return function () { - const args = Array.prototype.slice.call(arguments); + return function(...args) { return retry(() => { - const t = fakeTransaction(f); - return t.apply(this, args); + const t = fakeTransaction(f) + return t.apply(this, args) }, { max: 5, match: [ @@ -90,5 +87,5 @@ function generateFakeTransaction(f) { module.exports = { generateTransaction: generateTransaction, - generateFakeTransaction: generateFakeTransaction -}; \ No newline at end of file + generateFakeTransaction: generateFakeTransaction, +} diff --git a/src/enums/fog-state.js b/src/enums/fog-state.js index 7c14e7a47..8cd7cb3f7 100644 --- a/src/enums/fog-state.js +++ b/src/enums/fog-state.js @@ -13,7 +13,7 @@ const fogState = { UNKNOWN: 'UNKNOWN', - RUNNING: 'RUNNING' -}; + RUNNING: 'RUNNING', +} -module.exports = fogState; \ No newline at end of file +module.exports = fogState diff --git a/src/enums/microservice-state.js b/src/enums/microservice-state.js index 1956f9109..5dd10c383 100644 --- a/src/enums/microservice-state.js +++ b/src/enums/microservice-state.js @@ -16,7 +16,7 @@ const microserviceState = { RUNNING: 'RUNNING', RESTARTING: 'RESTARTING', STUCK_IN_RESTART: 'STUCK_IN_RESTART', -}; +} -module.exports = microserviceState; +module.exports = microserviceState diff --git a/src/enums/tracking-event-type.js b/src/enums/tracking-event-type.js index 64b0ab702..2092c500c 100644 --- a/src/enums/tracking-event-type.js +++ b/src/enums/tracking-event-type.js @@ -22,6 +22,6 @@ const trackingEventType = Object.freeze({ CATALOG_CREATED: 'catalog created', CONFIG_CHANGED: 'config changed', OTHER: 'other', -}); +}) -module.exports = trackingEventType; \ No newline at end of file +module.exports = trackingEventType diff --git a/src/helpers/app-helper.js b/src/helpers/app-helper.js index 9ff6b6924..e4a580862 100644 --- a/src/helpers/app-helper.js +++ b/src/helpers/app-helper.js @@ -11,55 +11,54 @@ * */ -const crypto = require('crypto'); -const Errors = require('./errors'); -const ErrorMessages = require('./error-messages'); +const crypto = require('crypto') +const Errors = require('./errors') -const logger = require('../logger'); -const fs = require('fs'); -const Config = require('../config'); -const path = require('path'); -const portscanner = require('portscanner'); -const format = require('string-format'); +const logger = require('../logger') +const fs = require('fs') +const Config = require('../config') +const path = require('path') +const portscanner = require('portscanner') +const format = require('string-format') -const ALGORITHM = 'aes-256-ctr'; -const IV_LENGTH = 16; +const ALGORITHM = 'aes-256-ctr' +const IV_LENGTH = 16 -const Transaction = require('sequelize/lib/transaction'); +const Transaction = require('sequelize/lib/transaction') function encryptText(text, salt) { - const iv = crypto.randomBytes(IV_LENGTH); - const processedSalt = crypto.createHash('md5').update(salt).digest("hex"); + const iv = crypto.randomBytes(IV_LENGTH) + const processedSalt = crypto.createHash('md5').update(salt).digest('hex') - const cipher = crypto.createCipheriv(ALGORITHM, processedSalt, iv); - let crypted = cipher.update(text, 'utf8', 'hex'); - crypted += cipher.final('hex'); - return iv.toString('hex') + ':' + crypted.toString('hex'); + const cipher = crypto.createCipheriv(ALGORITHM, processedSalt, iv) + let crypted = cipher.update(text, 'utf8', 'hex') + crypted += cipher.final('hex') + return iv.toString('hex') + ':' + crypted.toString('hex') } function decryptText(text, salt) { - const processedSalt = crypto.createHash('md5').update(salt).digest("hex"); + const processedSalt = crypto.createHash('md5').update(salt).digest('hex') - const textParts = text.split(':'); - const iv = Buffer.from(textParts.shift(), 'hex'); - let encryptedText = Buffer.from(textParts.join(':'), 'hex'); + const textParts = text.split(':') + const iv = Buffer.from(textParts.shift(), 'hex') + const encryptedText = Buffer.from(textParts.join(':'), 'hex') - const decipher = crypto.createDecipheriv(ALGORITHM, processedSalt, iv); - let dec = decipher.update(encryptedText, 'hex', 'utf8'); - dec += decipher.final('utf8'); + const decipher = crypto.createDecipheriv(ALGORITHM, processedSalt, iv) + let dec = decipher.update(encryptedText, 'hex', 'utf8') + dec += decipher.final('utf8') return dec } function generateRandomString(size) { + let randString = '' + const possible = '2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ' - let randString = ""; - const possible = "2346789bcdfghjkmnpqrtvwxyzBCDFGHJKLMNPQRTVWXYZ"; - - for (let i = 0; i < size; i++) - randString += possible.charAt(Math.floor(Math.random() * possible.length)); + for (let i = 0; i < size; i++) { + randString += possible.charAt(Math.floor(Math.random() * possible.length)) + } - return randString; + return randString } // Checks the status of a single port @@ -67,60 +66,62 @@ function generateRandomString(size) { // returns 'open' if port is not available async function checkPortAvailability(port) { return new Promise((resolve) => { - return resolve(portscanner.checkPortStatus(port)); - }); + return resolve(portscanner.checkPortStatus(port)) + }) } -const findAvailablePort = async function (hostname) { - let portRange = Config.get("Tunnel:PortRange"); +const findAvailablePort = async function(hostname) { + let portRange = Config.get('Tunnel:PortRange') if (!portRange) { - logger.warn('Port range was\'n specified in config. Default range (2000-10000) will be used'); - portRange = '2000-10000'; + logger.warn('Port range was\'n specified in config. Default range (2000-10000) will be used') + portRange = '2000-10000' } - let portBounds = portRange.split("-").map(i => parseInt(i)); - return await portscanner.findAPortNotInUse(portBounds[0], portBounds[1], hostname); -}; + const portBounds = portRange.split('-').map((i) => parseInt(i)) + return await portscanner.findAPortNotInUse(portBounds[0], portBounds[1], hostname) +} function isFileExists(filePath) { - if (path.extname(filePath).indexOf(".") >= 0) { - return fs.existsSync(filePath); + if (path.extname(filePath).indexOf('.') >= 0) { + return fs.existsSync(filePath) } else { - return false; + return false } } function isValidPort(port) { - port = Number(port); + port = Number(port) if (Number.isInteger(port)) { - if (port >= 0 && port < 65535) - return true; + if (port >= 0 && port < 65535) { + return true + } } - return false; + return false } function isValidDomain(domain) { - const re = /^((?:(?:(?:\w[\.\-\+]?)*)\w)+)((?:(?:(?:\w[\.\-\+]?){0,62})\w)+)\.(\w{2,6})$/; - return re.test(domain); + const re = /^((?:(?:(?:\w[\.\-\+]?)*)\w)+)((?:(?:(?:\w[\.\-\+]?){0,62})\w)+)\.(\w{2,6})$/ + return re.test(domain) } -const isValidPublicIP = function (publicIP) { - const re = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$|^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$|^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/; - return re.test(publicIP); -}; +const isValidPublicIP = function(publicIP) { + /* eslint-disable max-len */ + const re = /^(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])$|^(([a-zA-Z]|[a-zA-Z][a-zA-Z0-9\-]*[a-zA-Z0-9])\.)*([A-Za-z]|[A-Za-z][A-Za-z0-9\-]*[A-Za-z0-9])$|^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$/ + return re.test(publicIP) +} function generateAccessToken() { - let token = '', i; + let token = ''; let i for (i = 0; i < 8; i++) { - token += ((0 + (Math.floor(Math.random() * (Math.pow(2, 31))) + 1).toString(16)).slice(-8)).substr(-8); + token += ((0 + (Math.floor(Math.random() * (Math.pow(2, 31))) + 1).toString(16)).slice(-8)).substr(-8) } - return token; + return token } function checkTransaction(transaction) { if (isTest()) { return } - //TODO [when transactions concurrency issue fixed]: Remove '!transaction.fakeTransaction' + // TODO [when transactions concurrency issue fixed]: Remove '!transaction.fakeTransaction' if (!transaction || (!(transaction instanceof Transaction) && !transaction.fakeTransaction)) { throw new Errors.TransactionError() } @@ -133,37 +134,36 @@ function deleteUndefinedFields(obj) { Object.keys(obj).forEach((fld) => { if (obj[fld] === undefined) { - delete obj[fld] + delete obj[fld] } else if (obj[fld] instanceof Object) { obj[fld] = deleteUndefinedFields(obj[fld]) } - }); + }) return obj } function validateBooleanCliOptions(trueOption, falseOption) { if (trueOption && falseOption) { - throw new Errors.ValidationError("Two opposite can not be used simultaneously"); + throw new Errors.ValidationError('Two opposite can not be used simultaneously') } return trueOption ? true : (falseOption ? false : undefined) } -function formatMessage() { - const argsArray = Array.prototype.slice.call(arguments); - return format.apply(null, argsArray); +function formatMessage(...args) { + return format(...args) } function stringifyCliJsonSchema(json) { return JSON.stringify(json, null, 2) - .replace(/{/g, "\\{") - .replace(/}/g, "\\}"); + .replace(/{/g, '\\{') + .replace(/}/g, '\\}') } function trimCertificate(cert) { - let result = cert.replace(/(^[\s\S]*-{3,}BEGIN CERTIFICATE-{3,}[\s]*)/, ""); - result = result.replace(/([\s]*-{3,}END CERTIFICATE-{3,}[\s\S]*$)/, ""); - return result; + let result = cert.replace(/(^[\s\S]*-{3,}BEGIN CERTIFICATE-{3,}[\s]*)/, '') + result = result.replace(/([\s]*-{3,}END CERTIFICATE-{3,}[\s\S]*$)/, '') + return result } function isTest() { @@ -172,17 +172,18 @@ function isTest() { function isEmpty(obj) { for (const key in obj) { - if (obj.hasOwnProperty(key)) - return false; + if (obj.hasOwnProperty(key)) { + return false + } } - return true; + return true } function isOnline() { - const daemon = require('../daemon'); + const daemon = require('../daemon') - let pid = daemon.status(); - return pid !== 0; + const pid = daemon.status() + return pid !== 0 } module.exports = { @@ -204,5 +205,5 @@ module.exports = { trimCertificate, isTest, isEmpty, - isOnline -}; + isOnline, +} diff --git a/src/helpers/constants.js b/src/helpers/constants.js index 6a67a34a0..79d3fc591 100644 --- a/src/helpers/constants.js +++ b/src/helpers/constants.js @@ -71,4 +71,4 @@ module.exports = { HTTP_CODE_NOT_FOUND: 404, HTTP_CODE_DUPLICATE_PROPERTY: 409, HTTP_CODE_INTERNAL_ERROR: 500, -}; \ No newline at end of file +} diff --git a/src/helpers/error-messages.js b/src/helpers/error-messages.js index 9caebc8df..56cdf0c60 100644 --- a/src/helpers/error-messages.js +++ b/src/helpers/error-messages.js @@ -13,49 +13,51 @@ module.exports = { INVALID_CLI_ARGUMENT_TYPE: 'Field "{}" is not of type(s) {}', - DUPLICATE_NAME: "Duplicate name '{}'", + DUPLICATE_NAME: 'Duplicate name \'{}\'', ALREADY_EXISTS: 'Model already exists', - INVALID_CATALOG_ITEM_ID: "Invalid catalog item id '{}'", - INVALID_FLOW_ID: "Invalid flow id '{}'", - INVALID_REGISTRY_ID: "Invalid registry id '{}'", - INVALID_CONNECTOR_IP: "Invalid connector IP '{}'", + INVALID_CATALOG_ITEM_ID: 'Invalid catalog item id \'{}\'', + INVALID_FLOW_ID: 'Invalid flow id \'{}\'', + INVALID_REGISTRY_ID: 'Invalid registry id \'{}\'', + INVALID_CONNECTOR_IP: 'Invalid connector IP \'{}\'', UNABLE_TO_CREATE_ACTIVATION_CODE: 'Unable to create activation code', UNABLE_TO_GET_ACTIVATION_CODE: 'Unable to create activation code', - INVALID_IOFOG_UUID: "Invalid ioFog UUID '{}'", + INVALID_IOFOG_UUID: 'Invalid ioFog UUID \'{}\'', INVALID_USER_EMAIL: 'Invalid user email', - INVALID_MICROSERVICE_UUID: "Invalid microservice UUID '{}'", - INVALID_SOURCE_MICROSERVICE_UUID: "Invalid source microservice UUID '{}'", - INVALID_DEST_MICROSERVICE_UUID: "Invalid destination microservice UUID '{}'", - INVALID_MICROSERVICE_STRACE: "Strace data for this microservice not found", - INVALID_VOLUME_MAPPING_UUID: "Invalid volume mapping id '{}'", + INVALID_MICROSERVICE_UUID: 'Invalid microservice UUID \'{}\'', + INVALID_SOURCE_MICROSERVICE_UUID: 'Invalid source microservice UUID \'{}\'', + INVALID_DEST_MICROSERVICE_UUID: 'Invalid destination microservice UUID \'{}\'', + INVALID_MICROSERVICE_STRACE: 'Strace data for this microservice not found', + INVALID_VOLUME_MAPPING_UUID: 'Invalid volume mapping id \'{}\'', ACTIVATION_CODE_NOT_FOUND: 'Activation code not found', INVALID_OLD_PASSWORD: 'Old password is incorrect', - NEEDED_FORCE_DELETE_USER: "There are running iofog-agents, stop them before removal or pass 'force' parameter", + NEEDED_FORCE_DELETE_USER: 'There are running iofog-agents, stop them before removal or pass \'force\' parameter', ACCOUNT_NOT_FOUND: 'Account not found', USER_NOT_UPDATED: 'User not updated', EMAIL_NOT_ACTIVATED: 'Email is not activated. Please activate your account first.', - REGISTRATION_FAILED: 'Registration failed: There is already an account associated with your email address. Please try logging in instead.', + REGISTRATION_FAILED: 'Registration failed: There is already an account associated with your email address. ' + + 'Please try logging in instead.', INVALID_PROVISIONING_KEY: 'Invalid Provisioning Key', EMAIL_SENDER_NOT_CONFIGURED: 'Email sender not configured', INVALID_PORT_FORMAT: 'Invalid port format', INVALID_FILE_PATH: 'Invalid file path', - PORT_NOT_AVAILABLE: "Port '{}' is not available", - UNABLE_TO_WRITE_STRACE: "Error while writing strace data to file. File name: '{}', err: '{}'", - UNABLE_TO_DELETE_STRACE: "Error while deleting strace data file. File name: '{}', err: '{}'", - FTP_ERROR: "FTP error: '{}'", + PORT_NOT_AVAILABLE: 'Port \'{}\' is not available', + UNABLE_TO_WRITE_STRACE: 'Error while writing strace data to file. File name: \'{}\', err: \'{}\'', + UNABLE_TO_DELETE_STRACE: 'Error while deleting strace data file. File name: \'{}\', err: \'{}\'', + FTP_ERROR: 'FTP error: \'{}\'', EXPIRED_PROVISION_KEY: 'Expired provision key', VERSION_COMMAND_NOT_FOUND: 'Version command not found', - STRACE_WITHOUT_FOG: "Can't run strace for microservice without ioFog.", + STRACE_WITHOUT_FOG: 'Can\'t run strace for microservice without ioFog.', INVALID_ACTION_PROPERTY: 'Unknown action property. Action can be "open" or "close"', IMAGE_SNAPSHOT_NOT_FOUND: 'Image snapshot not found', - INVALID_MICROSERVICES_FOG_TYPE: 'Some of microservices haven\'t proper docker images for this ioFog type. List of invalid microservices:\n', - INVALID_MICROSERVICE_CONFIG: "Can't create network microservice without appropriate configuration.", + INVALID_MICROSERVICES_FOG_TYPE: 'Some of microservices haven\'t proper docker images for this ioFog type. ' + + 'List of invalid microservices:\n', + INVALID_MICROSERVICE_CONFIG: 'Can\'t create network microservice without appropriate configuration.', INVALID_MICROSERVICE_USER: 'Invalid microservice user or UUID', ROUTE_NOT_FOUND: 'Route not found', IMAGE_SNAPSHOT_WITHOUT_FOG: 'Can not run image snapshot for microservice without ioFog.', IMAGE_SNAPSHOT_NOT_AVAILABLE: 'Image snapshot is not available for this microservice.', FILE_DOES_NOT_EXIST: 'File does not exist.', - RESTRICTED_PUBLISHER: "You are not allowed to add catalog item as 'Eclipse ioFog' publisher", + RESTRICTED_PUBLISHER: 'You are not allowed to add catalog item as \'Eclipse ioFog\' publisher', REQUIRED_FOG_NODE: 'ioFog node is required.', PORT_MAPPING_ALREADY_EXISTS: 'Port mapping already exists', PORT_MAPPING_INTERNAL_PORT_NOT_PROVIDED: 'Internal port wasn\'t provided', @@ -73,16 +75,16 @@ module.exports = { INVALID_PORT_MAPPING: 'Port mapping parsing error. Please provide valid port mapping.', INVALID_VOLUME_MAPPING: 'Volume mapping parsing error. Please provide valid volume mapping.', INVALID_INTERNAL_PORT: 'Internal parsing error. Please provide valid internal port.', - INVALID_ROUTE: 'Route parsing error. Please provide valid route.' + INVALID_ROUTE: 'Route parsing error. Please provide valid route.', }, CONNECTOR_IS_IN_USE: 'You can\'t delete connector, because it is used for routing now.', INVALID_VERSION_COMMAND_UPGRADE: 'Can\'t upgrade version now. Latest is already installed', INVALID_VERSION_COMMAND_ROLLBACK: 'Can\'t rollback version now. There are no backups on agent', CATALOG_ITEM_IMAGES_IS_FROZEN: 'Can\'t update catalog item images for item used for running microservices', CATALOG_UPDATE_NO_FIELDS: 'Add some parameters which should be updated.', - CATALOG_UPDATE_REQUIRES_ID: "Parameter '--item-id' is missing, update requires Catalog id.", + CATALOG_UPDATE_REQUIRES_ID: 'Parameter \'--item-id\' is missing, update requires Catalog id.', SYSTEM_CATALOG_ITEM_UPDATE: 'Catalog item id {} is system and can\'t be updated', SYSTEM_CATALOG_ITEM_DELETE: 'Catalog item id {} is system and can\'t be deleted', SYSTEM_MICROSERVICE_UPDATE: 'Microservice uuid {} is system and can\'t be updated', - SYSTEM_MICROSERVICE_DELETE: 'Microservice uuid {} is system and can\'t be deleted' -}; + SYSTEM_MICROSERVICE_DELETE: 'Microservice uuid {} is system and can\'t be deleted', +} diff --git a/src/helpers/errors.js b/src/helpers/errors.js index 9a0aa9980..247eafd2c 100644 --- a/src/helpers/errors.js +++ b/src/helpers/errors.js @@ -21,93 +21,93 @@ class AuthenticationError extends Error { class TransactionError extends Error { constructor() { - const message = 'Transaction not provided'; - super(message); - this.message = message; + const message = 'Transaction not provided' + super(message) + this.message = message this.name = 'TransactionError' } } class ValidationError extends Error { constructor(message) { - super(message); - this.message = message; - this.name = "ValidationError"; + super(message) + this.message = message + this.name = 'ValidationError' } } class InvalidCredentialsError extends Error { constructor() { - const message = 'Invalid credentials'; - super(message); - this.message = message; - this.name = "InvalidCredentialsError"; + const message = 'Invalid credentials' + super(message) + this.message = message + this.name = 'InvalidCredentialsError' } } class DuplicatePropertyError extends Error { constructor(message) { - super(message); - this.message = message; - this.name = "DuplicatePropertyError"; + super(message) + this.message = message + this.name = 'DuplicatePropertyError' } } class ModelNotFoundError extends Error { constructor() { const message = 'Model not found' - super(message); - this.message = message; - this.name = "ModelNotFoundError"; + super(message) + this.message = message + this.name = 'ModelNotFoundError' } } class NotFoundError extends Error { constructor(message) { - super(message); - this.message = message; - this.name = "NotFoundError"; + super(message) + this.message = message + this.name = 'NotFoundError' } } class FtpError extends Error { constructor(message) { - super(message); - this.message = message; - this.name = "FtpError"; + super(message) + this.message = message + this.name = 'FtpError' } } class EmailActivationSetupError extends Error { constructor() { - const message = 'Email activation is not configured on Controller'; - super(message); - this.message = message; - this.name = "EmailActivationSetupError"; + const message = 'Email activation is not configured on Controller' + super(message) + this.message = message + this.name = 'EmailActivationSetupError' } } class InvalidArgumentError extends Error { constructor(message) { - super(message); - this.message = message; - this.name = "InvalidArgumentError"; + super(message) + this.message = message + this.name = 'InvalidArgumentError' } } class InvalidArgumentTypeError extends Error { constructor(message) { - super(message); - this.message = message; - this.name = "InvalidArgumentTypeError"; + super(message) + this.message = message + this.name = 'InvalidArgumentTypeError' } } class CLIArgsNotProvidedError extends Error { constructor() { - super('Empty args'); - this.message = 'Empty args'; - this.name = 'CLIArgsNotProvidedError'; + super('Empty args') + this.message = 'Empty args' + this.name = 'CLIArgsNotProvidedError' } } @@ -123,5 +123,5 @@ module.exports = { EmailActivationSetupError: EmailActivationSetupError, InvalidArgumentError: InvalidArgumentError, InvalidArgumentTypeError: InvalidArgumentTypeError, - CLIArgsNotProvidedError: CLIArgsNotProvidedError -}; \ No newline at end of file + CLIArgsNotProvidedError: CLIArgsNotProvidedError, +} diff --git a/src/jobs/base/base-job-handler.js b/src/jobs/base/base-job-handler.js index 81fac4dc2..58d5388f5 100644 --- a/src/jobs/base/base-job-handler.js +++ b/src/jobs/base/base-job-handler.js @@ -11,16 +11,16 @@ * */ -const Config = require('../../config'); +const Config = require('../../config') class BaseJobHandler { constructor() { - this.scheduleTime = Config.get('Settings:DefaultJobIntervalSeconds') * 1000; + this.scheduleTime = Config.get('Settings:DefaultJobIntervalSeconds') * 1000 } run() { - throw new Error('Not Implemented'); + throw new Error('Not Implemented') } } -module.exports = BaseJobHandler; \ No newline at end of file +module.exports = BaseJobHandler diff --git a/src/jobs/fog-status-job.js b/src/jobs/fog-status-job.js index 25642df82..ae0d54e9b 100644 --- a/src/jobs/fog-status-job.js +++ b/src/jobs/fog-status-job.js @@ -11,55 +11,55 @@ * */ -const TransactionDecorator = require('../decorators/transaction-decorator'); +const TransactionDecorator = require('../decorators/transaction-decorator') -const FogManager = require('../sequelize/managers/iofog-manager'); -const MicroserviceManager = require('../sequelize/managers/microservice-manager'); -const MicroserviceStatusManager = require('../sequelize/managers/microservice-status-manager'); -const MicroserviceService = require('../services/microservices-service'); -const MicroserviceStates = require('../enums/microservice-state'); -const FogStates = require('../enums/fog-state'); -const BaseJobHandler = require('./base/base-job-handler'); -const Config = require('../config'); +const FogManager = require('../sequelize/managers/iofog-manager') +const MicroserviceManager = require('../sequelize/managers/microservice-manager') +const MicroserviceStatusManager = require('../sequelize/managers/microservice-status-manager') +const MicroserviceService = require('../services/microservices-service') +const MicroserviceStates = require('../enums/microservice-state') +const FogStates = require('../enums/fog-state') +const BaseJobHandler = require('./base/base-job-handler') +const Config = require('../config') class FogStatusJob extends BaseJobHandler { constructor() { - super(); - this.scheduleTime = Config.get('Settings:FogStatusUpdateIntervalSeconds') * 1000; + super() + this.scheduleTime = Config.get('Settings:FogStatusUpdateIntervalSeconds') * 1000 } run() { - setInterval(TransactionDecorator.generateFakeTransaction(updateFogsConnectionStatus), this.scheduleTime); + setInterval(TransactionDecorator.generateFakeTransaction(updateFogsConnectionStatus), this.scheduleTime) } } async function updateFogsConnectionStatus(transaction) { - const unknownFogUuids = await _updateFogStatus(transaction); - const microservices = await _updateMicroserviceStatus(unknownFogUuids, transaction); - await _deleteNotRunningMicroservices(microservices, transaction); + const unknownFogUuids = await _updateFogStatus(transaction) + const microservices = await _updateMicroserviceStatus(unknownFogUuids, transaction) + await _deleteNotRunningMicroservices(microservices, transaction) } async function _updateFogStatus(transaction) { - const minInMs = Config.get('Settings:FogStatusFrequencySeconds') * 1000; - const fogs = await FogManager.findAll({daemonStatus: FogStates.RUNNING}, transaction); + const minInMs = Config.get('Settings:FogStatusFrequencySeconds') * 1000 + const fogs = await FogManager.findAll({daemonStatus: FogStates.RUNNING}, transaction) const unknownFogUuids = fogs - .filter(fog => { - const intervalInMs = fog.statusFrequency > minInMs ? fog.statusFrequency * 2 : minInMs; - return Date.now() - fog.lastStatusTime > intervalInMs - }) - .map(fog => fog.uuid); + .filter((fog) => { + const intervalInMs = fog.statusFrequency > minInMs ? fog.statusFrequency * 2 : minInMs + return Date.now() - fog.lastStatusTime > intervalInMs + }) + .map((fog) => fog.uuid) - const where = {uuid: unknownFogUuids}; - const data = {daemonStatus: FogStates.UNKNOWN, ipAddress: '0.0.0.0'}; - await FogManager.update(where, data, transaction); - return unknownFogUuids; + const where = {uuid: unknownFogUuids} + const data = {daemonStatus: FogStates.UNKNOWN, ipAddress: '0.0.0.0'} + await FogManager.update(where, data, transaction) + return unknownFogUuids } async function _updateMicroserviceStatus(unknownFogUuids, transaction) { - const microservices = await MicroserviceManager.findAllWithStatuses({iofogUuid: unknownFogUuids}, transaction); - const microserviceStatusIds = microservices.map(microservice => microservice.microserviceStatus.id); - await MicroserviceStatusManager.update({id: microserviceStatusIds}, {status: MicroserviceStates.NOT_RUNNING}, transaction); - return microservices; + const microservices = await MicroserviceManager.findAllWithStatuses({iofogUuid: unknownFogUuids}, transaction) + const microserviceStatusIds = microservices.map((microservice) => microservice.microserviceStatus.id) + await MicroserviceStatusManager.update({id: microserviceStatusIds}, {status: MicroserviceStates.NOT_RUNNING}, transaction) + return microservices } async function _deleteNotRunningMicroservices(microservices, transaction) { @@ -70,4 +70,4 @@ async function _deleteNotRunningMicroservices(microservices, transaction) { } } -module.exports = new FogStatusJob(); \ No newline at end of file +module.exports = new FogStatusJob() diff --git a/src/jobs/send-tracking-job.js b/src/jobs/send-tracking-job.js index 860b98666..78c5a305e 100644 --- a/src/jobs/send-tracking-job.js +++ b/src/jobs/send-tracking-job.js @@ -11,33 +11,31 @@ * */ -const BaseJobHandler = require('./base/base-job-handler'); -const Tracking = require('../tracking'); -const TrackingEventType = require('../enums/tracking-event-type'); -const TrackingEventManager = require('../sequelize/managers/tracking-event-manager'); +const BaseJobHandler = require('./base/base-job-handler') +const Tracking = require('../tracking') +const TrackingEventManager = require('../sequelize/managers/tracking-event-manager') class SendTrackingJob extends BaseJobHandler { - constructor() { - super(); - this.scheduleTime = intervalMin * 60 * 1000; + super() + this.scheduleTime = intervalMin * 60 * 1000 } run() { - setInterval(sendTracking, this.scheduleTime); + setInterval(sendTracking, this.scheduleTime) } } -const intervalMin = 5; +const intervalMin = 5 async function sendTracking() { - const fakeTransactionObject = {fakeTransaction: true}; - const events = await TrackingEventManager.popAll(fakeTransactionObject); + const fakeTransactionObject = {fakeTransaction: true} + const events = await TrackingEventManager.popAll(fakeTransactionObject) try { - Tracking.sendEvents(events); + Tracking.sendEvents(events) } catch (e) { - logger.silly(`tracking sending failed with error ${e.message}`); + logger.silly(`tracking sending failed with error ${e.message}`) } } -module.exports = new SendTrackingJob(); \ No newline at end of file +module.exports = new SendTrackingJob() diff --git a/src/jobs/time-tracking-job.js b/src/jobs/time-tracking-job.js index 8fcb69c14..85583d95a 100644 --- a/src/jobs/time-tracking-job.js +++ b/src/jobs/time-tracking-job.js @@ -11,45 +11,44 @@ * */ -const moment = require('moment'); +const moment = require('moment') -const BaseJobHandler = require('./base/base-job-handler'); -const FogAccessTokenService = require('../services/iofog-access-token-service'); -const logger = require('../logger'); -const Tracking = require('../tracking'); -const TrackingEventType = require('../enums/tracking-event-type'); -const TransactionDecorator = require('../decorators/transaction-decorator'); +const BaseJobHandler = require('./base/base-job-handler') +const FogAccessTokenService = require('../services/iofog-access-token-service') +const logger = require('../logger') +const Tracking = require('../tracking') +const TrackingEventType = require('../enums/tracking-event-type') +const TransactionDecorator = require('../decorators/transaction-decorator') -const INTERVAL_MIN = 5; +const INTERVAL_MIN = 5 class TimeTrackingJob extends BaseJobHandler { - constructor() { - super(); - this.scheduleTime = INTERVAL_MIN * 60 * 1000; - this.startTime = moment.now(); + super() + this.scheduleTime = INTERVAL_MIN * 60 * 1000 + this.startTime = moment.now() } run() { - setTimeout(this.trackTime, this.scheduleTime); + setTimeout(this.trackTime, this.scheduleTime) } async trackTime() { let agentsCount = 0 try { - const agents = await TransactionDecorator.generateFakeTransaction(FogAccessTokenService.all)(); - agentsCount = (agents || []).length; + const agents = await TransactionDecorator.generateFakeTransaction(FogAccessTokenService.all)() + agentsCount = (agents || []).length } catch (e) { logger.warn('Unable to count ioFog agents') } - const runningTime = moment().diff(this.startTime, 'minutes'); - const event = Tracking.buildEvent(TrackingEventType.RUNNING_TIME, { runningTime, agentsCount }); - await Tracking.processEvent(event); + const runningTime = moment().diff(this.startTime, 'minutes') + const event = Tracking.buildEvent(TrackingEventType.RUNNING_TIME, {runningTime, agentsCount}) + await Tracking.processEvent(event) - setTimeout(this.trackTime, this.scheduleTime); + setTimeout(this.trackTime, this.scheduleTime) } } -module.exports = new TimeTrackingJob(); \ No newline at end of file +module.exports = new TimeTrackingJob() diff --git a/src/logger/index.js b/src/logger/index.js index e34efb8ad..c5a9f9020 100644 --- a/src/logger/index.js +++ b/src/logger/index.js @@ -11,10 +11,10 @@ * */ -const winston = require('winston'); -const config = require('../config'); -const fs = require('fs'); -const MESSAGE = Symbol.for('message'); +const winston = require('winston') +const config = require('../config') +const fs = require('fs') +const MESSAGE = Symbol.for('message') const dirname = config.get('Service:LogsDirectory') const maxsize = config.get('Service:LogsFileSize') @@ -22,7 +22,7 @@ const maxsize = config.get('Service:LogsFileSize') // Create the log directory if it does not exist try { if (!fs.existsSync(dirname)) { - fs.mkdirSync(dirname); + fs.mkdirSync(dirname) } } catch (e) { // can't initialize log folder @@ -38,36 +38,36 @@ const levels = { info: 6, verbose: 7, debug: 8, - silly: 9 -}; + silly: 9, +} const formattedJson = winston.format((log) => { - let sortedFields = ['level', 'timestamp', 'message']; + let sortedFields = ['level', 'timestamp', 'message'] if (log.args) { - sortedFields = sortedFields.concat(['args']).concat(getAllObjKeys(log.args)); + sortedFields = sortedFields.concat(['args']).concat(getAllObjKeys(log.args)) } - log[MESSAGE] = JSON.stringify(log, sortedFields); - return log; -}); + log[MESSAGE] = JSON.stringify(log, sortedFields) + return log +}) const prepareObjectLogs = winston.format((log) => { if (!(log.message instanceof Object)) { - return log; + return log } if (log.level === 'apiReq' && log.message instanceof Object) { - const req = log.message; - log.message = `${req.method} ${req.originalUrl}`; + const req = log.message + log.message = `${req.method} ${req.originalUrl}` log.args = {params: req.params, query: req.query, body: req.body} } if (log.level === 'apiRes' && log.message instanceof Object) { - const req = log.message.req; - const res = log.message.res; - log.message = `${req.method} ${req.originalUrl}`; + const req = log.message.req + const res = log.message.res + log.message = `${req.method} ${req.originalUrl}` log.args = res } - return log; -}); + return log +}) const logger = winston.createLogger({ levels: levels, @@ -75,19 +75,19 @@ const logger = winston.createLogger({ transports: [ new winston.transports.File({ format: winston.format.combine( - winston.format.timestamp(), - prepareObjectLogs(), - formattedJson() + winston.format.timestamp(), + prepareObjectLogs(), + formattedJson() ), filename: 'iofog-controller.0.log', dirname: dirname, - maxsize: maxsize, + maxsize: maxsize, rotationFormat: function() { - return getFormattedLogName(); - } + return getFormattedLogName() + }, }), ], -}); +}) // logFileName pattern similar to agent function getFormattedLogName() { @@ -99,14 +99,14 @@ function getFormattedLogName() { return '' } - files.reverse().forEach(file => { + files.reverse().forEach((file) => { const path = dirname + '/' + file if (fs.existsSync(path)) { const strNumber = file.replace('iofog-controller.', '').replace('.log', '') const number = parseInt(strNumber) + 1 fs.renameSync(path, path.replace(strNumber, number)) } - }); + }) } return '' } @@ -118,39 +118,39 @@ logger.add(new winston.transports.Console({ return } if (log.level === 'apiReq' && log.message instanceof Object) { - const req = log.message; - log.message = `${req.method} ${req.originalUrl}`; + const req = log.message + log.message = `${req.method} ${req.originalUrl}` log.args = {params: req.params, query: req.query, body: req.body} } if (log.level === 'apiRes' && log.message instanceof Object) { - const req = log.message.req; - const res = log.message.res; - log.message = `${req.method} ${req.originalUrl}`; + const req = log.message.req + const res = log.message.res + log.message = `${req.method} ${req.originalUrl}` log.args = res } - let message = log.level === 'cliRes' ? `${log.message}` : `[${log.level}] ${log.message}`; + let message = log.level === 'cliRes' ? `${log.message}` : `[${log.level}] ${log.message}` if (log.args) { message += ` | args: ${JSON.stringify(log.args)}` } - log[MESSAGE] = message; - return log; + log[MESSAGE] = message + return log })(), -})); +})) function getAllObjKeys(obj) { - let keys = []; + let keys = [] for (const key in obj) { if (!obj.hasOwnProperty(key)) { - continue; + continue } - keys.push(key); + keys.push(key) if (obj[key] instanceof Object) { - const innerKeys = getAllObjKeys(obj[key]); - keys = keys.concat(innerKeys); + const innerKeys = getAllObjKeys(obj[key]) + keys = keys.concat(innerKeys) } } - return keys; + return keys } -module.exports = logger; +module.exports = logger diff --git a/src/main.js b/src/main.js index ee4b31c48..2c32f7c9c 100644 --- a/src/main.js +++ b/src/main.js @@ -17,14 +17,13 @@ if (!process.env.NODE_ENV) { process.env.NODE_ENV = 'production' } -const Cli = require('./cli'); -const logger = require('./logger'); -const daemon = require('./daemon'); +const Cli = require('./cli') +const daemon = require('./daemon') function main() { - const cli = new Cli(); + const cli = new Cli() cli.run(daemon) } -main(); \ No newline at end of file +main() diff --git a/src/routes/agent.js b/src/routes/agent.js index 649dc23ca..1d0e47ed4 100644 --- a/src/routes/agent.js +++ b/src/routes/agent.js @@ -11,542 +11,553 @@ * */ -const constants = require('../helpers/constants'); -const AgentController = require('../controllers/agent-controller'); -const ResponseDecorator = require('../decorators/response-decorator'); +const constants = require('../helpers/constants') +const AgentController = require('../controllers/agent-controller') +const ResponseDecorator = require('../decorators/response-decorator') -const Errors = require('../helpers/errors'); -const logger = require('../logger'); +const Errors = require('../helpers/errors') +const logger = require('../logger') module.exports = [ { method: 'post', path: '/api/v3/agent/provision', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] + errors: [Errors.NotFoundError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] - const agentProvisionEndPoint = ResponseDecorator.handleErrors(AgentController.agentProvisionEndPoint, successCode, errorCodes); - const responseObject = await agentProvisionEndPoint(req); + const agentProvisionEndPoint = ResponseDecorator.handleErrors(AgentController.agentProvisionEndPoint, successCode, errorCodes) + const responseObject = await agentProvisionEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'post', path: '/api/v3/agent/deprovision', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] - const agentDeprovisionEndPoint = ResponseDecorator.handleErrors(AgentController.agentDeprovisionEndPoint, successCode, errorCodes); - const responseObject = await agentDeprovisionEndPoint(req); + const agentDeprovisionEndPoint = ResponseDecorator.handleErrors(AgentController.agentDeprovisionEndPoint, + successCode, errorCodes) + const responseObject = await agentDeprovisionEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/agent/config', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const getAgentConfigEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentConfigEndPoint, successCode, errorCodes); - const responseObject = await getAgentConfigEndPoint(req); + const getAgentConfigEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentConfigEndPoint, successCode, errorCodes) + const responseObject = await getAgentConfigEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'patch', path: '/api/v3/agent/config', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] - const updateAgentConfigEndPoint = ResponseDecorator.handleErrors(AgentController.updateAgentConfigEndPoint, successCode, errorCodes); - const responseObject = await updateAgentConfigEndPoint(req); + const updateAgentConfigEndPoint = ResponseDecorator.handleErrors(AgentController.updateAgentConfigEndPoint, + successCode, errorCodes) + const responseObject = await updateAgentConfigEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/agent/config/changes', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] - const getAgentConfigChangesEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentConfigChangesEndPoint, successCode, errorCodes); - const responseObject = await getAgentConfigChangesEndPoint(req); + const getAgentConfigChangesEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentConfigChangesEndPoint, + successCode, errorCodes) + const responseObject = await getAgentConfigChangesEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'put', path: '/api/v3/agent/status', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] - const updateAgentStatusEndPoint = ResponseDecorator.handleErrors(AgentController.updateAgentStatusEndPoint, successCode, errorCodes); - const responseObject = await updateAgentStatusEndPoint(req); + const updateAgentStatusEndPoint = ResponseDecorator.handleErrors(AgentController.updateAgentStatusEndPoint, + successCode, errorCodes) + const responseObject = await updateAgentStatusEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/agent/microservices', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const getAgentMicroservicesEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentMicroservicesEndPoint, successCode, errorCodes); - const responseObject = await getAgentMicroservicesEndPoint(req); + const getAgentMicroservicesEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentMicroservicesEndPoint, + successCode, errorCodes) + const responseObject = await getAgentMicroservicesEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/agent/microservices/:microserviceUuid', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] + errors: [Errors.NotFoundError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const getAgentMicroserviceEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentMicroserviceEndPoint, successCode, errorCodes); - const responseObject = await getAgentMicroserviceEndPoint(req); + const getAgentMicroserviceEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentMicroserviceEndPoint, + successCode, errorCodes) + const responseObject = await getAgentMicroserviceEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/agent/registries', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const getAgentRegistriesEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentRegistriesEndPoint, successCode, errorCodes); - const responseObject = await getAgentRegistriesEndPoint(req); + const getAgentRegistriesEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentRegistriesEndPoint, + successCode, errorCodes) + const responseObject = await getAgentRegistriesEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/agent/tunnel', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] + errors: [Errors.NotFoundError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const getAgentTunnelEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentTunnelEndPoint, successCode, errorCodes); - const responseObject = await getAgentTunnelEndPoint(req); + const getAgentTunnelEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentTunnelEndPoint, + successCode, errorCodes) + const responseObject = await getAgentTunnelEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/agent/strace', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] + errors: [Errors.NotFoundError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const getAgentStraceEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentStraceEndPoint, successCode, errorCodes); - const responseObject = await getAgentStraceEndPoint(req); + const getAgentStraceEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentStraceEndPoint, + successCode, errorCodes) + const responseObject = await getAgentStraceEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'put', path: '/api/v3/agent/strace', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] + errors: [Errors.NotFoundError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] - const updateAgentStraceEndPoint = ResponseDecorator.handleErrors(AgentController.updateAgentStraceEndPoint, successCode, errorCodes); - const responseObject = await updateAgentStraceEndPoint(req); + const updateAgentStraceEndPoint = ResponseDecorator.handleErrors(AgentController.updateAgentStraceEndPoint, + successCode, errorCodes) + const responseObject = await updateAgentStraceEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/agent/version', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const getAgentChangeVersionCommandEndPoint = ResponseDecorator.handleErrors(AgentController.getAgentChangeVersionCommandEndPoint, - successCode, errorCodes); - const responseObject = await getAgentChangeVersionCommandEndPoint(req); + const getAgentChangeVersionCommandEndPoint = ResponseDecorator.handleErrors( + AgentController.getAgentChangeVersionCommandEndPoint, successCode, errorCodes) + const responseObject = await getAgentChangeVersionCommandEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'put', path: '/api/v3/agent/hal/hw', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] const updateHalHardwareInfoEndPoint = ResponseDecorator.handleErrors(AgentController.updateHalHardwareInfoEndPoint, - successCode, errorCodes); - const responseObject = await updateHalHardwareInfoEndPoint(req); + successCode, errorCodes) + const responseObject = await updateHalHardwareInfoEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'put', path: '/api/v3/agent/hal/usb', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] const updateHalUsbInfoEndPoint = ResponseDecorator.handleErrors(AgentController.updateHalUsbInfoEndPoint, - successCode, errorCodes); - const responseObject = await updateHalUsbInfoEndPoint(req); + successCode, errorCodes) + const responseObject = await updateHalUsbInfoEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'delete', path: '/api/v3/agent/delete-node', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errCodes = [ { code: 401, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const deleteNodeEndPoint = ResponseDecorator.handleErrors(AgentController.deleteNodeEndPoint, successCode, errCodes); - const responseObject = await deleteNodeEndPoint(req); + const deleteNodeEndPoint = ResponseDecorator.handleErrors(AgentController.deleteNodeEndPoint, + successCode, errCodes) + const responseObject = await deleteNodeEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/agent/image-snapshot', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] const getImageSnapshotEndPoint = ResponseDecorator.handleErrors(AgentController.getImageSnapshotEndPoint, - successCode, errorCodes); - const responseObject = await getImageSnapshotEndPoint(req); + successCode, errorCodes) + const responseObject = await getImageSnapshotEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'put', path: '/api/v3/agent/image-snapshot', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] const putImageSnapshotEndPoint = ResponseDecorator.handleErrors(AgentController.putImageSnapshotEndPoint, - successCode, errorCodes); - const responseObject = await putImageSnapshotEndPoint(req); + successCode, errorCodes) + const responseObject = await putImageSnapshotEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'post', path: '/api/v3/agent/tracking', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] const postTracking = ResponseDecorator.handleErrors(AgentController.postTrackingEndPoint, - successCode, errorCodes); - const responseObject = await postTracking(req); + successCode, errorCodes) + const responseObject = await postTracking(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } - } -]; + logger.apiRes({req: req, res: responseObject}) + }, + }, +] diff --git a/src/routes/catalog.js b/src/routes/catalog.js index cf6fa44c1..e9769d460 100644 --- a/src/routes/catalog.js +++ b/src/routes/catalog.js @@ -10,179 +10,179 @@ * ******************************************************************************* * */ -const constants = require('../helpers/constants'); -const CatalogController = require('../controllers/catalog-controller'); -const ResponseDecorator = require('../decorators/response-decorator'); -const Errors = require('../helpers/errors'); -const logger = require('../logger'); +const constants = require('../helpers/constants') +const CatalogController = require('../controllers/catalog-controller') +const ResponseDecorator = require('../decorators/response-decorator') +const Errors = require('../helpers/errors') +const logger = require('../logger') module.exports = [ { method: 'get', path: '/api/v3/catalog/microservices', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] const listCatalogItemsEndPoint = ResponseDecorator.handleErrors( - CatalogController.listCatalogItemsEndPoint, - successCode, - errorCodes - ); - const responseObject = await listCatalogItemsEndPoint(req); + CatalogController.listCatalogItemsEndPoint, + successCode, + errorCodes + ) + const responseObject = await listCatalogItemsEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'post', path: '/api/v3/catalog/microservices', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_CREATED; + const successCode = constants.HTTP_CODE_CREATED const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_DUPLICATE_PROPERTY, - errors: [Errors.DuplicatePropertyError] - } - ]; + errors: [Errors.DuplicatePropertyError], + }, + ] const createCatalogItemEndpoint = ResponseDecorator.handleErrors( - CatalogController.createCatalogItemEndPoint, - successCode, - errorCodes - ); - const responseObject = await createCatalogItemEndpoint(req); + CatalogController.createCatalogItemEndPoint, + successCode, + errorCodes + ) + const responseObject = await createCatalogItemEndpoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/catalog/microservices/:id', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] const listCatalogItemEndPoint = ResponseDecorator.handleErrors( - CatalogController.listCatalogItemEndPoint, - successCode, - errorCodes - ); - const responseObject = await listCatalogItemEndPoint(req); + CatalogController.listCatalogItemEndPoint, + successCode, + errorCodes + ) + const responseObject = await listCatalogItemEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'patch', path: '/api/v3/catalog/microservices/:id', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_DUPLICATE_PROPERTY, - errors: [Errors.DuplicatePropertyError] + errors: [Errors.DuplicatePropertyError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] const updateCatalogItemEndpoint = ResponseDecorator.handleErrors( - CatalogController.updateCatalogItemEndPoint, - successCode, - errorCodes - ); - const responseObject = await updateCatalogItemEndpoint(req); + CatalogController.updateCatalogItemEndPoint, + successCode, + errorCodes + ) + const responseObject = await updateCatalogItemEndpoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'delete', path: '/api/v3/catalog/microservices/:id', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] const deleteCatalogItemEndPoint = ResponseDecorator.handleErrors( - CatalogController.deleteCatalogItemEndPoint, - successCode, - errorCodes - ); - const responseObject = await deleteCatalogItemEndPoint(req); + CatalogController.deleteCatalogItemEndPoint, + successCode, + errorCodes + ) + const responseObject = await deleteCatalogItemEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } - } + logger.apiRes({req: req, res: responseObject}) + }, + }, ] diff --git a/src/routes/controller.js b/src/routes/controller.js index 8c9ccd17a..8da2bb4da 100644 --- a/src/routes/controller.js +++ b/src/routes/controller.js @@ -10,65 +10,64 @@ * ******************************************************************************* * */ -const constants = require('../helpers/constants'); -const Controller = require('../controllers/controller'); -const ResponseDecorator = require('../decorators/response-decorator'); -const Errors = require('../helpers/errors'); -const logger = require('../logger'); +const constants = require('../helpers/constants') +const Controller = require('../controllers/controller') +const ResponseDecorator = require('../decorators/response-decorator') +const logger = require('../logger') module.exports = [ { method: 'get', path: '/api/v3/status', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; - const errorCodes = []; - const statusControllerEndPoint = ResponseDecorator.handleErrors(Controller.statusControllerEndPoint, successCode, errorCodes); - const responseObject = await statusControllerEndPoint(req); + const successCode = constants.HTTP_CODE_SUCCESS + const errorCodes = [] + const statusControllerEndPoint = ResponseDecorator.handleErrors(Controller.statusControllerEndPoint, successCode, errorCodes) + const responseObject = await statusControllerEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/email-activation', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; - const errorCodes = []; - const emailActivationEndPoint = ResponseDecorator.handleErrors(Controller.emailActivationEndPoint, successCode, errorCodes); - const responseObject = await emailActivationEndPoint(req); + const successCode = constants.HTTP_CODE_SUCCESS + const errorCodes = [] + const emailActivationEndPoint = ResponseDecorator.handleErrors(Controller.emailActivationEndPoint, successCode, errorCodes) + const responseObject = await emailActivationEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/fog-types/', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; - const errorCodes = []; - const fogTypesEndPoint = ResponseDecorator.handleErrors(Controller.fogTypesEndPoint, successCode, errorCodes); - const responseObject = await fogTypesEndPoint(req); + const successCode = constants.HTTP_CODE_SUCCESS + const errorCodes = [] + const fogTypesEndPoint = ResponseDecorator.handleErrors(Controller.fogTypesEndPoint, successCode, errorCodes) + const responseObject = await fogTypesEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } - } -]; + logger.apiRes({req: req, res: responseObject}) + }, + }, +] diff --git a/src/routes/diagnostics.js b/src/routes/diagnostics.js index eb0d9de58..a1d21d9a5 100644 --- a/src/routes/diagnostics.js +++ b/src/routes/diagnostics.js @@ -10,192 +10,192 @@ * ******************************************************************************* * */ -const constants = require('../helpers/constants'); -const DiagnosticController = require('../controllers/diagnostic-controller'); -const ResponseDecorator = require('../decorators/response-decorator'); -const Errors = require('../helpers/errors'); -const fs = require('fs'); -const logger = require('../logger'); +const constants = require('../helpers/constants') +const DiagnosticController = require('../controllers/diagnostic-controller') +const ResponseDecorator = require('../decorators/response-decorator') +const Errors = require('../helpers/errors') +const fs = require('fs') +const logger = require('../logger') module.exports = [ { method: 'post', path: '/api/v3/microservices/:uuid/image-snapshot', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_CREATED; + const successCode = constants.HTTP_CODE_CREATED const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] const createMicroserviceImageSnapshotEndPoint = ResponseDecorator.handleErrors( - DiagnosticController.createMicroserviceImageSnapshotEndPoint, - successCode, - errorCodes - ); - const responseObject = await createMicroserviceImageSnapshotEndPoint(req); + DiagnosticController.createMicroserviceImageSnapshotEndPoint, + successCode, + errorCodes + ) + const responseObject = await createMicroserviceImageSnapshotEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/microservices/:uuid/image-snapshot', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] const getMicroserviceImageSnapshotEndPoint = ResponseDecorator.handleErrors( - DiagnosticController.getMicroserviceImageSnapshotEndPoint, - successCode, - errorCodes - ); - const responseObject = await getMicroserviceImageSnapshotEndPoint(req); + DiagnosticController.getMicroserviceImageSnapshotEndPoint, + successCode, + errorCodes + ) + const responseObject = await getMicroserviceImageSnapshotEndPoint(req) if (responseObject.code !== successCode) { res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); + logger.apiRes({req: req, res: responseObject}) } else { res.writeHead(successCode, { - "Content-Length": responseObject.body['Content-Length'], - "Content-Type": responseObject.body['Content-Type'], - "Content-Disposition": "attachment; filename=" + responseObject.body.fileName - }); - fs.createReadStream(responseObject.body.filePath).pipe(res); + 'Content-Length': responseObject.body['Content-Length'], + 'Content-Type': responseObject.body['Content-Type'], + 'Content-Disposition': 'attachment; filename=' + responseObject.body.fileName, + }) + fs.createReadStream(responseObject.body.filePath).pipe(res) } - } + }, }, { method: 'patch', path: '/api/v3/microservices/:uuid/strace', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] + errors: [Errors.NotFoundError], }, { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] const changeMicroserviceStraceStateEndPoint = ResponseDecorator.handleErrors( - DiagnosticController.changeMicroserviceStraceStateEndPoint, - successCode, - errorCodes - ); - const responseObject = await changeMicroserviceStraceStateEndPoint(req); + DiagnosticController.changeMicroserviceStraceStateEndPoint, + successCode, + errorCodes + ) + const responseObject = await changeMicroserviceStraceStateEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/microservices/:uuid/strace', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] const getMicroserviceStraceDataEndPoint = ResponseDecorator.handleErrors( - DiagnosticController.getMicroserviceStraceDataEndPoint, - successCode, - errorCodes - ); - const responseObject = await getMicroserviceStraceDataEndPoint(req); + DiagnosticController.getMicroserviceStraceDataEndPoint, + successCode, + errorCodes + ) + const responseObject = await getMicroserviceStraceDataEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'put', path: '/api/v3/microservices/:uuid/strace', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] + errors: [Errors.NotFoundError], }, { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_INTERNAL_ERROR, - errors: [Errors.FtpError] - } - ]; + errors: [Errors.FtpError], + }, + ] const postMicroserviceStraceDataToFtpEndPoint = ResponseDecorator.handleErrors( - DiagnosticController.postMicroserviceStraceDataToFtpEndPoint, - successCode, - errorCodes - ); - const responseObject = await postMicroserviceStraceDataToFtpEndPoint(req); + DiagnosticController.postMicroserviceStraceDataToFtpEndPoint, + successCode, + errorCodes + ) + const responseObject = await postMicroserviceStraceDataToFtpEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } - } -]; + logger.apiRes({req: req, res: responseObject}) + }, + }, +] diff --git a/src/routes/flow.js b/src/routes/flow.js index c94d2f994..baab5ba26 100644 --- a/src/routes/flow.js +++ b/src/routes/flow.js @@ -10,151 +10,151 @@ * ******************************************************************************* * */ -const constants = require('../helpers/constants'); -const FlowController = require('../controllers/flow-controller'); -const ResponseDecorator = require('../decorators/response-decorator'); -const Errors = require('../helpers/errors'); -const logger = require('../logger'); +const constants = require('../helpers/constants') +const FlowController = require('../controllers/flow-controller') +const ResponseDecorator = require('../decorators/response-decorator') +const Errors = require('../helpers/errors') +const logger = require('../logger') module.exports = [ { method: 'get', path: '/api/v3/flow', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const getFlowsByUserEndPoint = ResponseDecorator.handleErrors(FlowController.getFlowsByUserEndPoint, successCode, errorCodes); - const responseObject = await getFlowsByUserEndPoint(req); + const getFlowsByUserEndPoint = ResponseDecorator.handleErrors(FlowController.getFlowsByUserEndPoint, successCode, errorCodes) + const responseObject = await getFlowsByUserEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'post', path: '/api/v3/flow', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_CREATED; + const successCode = constants.HTTP_CODE_CREATED const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const createFlowEndPoint = ResponseDecorator.handleErrors(FlowController.createFlowEndPoint, successCode, errorCodes); - const responseObject = await createFlowEndPoint(req); + const createFlowEndPoint = ResponseDecorator.handleErrors(FlowController.createFlowEndPoint, successCode, errorCodes) + const responseObject = await createFlowEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/flow/:id', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const getFlowEndPoint = ResponseDecorator.handleErrors(FlowController.getFlowEndPoint, successCode, errorCodes); - const responseObject = await getFlowEndPoint(req); + const getFlowEndPoint = ResponseDecorator.handleErrors(FlowController.getFlowEndPoint, successCode, errorCodes) + const responseObject = await getFlowEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'patch', path: '/api/v3/flow/:id', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const updateFlowEndPoint = ResponseDecorator.handleErrors(FlowController.updateFlowEndPoint, successCode, errorCodes); - const responseObject = await updateFlowEndPoint(req); + const updateFlowEndPoint = ResponseDecorator.handleErrors(FlowController.updateFlowEndPoint, successCode, errorCodes) + const responseObject = await updateFlowEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'delete', path: '/api/v3/flow/:id', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const deleteFlowEndPoint = ResponseDecorator.handleErrors(FlowController.deleteFlowEndPoint, successCode, errorCodes); - const responseObject = await deleteFlowEndPoint(req); + const deleteFlowEndPoint = ResponseDecorator.handleErrors(FlowController.deleteFlowEndPoint, successCode, errorCodes) + const responseObject = await deleteFlowEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, -]; \ No newline at end of file +] diff --git a/src/routes/iofog.js b/src/routes/iofog.js index f9d6ba949..f5eb6de3a 100644 --- a/src/routes/iofog.js +++ b/src/routes/iofog.js @@ -10,304 +10,308 @@ * ******************************************************************************* * */ -const constants = require('../helpers/constants'); -const FogController = require('../controllers/iofog-controller'); -const ResponseDecorator = require('../decorators/response-decorator'); -const Errors = require('../helpers/errors'); -const logger = require('../logger'); +const constants = require('../helpers/constants') +const FogController = require('../controllers/iofog-controller') +const ResponseDecorator = require('../decorators/response-decorator') +const Errors = require('../helpers/errors') +const logger = require('../logger') module.exports = [ { method: 'get', path: '/api/v3/iofog-list', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errCodes = [ { code: 400, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: 401, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const getFogList = ResponseDecorator.handleErrors(FogController.getFogListEndPoint, successCode, errCodes); - const responseObject = await getFogList(req); + const getFogList = ResponseDecorator.handleErrors(FogController.getFogListEndPoint, successCode, errCodes) + const responseObject = await getFogList(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'post', path: '/api/v3/iofog', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_CREATED; + const successCode = constants.HTTP_CODE_CREATED const errCodes = [ { code: 400, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: 401, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const createFog = ResponseDecorator.handleErrors(FogController.createFogEndPoint, successCode, errCodes); - const responseObject = await createFog(req); + const createFog = ResponseDecorator.handleErrors(FogController.createFogEndPoint, successCode, errCodes) + const responseObject = await createFog(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'patch', path: '/api/v3/iofog/:uuid', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errCodes = [ { code: 400, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: 401, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: 404, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const updateFog = ResponseDecorator.handleErrors(FogController.updateFogEndPoint, successCode, errCodes); - const responseObject = await updateFog(req); + const updateFog = ResponseDecorator.handleErrors(FogController.updateFogEndPoint, successCode, errCodes) + const responseObject = await updateFog(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'delete', path: '/api/v3/iofog/:uuid', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_ACCEPTED; + const successCode = constants.HTTP_CODE_ACCEPTED const errCodes = [ { code: 401, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: 404, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const deleteFog = ResponseDecorator.handleErrors(FogController.deleteFogEndPoint, successCode, errCodes); - const responseObject = await deleteFog(req); + const deleteFog = ResponseDecorator.handleErrors(FogController.deleteFogEndPoint, successCode, errCodes) + const responseObject = await deleteFog(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/iofog/:uuid', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errCodes = [ { code: 401, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: 404, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const getFog = ResponseDecorator.handleErrors(FogController.getFogEndPoint, successCode, errCodes); - const responseObject = await getFog(req); + const getFog = ResponseDecorator.handleErrors(FogController.getFogEndPoint, successCode, errCodes) + const responseObject = await getFog(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/iofog/:uuid/provisioning-key', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_CREATED; + const successCode = constants.HTTP_CODE_CREATED const errCodes = [ { code: 401, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: 404, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const generateFogProvisioningKey = ResponseDecorator.handleErrors(FogController.generateProvisioningKeyEndPoint, successCode, errCodes); - const responseObject = await generateFogProvisioningKey(req); + const generateFogProvisioningKey = ResponseDecorator.handleErrors(FogController.generateProvisioningKeyEndPoint, + successCode, errCodes) + const responseObject = await generateFogProvisioningKey(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'post', path: '/api/v3/iofog/:uuid/version/:versionCommand', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errCodes = [ { code: 400, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: 401, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: 404, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const setFogVersionCommand = ResponseDecorator.handleErrors(FogController.setFogVersionCommandEndPoint, successCode, errCodes); - const responseObject = await setFogVersionCommand(req); + const setFogVersionCommand = ResponseDecorator.handleErrors(FogController.setFogVersionCommandEndPoint, + successCode, errCodes) + const responseObject = await setFogVersionCommand(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'post', path: '/api/v3/iofog/:uuid/reboot', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errCodes = [ { code: 400, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: 401, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: 404, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const setFogRebootCommand = ResponseDecorator.handleErrors(FogController.setFogRebootCommandEndPoint, successCode, errCodes); - const responseObject = await setFogRebootCommand(req); + const setFogRebootCommand = ResponseDecorator.handleErrors(FogController.setFogRebootCommandEndPoint, + successCode, errCodes) + const responseObject = await setFogRebootCommand(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/iofog/:uuid/hal/hw', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errCodes = [ { code: 401, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: 404, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const getHalHardwareInfo = ResponseDecorator.handleErrors(FogController.getHalHardwareInfoEndPoint, successCode, errCodes); - const responseObject = await getHalHardwareInfo(req); + const getHalHardwareInfo = ResponseDecorator.handleErrors(FogController.getHalHardwareInfoEndPoint, + successCode, errCodes) + const responseObject = await getHalHardwareInfo(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/iofog/:uuid/hal/usb', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errCodes = [ { code: 401, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: 404, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const getHalUsbInfo = ResponseDecorator.handleErrors(FogController.getHalUsbInfoEndPoint, successCode, errCodes); - const responseObject = await getHalUsbInfo(req); + const getHalUsbInfo = ResponseDecorator.handleErrors(FogController.getHalUsbInfoEndPoint, successCode, errCodes) + const responseObject = await getHalUsbInfo(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } - } -]; \ No newline at end of file + logger.apiRes({req: req, res: responseObject}) + }, + }, +] diff --git a/src/routes/microservices.js b/src/routes/microservices.js index 218efcb90..7ffb7cf79 100644 --- a/src/routes/microservices.js +++ b/src/routes/microservices.js @@ -10,408 +10,418 @@ * ******************************************************************************* * */ -const constants = require('../helpers/constants'); -const MicroservicesController = require('../controllers/microservices-controller'); -const ResponseDecorator = require('../decorators/response-decorator'); -const Errors = require('../helpers/errors'); -const logger = require('../logger'); +const constants = require('../helpers/constants') +const MicroservicesController = require('../controllers/microservices-controller') +const ResponseDecorator = require('../decorators/response-decorator') +const Errors = require('../helpers/errors') +const logger = require('../logger') module.exports = [ { - method: 'get', - path: '/api/v3/microservices/', - middleware: async (req, res) => { - logger.apiReq(req); - - const successCode = constants.HTTP_CODE_SUCCESS; - const errorCodes = [ - { - code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; - - const getMicroservicesByFlowEndPoint = ResponseDecorator.handleErrors(MicroservicesController.getMicroservicesByFlowEndPoint, successCode, errorCodes); - const responseObject = await getMicroservicesByFlowEndPoint(req); - - res - .status(responseObject.code) - .send(responseObject.body); - - logger.apiRes({req: req, res: responseObject}); - } + method: 'get', + path: '/api/v3/microservices/', + middleware: async (req, res) => { + logger.apiReq(req) + + const successCode = constants.HTTP_CODE_SUCCESS + const errorCodes = [ + { + code: constants.HTTP_CODE_UNAUTHORIZED, + errors: [Errors.AuthenticationError], + }, + ] + + const getMicroservicesByFlowEndPoint = ResponseDecorator.handleErrors(MicroservicesController.getMicroservicesByFlowEndPoint, + successCode, errorCodes) + const responseObject = await getMicroservicesByFlowEndPoint(req) + + res + .status(responseObject.code) + .send(responseObject.body) + + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'post', path: '/api/v3/microservices', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_CREATED; + const successCode = constants.HTTP_CODE_CREATED const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const createMicroservicesOnFogEndPoint = ResponseDecorator.handleErrors(MicroservicesController.createMicroserviceOnFogEndPoint, successCode, errorCodes); - const responseObject = await createMicroservicesOnFogEndPoint(req); + const createMicroservicesOnFogEndPoint = ResponseDecorator.handleErrors( + MicroservicesController.createMicroserviceOnFogEndPoint, successCode, errorCodes) + const responseObject = await createMicroservicesOnFogEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/microservices/:uuid', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const getMicroserviceEndPoint = ResponseDecorator.handleErrors(MicroservicesController.getMicroserviceEndPoint, successCode, errorCodes); - const responseObject = await getMicroserviceEndPoint(req); + const getMicroserviceEndPoint = ResponseDecorator.handleErrors(MicroservicesController.getMicroserviceEndPoint, + successCode, errorCodes) + const responseObject = await getMicroserviceEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'patch', path: '/api/v3/microservices/:uuid', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const updateMicroserviceEndPoint = ResponseDecorator.handleErrors(MicroservicesController.updateMicroserviceEndPoint, successCode, errorCodes); - const responseObject = await updateMicroserviceEndPoint(req); + const updateMicroserviceEndPoint = ResponseDecorator.handleErrors(MicroservicesController.updateMicroserviceEndPoint, + successCode, errorCodes) + const responseObject = await updateMicroserviceEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'delete', path: '/api/v3/microservices/:uuid', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const deleteMicroserviceEndPoint = ResponseDecorator.handleErrors(MicroservicesController.deleteMicroserviceEndPoint, successCode, errorCodes); - const responseObject = await deleteMicroserviceEndPoint(req); + const deleteMicroserviceEndPoint = ResponseDecorator.handleErrors(MicroservicesController.deleteMicroserviceEndPoint, + successCode, errorCodes) + const responseObject = await deleteMicroserviceEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'post', path: '/api/v3/microservices/:uuid/routes/:receiverUuid', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const createMicroserviceRouteEndPoint = ResponseDecorator.handleErrors(MicroservicesController.createMicroserviceRouteEndPoint, successCode, errorCodes); - const responseObject = await createMicroserviceRouteEndPoint(req); + const createMicroserviceRouteEndPoint = ResponseDecorator.handleErrors( + MicroservicesController.createMicroserviceRouteEndPoint, successCode, errorCodes) + const responseObject = await createMicroserviceRouteEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); + logger.apiRes({req: req, res: responseObject}) }, }, { method: 'delete', path: '/api/v3/microservices/:uuid/routes/:receiverUuid', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const deleteMicroserviceRouteEndPoint = ResponseDecorator.handleErrors(MicroservicesController.deleteMicroserviceRouteEndPoint, successCode, errorCodes); - const responseObject = await deleteMicroserviceRouteEndPoint(req); + const deleteMicroserviceRouteEndPoint = ResponseDecorator.handleErrors( + MicroservicesController.deleteMicroserviceRouteEndPoint, successCode, errorCodes) + const responseObject = await deleteMicroserviceRouteEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); + logger.apiRes({req: req, res: responseObject}) }, }, { method: 'post', path: '/api/v3/microservices/:uuid/port-mapping', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_CREATED; + const successCode = constants.HTTP_CODE_CREATED const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const createMicroservicePortMappingEndPoint = ResponseDecorator.handleErrors(MicroservicesController.createMicroservicePortMappingEndPoint, successCode, errorCodes); - const responseObject = await createMicroservicePortMappingEndPoint(req); + const createMicroservicePortMappingEndPoint = ResponseDecorator.handleErrors( + MicroservicesController.createMicroservicePortMappingEndPoint, successCode, errorCodes) + const responseObject = await createMicroservicePortMappingEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); + logger.apiRes({req: req, res: responseObject}) }, }, { method: 'delete', path: '/api/v3/microservices/:uuid/port-mapping/:internalPort', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const deleteMicroservicePortMapping = ResponseDecorator.handleErrors(MicroservicesController.deleteMicroservicePortMappingEndPoint, successCode, errorCodes); - const responseObject = await deleteMicroservicePortMapping(req); + const deleteMicroservicePortMapping = ResponseDecorator.handleErrors( + MicroservicesController.deleteMicroservicePortMappingEndPoint, successCode, errorCodes) + const responseObject = await deleteMicroservicePortMapping(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); + logger.apiRes({req: req, res: responseObject}) }, }, { method: 'get', path: '/api/v3/microservices/:uuid/port-mapping', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const getMicroservicePortMapping = ResponseDecorator.handleErrors(MicroservicesController.getMicroservicePortMappingListEndPoint, successCode, errorCodes); - const responseObject = await getMicroservicePortMapping(req); + const getMicroservicePortMapping = ResponseDecorator.handleErrors( + MicroservicesController.getMicroservicePortMappingListEndPoint, successCode, errorCodes) + const responseObject = await getMicroservicePortMapping(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); + logger.apiRes({req: req, res: responseObject}) }, }, { method: 'get', path: '/api/v3/microservices/:uuid/volume-mapping', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] const listMicroserviceVolumeMappingEndPoint = ResponseDecorator.handleErrors( - MicroservicesController.listMicroserviceVolumeMappingsEndPoint, - successCode, - errorCodes - ); - const responseObject = await listMicroserviceVolumeMappingEndPoint(req); + MicroservicesController.listMicroserviceVolumeMappingsEndPoint, + successCode, + errorCodes + ) + const responseObject = await listMicroserviceVolumeMappingEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); + logger.apiRes({req: req, res: responseObject}) }, }, { method: 'post', path: '/api/v3/microservices/:uuid/volume-mapping', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_CREATED; + const successCode = constants.HTTP_CODE_CREATED const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] const createMicroserviceVolumeMappingEndPoint = ResponseDecorator.handleErrors( - MicroservicesController.createMicroserviceVolumeMappingEndPoint, - successCode, - errorCodes - ); - const responseObject = await createMicroserviceVolumeMappingEndPoint(req); + MicroservicesController.createMicroserviceVolumeMappingEndPoint, + successCode, + errorCodes + ) + const responseObject = await createMicroserviceVolumeMappingEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); + logger.apiRes({req: req, res: responseObject}) }, }, { method: 'delete', path: '/api/v3/microservices/:uuid/volume-mapping/:id', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] const deleteMicroserviceVolumeMappingEndPoint = ResponseDecorator.handleErrors( - MicroservicesController.deleteMicroserviceVolumeMappingEndPoint, - successCode, - errorCodes - ); - const responseObject = await deleteMicroserviceVolumeMappingEndPoint(req); + MicroservicesController.deleteMicroserviceVolumeMappingEndPoint, + successCode, + errorCodes + ) + const responseObject = await deleteMicroserviceVolumeMappingEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); + logger.apiRes({req: req, res: responseObject}) }, }, -]; +] diff --git a/src/routes/registries.js b/src/routes/registries.js index fe5bd0a27..df186b429 100644 --- a/src/routes/registries.js +++ b/src/routes/registries.js @@ -11,122 +11,123 @@ * */ const constants = require('../helpers/constants') -const RegistryController = require('../controllers/registry-controller'); -const ResponseDecorator = require('../decorators/response-decorator'); -const Errors = require('../helpers/errors'); -const logger = require('../logger'); +const RegistryController = require('../controllers/registry-controller') +const ResponseDecorator = require('../decorators/response-decorator') +const Errors = require('../helpers/errors') +const logger = require('../logger') module.exports = [ { method: 'post', path: '/api/v3/registries', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_CREATED; + const successCode = constants.HTTP_CODE_CREATED const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; - const registriesEndPoint = ResponseDecorator.handleErrors(RegistryController.createRegistryEndPoint, successCode, errorCodes); - const responseObject = await registriesEndPoint(req); + errors: [Errors.AuthenticationError], + }, + ] + const registriesEndPoint = ResponseDecorator.handleErrors(RegistryController.createRegistryEndPoint, successCode, errorCodes) + const responseObject = await registriesEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/registries', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; - const registriesEndPoint = ResponseDecorator.handleErrors(RegistryController.getRegistriesEndPoint, successCode, errorCodes); - const responseObject = await registriesEndPoint(req); + errors: [Errors.AuthenticationError], + }, + ] + const registriesEndPoint = ResponseDecorator.handleErrors(RegistryController.getRegistriesEndPoint, successCode, errorCodes) + const responseObject = await registriesEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'delete', path: '/api/v3/registries/:id', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; - const registriesEndPoint = ResponseDecorator.handleErrors(RegistryController.deleteRegistryEndPoint, successCode, errorCodes); - const responseObject = await registriesEndPoint(req); + errors: [Errors.NotFoundError], + }, + ] + const registriesEndPoint = ResponseDecorator.handleErrors(RegistryController.deleteRegistryEndPoint, successCode, errorCodes) + const responseObject = await registriesEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'patch', path: '/api/v3/registries/:id', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; - const updateRegistryEndPoint = ResponseDecorator.handleErrors(RegistryController.updateRegistryEndPoint, successCode, errorCodes); - const responseObject = await updateRegistryEndPoint(req); + errors: [Errors.NotFoundError], + }, + ] + const updateRegistryEndPoint = ResponseDecorator.handleErrors(RegistryController.updateRegistryEndPoint, + successCode, errorCodes) + const responseObject = await updateRegistryEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } - } -]; + logger.apiRes({req: req, res: responseObject}) + }, + }, +] diff --git a/src/routes/tunnel.js b/src/routes/tunnel.js index ff33afe94..e3bda9707 100644 --- a/src/routes/tunnel.js +++ b/src/routes/tunnel.js @@ -11,66 +11,66 @@ * */ const constants = require('../helpers/constants') -const TunnelController = require('../controllers/tunnel-controller'); -const ResponseDecorator = require('../decorators/response-decorator'); -const Errors = require('../helpers/errors'); -const logger = require('../logger'); +const TunnelController = require('../controllers/tunnel-controller') +const ResponseDecorator = require('../decorators/response-decorator') +const Errors = require('../helpers/errors') +const logger = require('../logger') module.exports = [ { method: 'patch', path: '/api/v3/iofog/:id/tunnel', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ - { - code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - }, - { - code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - }, - { - code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; - const tunnelEndPoint = ResponseDecorator.handleErrors(TunnelController.manageTunnelEndPoint, successCode, errorCodes); - const responseObject = await tunnelEndPoint(req); + { + code: constants.HTTP_CODE_BAD_REQUEST, + errors: [Errors.ValidationError], + }, + { + code: constants.HTTP_CODE_UNAUTHORIZED, + errors: [Errors.AuthenticationError], + }, + { + code: constants.HTTP_CODE_NOT_FOUND, + errors: [Errors.NotFoundError], + }, + ] + const tunnelEndPoint = ResponseDecorator.handleErrors(TunnelController.manageTunnelEndPoint, successCode, errorCodes) + const responseObject = await tunnelEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/iofog/:id/tunnel', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ - { - code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - }, - { - code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; - const tunnelEndPoint = ResponseDecorator.handleErrors(TunnelController.getTunnelEndPoint, successCode, errorCodes); - const responseObject = await tunnelEndPoint(req); + { + code: constants.HTTP_CODE_UNAUTHORIZED, + errors: [Errors.AuthenticationError], + }, + { + code: constants.HTTP_CODE_NOT_FOUND, + errors: [Errors.NotFoundError], + }, + ] + const tunnelEndPoint = ResponseDecorator.handleErrors(TunnelController.getTunnelEndPoint, successCode, errorCodes) + const responseObject = await tunnelEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } - } -]; \ No newline at end of file + logger.apiRes({req: req, res: responseObject}) + }, + }, +] diff --git a/src/routes/user.js b/src/routes/user.js index 403ddddd0..c9ba0ef44 100644 --- a/src/routes/user.js +++ b/src/routes/user.js @@ -12,268 +12,275 @@ */ const constants = require('../helpers/constants') -const UserController = require('../controllers/user-controller'); -const ResponseDecorator = require('../decorators/response-decorator'); -const Errors = require('../helpers/errors'); +const UserController = require('../controllers/user-controller') +const ResponseDecorator = require('../decorators/response-decorator') +const Errors = require('../helpers/errors') -const Config = require('../config'); -const logger = require('../logger'); +const Config = require('../config') +const logger = require('../logger') module.exports = [ { method: 'post', path: '/api/v3/user/login', middleware: async (req, res) => { - logger.apiReq('POST /api/v3/user/login'); //don't use req as arg, because password not encrypted + logger.apiReq('POST /api/v3/user/login') // don't use req as arg, because password not encrypted - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] + errors: [Errors.ValidationError], }, { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.InvalidCredentialsError] - } - ]; + errors: [Errors.InvalidCredentialsError], + }, + ] - const userLoginEndPoint = ResponseDecorator.handleErrors(UserController.userLoginEndPoint, successCode, errorCodes); - const responseObject = await userLoginEndPoint(req); + const userLoginEndPoint = ResponseDecorator.handleErrors(UserController.userLoginEndPoint, successCode, errorCodes) + const responseObject = await userLoginEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes('POST /api/v3/user/login', {args: {statusCode: responseObject.code}}); //don't use req and responseObject as args, because they have password and token - } + logger.apiRes('POST /api/v3/user/login', {args: {statusCode: responseObject.code}}) + // don't use req and responseObject as args, because they have password and token + }, }, { method: 'post', path: '/api/v3/user/logout', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const userLogoutEndPoint = ResponseDecorator.handleErrors(UserController.userLogoutEndPoint, successCode, errorCodes); - const responseObject = await userLogoutEndPoint(req); + const userLogoutEndPoint = ResponseDecorator.handleErrors(UserController.userLogoutEndPoint, successCode, errorCodes) + const responseObject = await userLogoutEndPoint(req) res - .status(responseObject.code) - .send() - } + .status(responseObject.code) + .send() + }, }, { method: 'post', path: '/api/v3/user/signup', middleware: async (req, res) => { - logger.apiReq('POST /api/v3/user/signup'); //don't use req as arg, because password not encrypted + logger.apiReq('POST /api/v3/user/signup') // don't use req as arg, because password not encrypted - const successCode = constants.HTTP_CODE_CREATED; + const successCode = constants.HTTP_CODE_CREATED const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] - const userSignupEndPoint = ResponseDecorator.handleErrors(UserController.userSignupEndPoint, successCode, errorCodes); - const responseObject = await userSignupEndPoint(req); + const userSignupEndPoint = ResponseDecorator.handleErrors(UserController.userSignupEndPoint, successCode, errorCodes) + const responseObject = await userSignupEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/user/signup/resend-activation', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] - const resendActivationEndPoint = ResponseDecorator.handleErrors(UserController.resendActivationEndPoint, successCode, errorCodes); - const responseObject = await resendActivationEndPoint(req); + const resendActivationEndPoint = ResponseDecorator.handleErrors(UserController.resendActivationEndPoint, + successCode, errorCodes) + const responseObject = await resendActivationEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'post', path: '/api/v3/user/activate', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SEE_OTHER; + const successCode = constants.HTTP_CODE_SEE_OTHER const errorCodes = [ { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const activateUserEndPoint = ResponseDecorator.handleErrors(UserController.activateUserAccountEndPoint, successCode, errorCodes); - const responseObject = await activateUserEndPoint(req); + const activateUserEndPoint = ResponseDecorator.handleErrors(UserController.activateUserAccountEndPoint, + successCode, errorCodes) + const responseObject = await activateUserEndPoint(req) // redirect to login page if (responseObject.code === successCode) { - res.setHeader('Location', Config.get('Email:HomeUrl')); + res.setHeader('Location', Config.get('Email:HomeUrl')) } res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'get', path: '/api/v3/user/profile', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const getUserProfileEndPoint = ResponseDecorator.handleErrors(UserController.getUserProfileEndPoint, successCode, errorCodes); - const responseObject = await getUserProfileEndPoint(req); + const getUserProfileEndPoint = ResponseDecorator.handleErrors(UserController.getUserProfileEndPoint, successCode, errorCodes) + const responseObject = await getUserProfileEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'patch', path: '/api/v3/user/profile', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_SUCCESS; + const successCode = constants.HTTP_CODE_SUCCESS const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] - const updateUserProfileEndPoint = ResponseDecorator.handleErrors(UserController.updateUserProfileEndPoint, successCode, errorCodes); - const responseObject = await updateUserProfileEndPoint(req); + const updateUserProfileEndPoint = ResponseDecorator.handleErrors(UserController.updateUserProfileEndPoint, + successCode, errorCodes) + const responseObject = await updateUserProfileEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'delete', path: '/api/v3/user/profile', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] - } - ]; + errors: [Errors.AuthenticationError], + }, + ] - const deleteUserProfileEndPoint = ResponseDecorator.handleErrors(UserController.deleteUserProfileEndPoint, successCode, errorCodes); - const responseObject = await deleteUserProfileEndPoint(req); + const deleteUserProfileEndPoint = ResponseDecorator.handleErrors(UserController.deleteUserProfileEndPoint, + successCode, errorCodes) + const responseObject = await deleteUserProfileEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'patch', path: '/api/v3/user/password', middleware: async (req, res) => { - logger.apiReq('PATCH /api/v3/user/password'); //don't use req as arg, because password not encrypted + logger.apiReq('PATCH /api/v3/user/password') // don't use req as arg, because password not encrypted - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_UNAUTHORIZED, - errors: [Errors.AuthenticationError] + errors: [Errors.AuthenticationError], }, { code: constants.HTTP_CODE_BAD_REQUEST, - errors: [Errors.ValidationError] - } - ]; + errors: [Errors.ValidationError], + }, + ] - const updateUserPasswordEndPoint = ResponseDecorator.handleErrors(UserController.updateUserPasswordEndPoint, successCode, errorCodes); - const responseObject = await updateUserPasswordEndPoint(req); + const updateUserPasswordEndPoint = ResponseDecorator.handleErrors(UserController.updateUserPasswordEndPoint, + successCode, errorCodes) + const responseObject = await updateUserPasswordEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } + logger.apiRes({req: req, res: responseObject}) + }, }, { method: 'delete', path: '/api/v3/user/password', middleware: async (req, res) => { - logger.apiReq(req); + logger.apiReq(req) - const successCode = constants.HTTP_CODE_NO_CONTENT; + const successCode = constants.HTTP_CODE_NO_CONTENT const errorCodes = [ { code: constants.HTTP_CODE_NOT_FOUND, - errors: [Errors.NotFoundError] - } - ]; + errors: [Errors.NotFoundError], + }, + ] - const resetUserPasswordEndPoint = ResponseDecorator.handleErrors(UserController.resetUserPasswordEndPoint, successCode, errorCodes); - const responseObject = await resetUserPasswordEndPoint(req); + const resetUserPasswordEndPoint = ResponseDecorator.handleErrors(UserController.resetUserPasswordEndPoint, + successCode, errorCodes) + const responseObject = await resetUserPasswordEndPoint(req) res - .status(responseObject.code) - .send(responseObject.body); + .status(responseObject.code) + .send(responseObject.body) - logger.apiRes({req: req, res: responseObject}); - } - } -]; \ No newline at end of file + logger.apiRes({req: req, res: responseObject}) + }, + }, +] diff --git a/src/schemas/agent.js b/src/schemas/agent.js index 37b5498d5..74891c787 100644 --- a/src/schemas/agent.js +++ b/src/schemas/agent.js @@ -12,175 +12,175 @@ */ const agentProvision = { - "id": "/agentProvision", - "type": "object", - "properties": { - "type": {"type": "integer", "minimum": 0, "maximum": 2}, - "key": {"type": "string"} + 'id': '/agentProvision', + 'type': 'object', + 'properties': { + 'type': {'type': 'integer', 'minimum': 0, 'maximum': 2}, + 'key': {'type': 'string'}, }, - "required": ["type", "key"], - "additionalProperties": false -}; + 'required': ['type', 'key'], + 'additionalProperties': false, +} const agentDeprovision = { - "id": "/agentDeprovision", - "type": "object", - "properties": { - "microserviceUuids": { - "type": "array", - "items": {"type": "string"} - } + 'id': '/agentDeprovision', + 'type': 'object', + 'properties': { + 'microserviceUuids': { + 'type': 'array', + 'items': {'type': 'string'}, + }, }, - "required": ["microserviceUuids"], - "additionalProperties": false -}; + 'required': ['microserviceUuids'], + 'additionalProperties': false, +} const updateAgentConfig = { - "id": "/updateAgentConfig", - "type": "object", - "properties": { - "networkInterface": {"type": "string"}, - "dockerUrl": {"type": "string"}, - "diskLimit": {"type": "integer", "minimum": 0}, - "diskDirectory": {"type": "string"}, - "memoryLimit": {"type": "integer", "minimum": 0}, - "cpuLimit": {"type": "integer", "minimum": 0}, - "logLimit": {"type": "integer", "minimum": 0}, - "logDirectory": {"type": "string"}, - "logFileCount": {"type": "integer", "minimum": 0}, - "statusFrequency": {"type": "integer", "minimum": 0}, - "changeFrequency": {"type": "integer", "minimum": 0}, - "deviceScanFrequency": {"type": "integer", "minimum": 0}, - "watchdogEnabled": {"type": "boolean"}, - "latitude": {"type": "number", "minimum": -90, "maximum": 90}, - "longitude": {"type": "number", "minimum": -180, "maximum": 180}, - "gpsMode": {"type": "string"} + 'id': '/updateAgentConfig', + 'type': 'object', + 'properties': { + 'networkInterface': {'type': 'string'}, + 'dockerUrl': {'type': 'string'}, + 'diskLimit': {'type': 'integer', 'minimum': 0}, + 'diskDirectory': {'type': 'string'}, + 'memoryLimit': {'type': 'integer', 'minimum': 0}, + 'cpuLimit': {'type': 'integer', 'minimum': 0}, + 'logLimit': {'type': 'integer', 'minimum': 0}, + 'logDirectory': {'type': 'string'}, + 'logFileCount': {'type': 'integer', 'minimum': 0}, + 'statusFrequency': {'type': 'integer', 'minimum': 0}, + 'changeFrequency': {'type': 'integer', 'minimum': 0}, + 'deviceScanFrequency': {'type': 'integer', 'minimum': 0}, + 'watchdogEnabled': {'type': 'boolean'}, + 'latitude': {'type': 'number', 'minimum': -90, 'maximum': 90}, + 'longitude': {'type': 'number', 'minimum': -180, 'maximum': 180}, + 'gpsMode': {'type': 'string'}, }, - "additionalProperties": false -}; + 'additionalProperties': false, +} const updateAgentStatus = { - "id": "/updateAgentStatus", - "type": "object", - "properties": { - "daemonStatus": {"type": "string"}, - "daemonOperatingDuration": {"type": "integer", "minimum": 0}, - "daemonLastStart": {"type": "integer", "minimum": 0}, - "memoryUsage": {"type": "number", "minimum": 0}, - "diskUsage": {"type": "number", "minimum": 0}, - "cpuUsage": {"type": "number", "minimum": 0}, - "memoryViolation": {"type": "boolean"}, - "diskViolation": {"type": "boolean"}, - "cpuViolation": {"type": "boolean"}, - "microserviceStatus": {"type": "string"}, - "repositoryCount": {"type": "integer", "minimum": 0}, - "repositoryStatus": {"type": "string"}, - "systemTime": {"type": "integer", "minimum": 0}, - "lastStatusTime": {"type": "integer", "minimum": 0}, - "ipAddress": {"type": "string"}, - "processedMessages": {"type": "integer", "minimum": 0}, - "microserviceMessageCounts": {"type": "string"}, - "messageSpeed": {"type": "number", "minimum": 0}, - "lastCommandTime": {"type": "integer", "minimum": 0}, - "tunnelStatus": {"type": "string"}, - "version": {"type": "string"}, - "isReadyToUpgrade": {"type": "boolean"}, - "isReadyToRollback": {"type": "boolean"} + 'id': '/updateAgentStatus', + 'type': 'object', + 'properties': { + 'daemonStatus': {'type': 'string'}, + 'daemonOperatingDuration': {'type': 'integer', 'minimum': 0}, + 'daemonLastStart': {'type': 'integer', 'minimum': 0}, + 'memoryUsage': {'type': 'number', 'minimum': 0}, + 'diskUsage': {'type': 'number', 'minimum': 0}, + 'cpuUsage': {'type': 'number', 'minimum': 0}, + 'memoryViolation': {'type': 'boolean'}, + 'diskViolation': {'type': 'boolean'}, + 'cpuViolation': {'type': 'boolean'}, + 'microserviceStatus': {'type': 'string'}, + 'repositoryCount': {'type': 'integer', 'minimum': 0}, + 'repositoryStatus': {'type': 'string'}, + 'systemTime': {'type': 'integer', 'minimum': 0}, + 'lastStatusTime': {'type': 'integer', 'minimum': 0}, + 'ipAddress': {'type': 'string'}, + 'processedMessages': {'type': 'integer', 'minimum': 0}, + 'microserviceMessageCounts': {'type': 'string'}, + 'messageSpeed': {'type': 'number', 'minimum': 0}, + 'lastCommandTime': {'type': 'integer', 'minimum': 0}, + 'tunnelStatus': {'type': 'string'}, + 'version': {'type': 'string'}, + 'isReadyToUpgrade': {'type': 'boolean'}, + 'isReadyToRollback': {'type': 'boolean'}, }, - "additionalProperties": false -}; + 'additionalProperties': false, +} const updateAgentStrace = { - "id": "/updateAgentStrace", - "type": "object", - "properties": { - "straceData": { - "type": "array", - "items": {"$ref": "/straceData"}, - "required": [] - } + 'id': '/updateAgentStrace', + 'type': 'object', + 'properties': { + 'straceData': { + 'type': 'array', + 'items': {'$ref': '/straceData'}, + 'required': [], + }, }, - "additionalProperties": false -}; + 'additionalProperties': false, +} const straceData = { - "id": "/straceData", - "type": "object", - "properties": { - "microserviceUuid": {"type": "string"}, - "buffer": {"type": "string"} + 'id': '/straceData', + 'type': 'object', + 'properties': { + 'microserviceUuid': {'type': 'string'}, + 'buffer': {'type': 'string'}, }, - "required": ["microserviceUuid", "buffer"], - "additionalProperties": false -}; + 'required': ['microserviceUuid', 'buffer'], + 'additionalProperties': false, +} const microserviceStatus = { - "id": "/microserviceStatus", - "type": "object", - "properties": { - "id": {"type": "string"}, - "containerId": {"type": "string"}, - "status": {"type": "string"}, - "startTime": {"type": "integer"}, - "operatingDuration": {"type": "integer"}, - "cpuUsage": {"type": "number"}, - "memoryUsage": {"type": "number"} + 'id': '/microserviceStatus', + 'type': 'object', + 'properties': { + 'id': {'type': 'string'}, + 'containerId': {'type': 'string'}, + 'status': {'type': 'string'}, + 'startTime': {'type': 'integer'}, + 'operatingDuration': {'type': 'integer'}, + 'cpuUsage': {'type': 'number'}, + 'memoryUsage': {'type': 'number'}, }, - "required": ["id"], - "additionalProperties": false -}; + 'required': ['id'], + 'additionalProperties': false, +} const updateHardwareInfo = { - "id": "/updateHardwareInfo", - "type": "object", - "properties": { - "info": {"type": "string"}, + 'id': '/updateHardwareInfo', + 'type': 'object', + 'properties': { + 'info': {'type': 'string'}, }, - "required": ["info"], - "additionalProperties": false -}; + 'required': ['info'], + 'additionalProperties': false, +} const updateUsbInfo = { - "id": "/updateUsbInfo", - "type": "object", - "properties": { - "info": {"type": "string"}, + 'id': '/updateUsbInfo', + 'type': 'object', + 'properties': { + 'info': {'type': 'string'}, }, - "required": ["info"], - "additionalProperties": false -}; + 'required': ['info'], + 'additionalProperties': false, +} const trackingArray = { - "id": "/trackingArray", - "type": "array", - "items": {"$ref": "/trackingMessage"} -}; + 'id': '/trackingArray', + 'type': 'array', + 'items': {'$ref': '/trackingMessage'}, +} const trackingMessage = { - "id": "/trackingMessage", - "type": "object", - "properties": { - "uuid": {"type": "string"}, - "sourceType": {"type": "string"}, - "timestamp": {"type": "number"}, - "type": {"type": "string"}, - "data": {"$ref": "/trackingData"}, + 'id': '/trackingMessage', + 'type': 'object', + 'properties': { + 'uuid': {'type': 'string'}, + 'sourceType': {'type': 'string'}, + 'timestamp': {'type': 'number'}, + 'type': {'type': 'string'}, + 'data': {'$ref': '/trackingData'}, }, - "required": ["uuid", "sourceType", "timestamp", "type", "data"], - "additionalProperties": false -}; + 'required': ['uuid', 'sourceType', 'timestamp', 'type', 'data'], + 'additionalProperties': false, +} const trackingData = { - "id": "/trackingData", - "type": "object", - "properties": { + 'id': '/trackingData', + 'type': 'object', + 'properties': { }, - "additionalProperties": true -}; + 'additionalProperties': true, +} module.exports = { mainSchemas: [agentProvision, agentDeprovision, updateAgentConfig, updateAgentStatus, updateAgentStrace, - updateHardwareInfo, updateUsbInfo, trackingArray], - innerSchemas: [straceData, microserviceStatus, trackingData, trackingMessage] -}; \ No newline at end of file + updateHardwareInfo, updateUsbInfo, trackingArray], + innerSchemas: [straceData, microserviceStatus, trackingData, trackingMessage], +} diff --git a/src/schemas/catalog.js b/src/schemas/catalog.js index 43ad63a4d..87ac0f0e6 100644 --- a/src/schemas/catalog.js +++ b/src/schemas/catalog.js @@ -12,84 +12,84 @@ */ const catalogItemCreate = { - "id": "/catalogItemCreate", - "type": "object", - "properties": { - "name": {"type": "string", "minLength": 1}, - "description": {"type": "string"}, - "category": {"type": "string"}, - "publisher": {"type": "string"}, - "diskRequired": {"type": "integer"}, - "ramRequired": {"type": "integer"}, - "picture": {"type": "string"}, - "isPublic": {"type": "boolean"}, - "registryId": {"type": "integer"}, - "configExample": {"type": "string"}, - "images": { - "type": "array", - "minItems": 1, - "maxItems": 2, - "items": {"$ref": "/image"} + 'id': '/catalogItemCreate', + 'type': 'object', + 'properties': { + 'name': {'type': 'string', 'minLength': 1}, + 'description': {'type': 'string'}, + 'category': {'type': 'string'}, + 'publisher': {'type': 'string'}, + 'diskRequired': {'type': 'integer'}, + 'ramRequired': {'type': 'integer'}, + 'picture': {'type': 'string'}, + 'isPublic': {'type': 'boolean'}, + 'registryId': {'type': 'integer'}, + 'configExample': {'type': 'string'}, + 'images': { + 'type': 'array', + 'minItems': 1, + 'maxItems': 2, + 'items': {'$ref': '/image'}, }, - "inputType": {"$ref": "/type"}, - "outputType": {"$ref": "/type"} + 'inputType': {'$ref': '/type'}, + 'outputType': {'$ref': '/type'}, }, - "required": ["name", "registryId", "images"], - "additionalProperties": false -}; + 'required': ['name', 'registryId', 'images'], + 'additionalProperties': false, +} const catalogItemUpdate = { - "id": "/catalogItemUpdate", - "type": "object", - "properties": { - "name": {"type": "string", "minLength": 1}, - "description": {"type": "string"}, - "category": {"type": "string"}, - "publisher": {"type": "string"}, - "diskRequired": {"type": "integer"}, - "ramRequired": {"type": "integer"}, - "picture": {"type": "string"}, - "isPublic": {"type": "boolean"}, - "registryId": {"type": "integer"}, - "configExample": {"type": "string"}, - "images": { - "type": "array", - "maxItems": 2, - "items": {"$ref": "/image"} + 'id': '/catalogItemUpdate', + 'type': 'object', + 'properties': { + 'name': {'type': 'string', 'minLength': 1}, + 'description': {'type': 'string'}, + 'category': {'type': 'string'}, + 'publisher': {'type': 'string'}, + 'diskRequired': {'type': 'integer'}, + 'ramRequired': {'type': 'integer'}, + 'picture': {'type': 'string'}, + 'isPublic': {'type': 'boolean'}, + 'registryId': {'type': 'integer'}, + 'configExample': {'type': 'string'}, + 'images': { + 'type': 'array', + 'maxItems': 2, + 'items': {'$ref': '/image'}, }, - "inputType": {"$ref": "/type"}, - "outputType": {"$ref": "/type"} + 'inputType': {'$ref': '/type'}, + 'outputType': {'$ref': '/type'}, }, - "additionalProperties": false -}; + 'additionalProperties': false, +} const image = { - "id": "/image", - "type": "object", - "properties": { - "containerImage": {"type": "string"}, - "fogTypeId": + 'id': '/image', + 'type': 'object', + 'properties': { + 'containerImage': {'type': 'string'}, + 'fogTypeId': { - "type": "integer", - "minimum": 1, - "maximum": 2 - } + 'type': 'integer', + 'minimum': 1, + 'maximum': 2, + }, }, - "required": ["containerImage", "fogTypeId"], - "additionalProperties": false -}; + 'required': ['containerImage', 'fogTypeId'], + 'additionalProperties': false, +} const type = { - "id": "/type", - "type": "object", - "properties": { - "infoType": {"type": "string"}, - "infoFormat": {"type": "string"} + 'id': '/type', + 'type': 'object', + 'properties': { + 'infoType': {'type': 'string'}, + 'infoFormat': {'type': 'string'}, }, - "additionalProperties": false -}; + 'additionalProperties': false, +} module.exports = { mainSchemas: [catalogItemCreate, catalogItemUpdate], - innerSchemas: [image, type] -}; \ No newline at end of file + innerSchemas: [image, type], +} diff --git a/src/schemas/config.js b/src/schemas/config.js index 4814b3b5f..4806ac910 100644 --- a/src/schemas/config.js +++ b/src/schemas/config.js @@ -12,25 +12,25 @@ */ const configUpdate = { - "id": "/configUpdate", - "type": "object", - "properties": { - "port": {"type": "integer", "minimum": 0, "maximum": 65535}, - "sslCert": {"type": "string"}, - "sslKey": {"type": "string"}, - "intermediateCert": {"type": "string"}, - "emailActivationOn": {"type": "boolean"}, - "emailActivationOff": {"type": "boolean"}, - "homeUrl": {"type": "string"}, - "emailAddress": {"type": "string"}, - "emailPassword": {"type": "string", "minLength": 1}, - "emailService": {"type": "string"}, - "logDir": {"type": "string"}, - "logSize": {"type": "integer"} - } -}; + 'id': '/configUpdate', + 'type': 'object', + 'properties': { + 'port': {'type': 'integer', 'minimum': 0, 'maximum': 65535}, + 'sslCert': {'type': 'string'}, + 'sslKey': {'type': 'string'}, + 'intermediateCert': {'type': 'string'}, + 'emailActivationOn': {'type': 'boolean'}, + 'emailActivationOff': {'type': 'boolean'}, + 'homeUrl': {'type': 'string'}, + 'emailAddress': {'type': 'string'}, + 'emailPassword': {'type': 'string', 'minLength': 1}, + 'emailService': {'type': 'string'}, + 'logDir': {'type': 'string'}, + 'logSize': {'type': 'integer'}, + }, +} module.exports = { mainSchemas: [configUpdate], - innerSchemas: [] -}; + innerSchemas: [], +} diff --git a/src/schemas/connector.js b/src/schemas/connector.js index f62f7bc09..bf57162fa 100644 --- a/src/schemas/connector.js +++ b/src/schemas/connector.js @@ -12,46 +12,46 @@ */ const connectorCreate = { - "id": "/connectorCreate", - "type": "object", - "properties": { - "name": {"type": "string", "minLength": 1}, - "domain": {"type": "string", "minLength": 4}, - "publicIp": {"type": "string", "minLength": 7}, - "cert": {"type": "string"}, - "isSelfSignedCert": {"type": "boolean"}, - "devMode": {"type": "boolean"} + 'id': '/connectorCreate', + 'type': 'object', + 'properties': { + 'name': {'type': 'string', 'minLength': 1}, + 'domain': {'type': 'string', 'minLength': 4}, + 'publicIp': {'type': 'string', 'minLength': 7}, + 'cert': {'type': 'string'}, + 'isSelfSignedCert': {'type': 'boolean'}, + 'devMode': {'type': 'boolean'}, }, - "required": ["publicIp", "name", "devMode"], - "additionalProperties": false -}; + 'required': ['publicIp', 'name', 'devMode'], + 'additionalProperties': false, +} const connectorUpdate = { - "id": "/connectorUpdate", - "type": "object", - "properties": { - "name": {"type": "string", "minLength": 1}, - "domain": {"type": "string", "minLength": 4}, - "publicIp": {"type": "string", "minLength": 7}, - "cert": {"type": "string"}, - "isSelfSignedCert": {"type": "boolean"}, - "devMode": {"type": "boolean"} + 'id': '/connectorUpdate', + 'type': 'object', + 'properties': { + 'name': {'type': 'string', 'minLength': 1}, + 'domain': {'type': 'string', 'minLength': 4}, + 'publicIp': {'type': 'string', 'minLength': 7}, + 'cert': {'type': 'string'}, + 'isSelfSignedCert': {'type': 'boolean'}, + 'devMode': {'type': 'boolean'}, }, - "required": ["publicIp"], - "additionalProperties": false -}; + 'required': ['publicIp'], + 'additionalProperties': false, +} const connectorDelete = { - "id": "/connectorDelete", - "type": "object", - "properties": { - "publicIp": {"type": "string", "minLength": 7} + 'id': '/connectorDelete', + 'type': 'object', + 'properties': { + 'publicIp': {'type': 'string', 'minLength': 7}, }, - "required": ["publicIp"], - "additionalProperties": false -}; + 'required': ['publicIp'], + 'additionalProperties': false, +} module.exports = { mainSchemas: [connectorCreate, connectorUpdate, connectorDelete], - innerSchemas: [] -}; \ No newline at end of file + innerSchemas: [], +} diff --git a/src/schemas/diagnostics.js b/src/schemas/diagnostics.js index 12c20b642..35762921a 100644 --- a/src/schemas/diagnostics.js +++ b/src/schemas/diagnostics.js @@ -12,37 +12,37 @@ */ const straceStateUpdate = { - "id": "/straceStateUpdate", - "type": "object", - "properties": { - "enable": {"type": "boolean"} + 'id': '/straceStateUpdate', + 'type': 'object', + 'properties': { + 'enable': {'type': 'boolean'}, }, - "required": ["enable"] -}; + 'required': ['enable'], +} const straceGetData = { - "id": "/straceGetData", - "type": "object", - "properties": { - "format": {"enum": ["string","file"]} + 'id': '/straceGetData', + 'type': 'object', + 'properties': { + 'format': {'enum': ['string', 'file']}, }, - "required": ["format"] -}; + 'required': ['format'], +} const stracePostToFtp = { - "id": "/stracePostToFtp", - "type": "object", - "properties": { - "ftpHost": {"type": "string"}, - "ftpPort": {"type": "integer", "minimum": 0}, - "ftpUser": {"type": "string"}, - "ftpPass": {"type": "string"}, - "ftpDestDir": {"type": "string"}, + 'id': '/stracePostToFtp', + 'type': 'object', + 'properties': { + 'ftpHost': {'type': 'string'}, + 'ftpPort': {'type': 'integer', 'minimum': 0}, + 'ftpUser': {'type': 'string'}, + 'ftpPass': {'type': 'string'}, + 'ftpDestDir': {'type': 'string'}, }, - "required": ["ftpHost","ftpPort","ftpUser","ftpPass","ftpDestDir"] -}; + 'required': ['ftpHost', 'ftpPort', 'ftpUser', 'ftpPass', 'ftpDestDir'], +} module.exports = { mainSchemas: [straceStateUpdate, straceGetData, stracePostToFtp], - innerSchemas: [] -}; \ No newline at end of file + innerSchemas: [], +} diff --git a/src/schemas/flow.js b/src/schemas/flow.js index 9c20be7c1..cb7f17afb 100644 --- a/src/schemas/flow.js +++ b/src/schemas/flow.js @@ -1,27 +1,27 @@ const flowCreate = { - "id": "/flowCreate", - "type": "object", - "properties": { - "name": {"type": "string", "minLength": 1}, - "description": {"type": "string"}, - "isActivated": {"type": "boolean"} + 'id': '/flowCreate', + 'type': 'object', + 'properties': { + 'name': {'type': 'string', 'minLength': 1}, + 'description': {'type': 'string'}, + 'isActivated': {'type': 'boolean'}, }, - "required": ["name"], - "additionalProperties": false -}; + 'required': ['name'], + 'additionalProperties': false, +} const flowUpdate = { - "id": "/flowUpdate", - "type": "object", - "properties": { - "name": {"type": "string", "minLength": 1}, - "description": {"type": "string"}, - "isActivated": {"type": "boolean"} + 'id': '/flowUpdate', + 'type': 'object', + 'properties': { + 'name': {'type': 'string', 'minLength': 1}, + 'description': {'type': 'string'}, + 'isActivated': {'type': 'boolean'}, }, - "additionalProperties": false -}; + 'additionalProperties': false, +} module.exports = { mainSchemas: [flowCreate, flowUpdate], - innerSchemas: [] -}; \ No newline at end of file + innerSchemas: [], +} diff --git a/src/schemas/index.js b/src/schemas/index.js index 492e09d1d..bd805fcad 100644 --- a/src/schemas/index.js +++ b/src/schemas/index.js @@ -11,78 +11,78 @@ * */ -const Validator = require('jsonschema').Validator; -const fs = require('fs'); -const path = require('path'); +const Validator = require('jsonschema').Validator +const fs = require('fs') +const path = require('path') -const basename = path.basename(__filename); +const basename = path.basename(__filename) -const Errors = require('../helpers/errors'); +const Errors = require('../helpers/errors') -const v = new Validator(); -const schemas = {}; +const v = new Validator() +const schemas = {} const registerSchema = (schema, schemaName) => { - v.addSchema(schema, schemaName); -}; + v.addSchema(schema, schemaName) +} fs.readdirSync(__dirname) - .filter(file => { - return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); - }) - .forEach(file => { - const allSchemas = require(path.join(__dirname, file)); + .filter((file) => { + return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js') + }) + .forEach((file) => { + const allSchemas = require(path.join(__dirname, file)) - const mainSchemas = allSchemas.mainSchemas; - const innerSchemas = allSchemas.innerSchemas; + const mainSchemas = allSchemas.mainSchemas + const innerSchemas = allSchemas.innerSchemas - mainSchemas.forEach(schema => { - schemas[schema.id.replace('/', '')] = schema; - }); - if (innerSchemas) { - innerSchemas.forEach(schema => { - registerSchema(schema, schema.id); - }); - } - }); + mainSchemas.forEach((schema) => { + schemas[schema.id.replace('/', '')] = schema + }) + if (innerSchemas) { + innerSchemas.forEach((schema) => { + registerSchema(schema, schema.id) + }) + } + }) async function validate(object, schema) { - const response = v.validate(object, schema); + const response = v.validate(object, schema) if (!response.valid) { - await handleValidationError(response.errors[0]); + await handleValidationError(response.errors[0]) } return response } async function handleValidationError(error) { - let message; + let message switch (error.name) { - case "pattern": - message = "Invalid format for field '" + error.property.replace('instance.', '') + "'"; - break; - case "required": - message = "Required field '" + error.argument + "' is missing"; - break; - case "minLength": - case "maxLength": - message = 'Field ' + error.stack.replace('instance.', ''); - break; - case "additionalProperties": - message = "Field '" + error.argument + "' not allowed"; - break; - case "type": - message = "Field '" + error.property.replace('instance.', '') + "' " + error.message; - break; - case "enum": - message = "Field " + error.stack.replace('instance.', ''); - break; - case "minimum": - message = error.stack.replace('instance.', ''); - break; + case 'pattern': + message = 'Invalid format for field \'' + error.property.replace('instance.', '') + '\'' + break + case 'required': + message = 'Required field \'' + error.argument + '\' is missing' + break + case 'minLength': + case 'maxLength': + message = 'Field ' + error.stack.replace('instance.', '') + break + case 'additionalProperties': + message = 'Field \'' + error.argument + '\' not allowed' + break + case 'type': + message = 'Field \'' + error.property.replace('instance.', '') + '\' ' + error.message + break + case 'enum': + message = 'Field ' + error.stack.replace('instance.', '') + break + case 'minimum': + message = error.stack.replace('instance.', '') + break default: - message = JSON.stringify(error); - break; + message = JSON.stringify(error) + break } throw new Errors.ValidationError(message) @@ -90,5 +90,5 @@ async function handleValidationError(error) { module.exports = { validate, - schemas -}; \ No newline at end of file + schemas, +} diff --git a/src/schemas/iofog.js b/src/schemas/iofog.js index 7b429302d..4372926a6 100644 --- a/src/schemas/iofog.js +++ b/src/schemas/iofog.js @@ -12,148 +12,148 @@ */ const iofogCreate = { - "id": "/iofogCreate", - "type": "object", - "properties": { - "name": {"type": "string", "minLength": 1}, - "location": {"type": "string"}, - "latitude": {"type": "number", "minimum": -90, "maximum": 90}, - "longitude": {"type": "number", "minimum": -180, "maximum": 180}, - "description": {"type": "string"}, - "dockerUrl": {"type": "string"}, - "diskLimit": {"type": "integer", "minimum": 0}, - "diskDirectory": {"type": "string"}, - "memoryLimit": {"type": "integer", "minimum": 0}, - "cpuLimit": {"type": "integer", "minimum": 0}, - "logLimit": {"type": "integer", "minimum": 0}, - "logDirectory": {"type": "string"}, - "logFileCount": {"type": "integer", "minimum": 0}, - "statusFrequency": {"type": "integer", "minimum": 0}, - "changeFrequency": {"type": "integer", "minimum": 0}, - "deviceScanFrequency": {"type": "integer", "minimum": 0}, - "bluetoothEnabled": {"type": "boolean"}, - "watchdogEnabled": {"type": "boolean"}, - "abstractedHardwareEnabled": {"type": "boolean"}, - "fogType": {"type": "integer", "minimum": 0, "maximum": 2} + 'id': '/iofogCreate', + 'type': 'object', + 'properties': { + 'name': {'type': 'string', 'minLength': 1}, + 'location': {'type': 'string'}, + 'latitude': {'type': 'number', 'minimum': -90, 'maximum': 90}, + 'longitude': {'type': 'number', 'minimum': -180, 'maximum': 180}, + 'description': {'type': 'string'}, + 'dockerUrl': {'type': 'string'}, + 'diskLimit': {'type': 'integer', 'minimum': 0}, + 'diskDirectory': {'type': 'string'}, + 'memoryLimit': {'type': 'integer', 'minimum': 0}, + 'cpuLimit': {'type': 'integer', 'minimum': 0}, + 'logLimit': {'type': 'integer', 'minimum': 0}, + 'logDirectory': {'type': 'string'}, + 'logFileCount': {'type': 'integer', 'minimum': 0}, + 'statusFrequency': {'type': 'integer', 'minimum': 0}, + 'changeFrequency': {'type': 'integer', 'minimum': 0}, + 'deviceScanFrequency': {'type': 'integer', 'minimum': 0}, + 'bluetoothEnabled': {'type': 'boolean'}, + 'watchdogEnabled': {'type': 'boolean'}, + 'abstractedHardwareEnabled': {'type': 'boolean'}, + 'fogType': {'type': 'integer', 'minimum': 0, 'maximum': 2}, }, - "required": ["name", "fogType"], - "additionalProperties": false -}; + 'required': ['name', 'fogType'], + 'additionalProperties': false, +} const iofogUpdate = { - "id": "/iofogUpdate", - "type": "object", - "properties": { - "uuid": {"type": "string"}, - "name": {"type": "string", "minLength": 1}, - "location": {"type": "string"}, - "latitude": {"type": "number", "minimum": -90, "maximum": 90}, - "longitude": {"type": "number", "minimum": -180, "maximum": 180}, - "description": {"type": "string"}, - "dockerUrl": {"type": "string"}, - "diskLimit": {"type": "integer", "minimum": 0}, - "diskDirectory": {"type": "string"}, - "memoryLimit": {"type": "integer", "minimum": 0}, - "cpuLimit": {"type": "integer", "minimum": 0}, - "logLimit": {"type": "integer", "minimum": 0}, - "logDirectory": {"type": "string"}, - "logFileCount": {"type": "integer", "minimum": 0}, - "statusFrequency": {"type": "integer", "minimum": 0}, - "changeFrequency": {"type": "integer", "minimum": 0}, - "deviceScanFrequency": {"type": "integer", "minimum": 0}, - "bluetoothEnabled": {"type": "boolean"}, - "watchdogEnabled": {"type": "boolean"}, - "abstractedHardwareEnabled": {"type": "boolean"}, - "fogType": {"type": "integer", "minimum": 0, "maximum": 2} + 'id': '/iofogUpdate', + 'type': 'object', + 'properties': { + 'uuid': {'type': 'string'}, + 'name': {'type': 'string', 'minLength': 1}, + 'location': {'type': 'string'}, + 'latitude': {'type': 'number', 'minimum': -90, 'maximum': 90}, + 'longitude': {'type': 'number', 'minimum': -180, 'maximum': 180}, + 'description': {'type': 'string'}, + 'dockerUrl': {'type': 'string'}, + 'diskLimit': {'type': 'integer', 'minimum': 0}, + 'diskDirectory': {'type': 'string'}, + 'memoryLimit': {'type': 'integer', 'minimum': 0}, + 'cpuLimit': {'type': 'integer', 'minimum': 0}, + 'logLimit': {'type': 'integer', 'minimum': 0}, + 'logDirectory': {'type': 'string'}, + 'logFileCount': {'type': 'integer', 'minimum': 0}, + 'statusFrequency': {'type': 'integer', 'minimum': 0}, + 'changeFrequency': {'type': 'integer', 'minimum': 0}, + 'deviceScanFrequency': {'type': 'integer', 'minimum': 0}, + 'bluetoothEnabled': {'type': 'boolean'}, + 'watchdogEnabled': {'type': 'boolean'}, + 'abstractedHardwareEnabled': {'type': 'boolean'}, + 'fogType': {'type': 'integer', 'minimum': 0, 'maximum': 2}, }, - "required": ["uuid"], - "additionalProperties": false -}; + 'required': ['uuid'], + 'additionalProperties': false, +} const iofogDelete = { - "id": "/iofogDelete", - "type": "object", - "properties": { - "uuid": {"type": "string"} + 'id': '/iofogDelete', + 'type': 'object', + 'properties': { + 'uuid': {'type': 'string'}, }, - "required": ["uuid"], - "additionalProperties": false -}; + 'required': ['uuid'], + 'additionalProperties': false, +} const iofogGet = { - "id": "/iofogGet", - "type": "object", - "properties": { - "uuid": {"type": "string"} + 'id': '/iofogGet', + 'type': 'object', + 'properties': { + 'uuid': {'type': 'string'}, }, - "required": ["uuid"], - "additionalProperties": false -}; + 'required': ['uuid'], + 'additionalProperties': false, +} const iofogGenerateProvision = { - "id": "/iofogGenerateProvision", - "type": "object", - "properties": { - "uuid": {"type": "string"} + 'id': '/iofogGenerateProvision', + 'type': 'object', + 'properties': { + 'uuid': {'type': 'string'}, }, - "required": ["uuid"], - "additionalProperties": false -}; + 'required': ['uuid'], + 'additionalProperties': false, +} const iofogSetVersionCommand = { - "id": "/iofogSetVersionCommand", - "type": "object", - "properties": { - "uuid": {"type": "string"}, - "versionCommand": {"enum": ["upgrade", "rollback"]} + 'id': '/iofogSetVersionCommand', + 'type': 'object', + 'properties': { + 'uuid': {'type': 'string'}, + 'versionCommand': {'enum': ['upgrade', 'rollback']}, }, - "required": ["uuid", "versionCommand"], - "additionalProperties": false -}; + 'required': ['uuid', 'versionCommand'], + 'additionalProperties': false, +} const iofogReboot = { - "id": "/iofogReboot", - "type": "object", - "properties": { - "uuid": {"type": "string"} + 'id': '/iofogReboot', + 'type': 'object', + 'properties': { + 'uuid': {'type': 'string'}, }, - "required": ["uuid"], - "additionalProperties": false -}; + 'required': ['uuid'], + 'additionalProperties': false, +} const iofogFilters = { - "id": "/iofogFilters", - "type": "array", - "items": {"$ref": "/filter"}, - "required": [], - "additionalProperties": false -}; + 'id': '/iofogFilters', + 'type': 'array', + 'items': {'$ref': '/filter'}, + 'required': [], + 'additionalProperties': false, +} const filter = { - "id": "/filter", - "type": "object", - "properties": { - "key": {"type": "string"}, - "value": {"type": "string"}, - "condition": {"enum": ["has", "equals"]} + 'id': '/filter', + 'type': 'object', + 'properties': { + 'key': {'type': 'string'}, + 'value': {'type': 'string'}, + 'condition': {'enum': ['has', 'equals']}, }, - "required": ["key", "value", "condition"], - "additionalProperties": false -}; + 'required': ['key', 'value', 'condition'], + 'additionalProperties': false, +} const halGet = { - "id": "/halGet", - "type": "object", - "properties": { - "uuid": {"type": "string"} + 'id': '/halGet', + 'type': 'object', + 'properties': { + 'uuid': {'type': 'string'}, }, - "required": ["uuid"], - "additionalProperties": false -}; + 'required': ['uuid'], + 'additionalProperties': false, +} module.exports = { mainSchemas: [iofogCreate, iofogUpdate, iofogDelete, iofogGet, iofogGenerateProvision, iofogSetVersionCommand, iofogReboot, iofogFilters, halGet], - innerSchemas: [filter] -}; \ No newline at end of file + innerSchemas: [filter], +} diff --git a/src/schemas/microservice.js b/src/schemas/microservice.js index bc80103ef..8853f5e08 100644 --- a/src/schemas/microservice.js +++ b/src/schemas/microservice.js @@ -1,104 +1,104 @@ const microserviceCreate = { - "id": "/microserviceCreate", - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1 + 'id': '/microserviceCreate', + 'type': 'object', + 'properties': { + 'name': { + 'type': 'string', + 'minLength': 1, }, - "config": {"type": "string"}, - "catalogItemId": { - "type": "integer", - "minimum": 4 + 'config': {'type': 'string'}, + 'catalogItemId': { + 'type': 'integer', + 'minimum': 4, }, - "flowId": {"type": "integer"}, - "iofogUuid": {"type": "string"}, - "rootHostAccess": {"type": "boolean"}, - "logSize": {"type": "integer"}, - "imageSnapshot": {"type": "string"}, - "volumeMappings": { - "type": "array", - "items": {"$ref": "/volumeMappings"}}, - "ports": { - "type": "array", - "items": {"$ref": "/ports"}}, - "routes": { - "type": "array", - "items": {"type": "string"}} - }, - "required": ["name", "flowId", "catalogItemId"], - "additionalProperties": false -}; + 'flowId': {'type': 'integer'}, + 'iofogUuid': {'type': 'string'}, + 'rootHostAccess': {'type': 'boolean'}, + 'logSize': {'type': 'integer'}, + 'imageSnapshot': {'type': 'string'}, + 'volumeMappings': { + 'type': 'array', + 'items': {'$ref': '/volumeMappings'}}, + 'ports': { + 'type': 'array', + 'items': {'$ref': '/ports'}}, + 'routes': { + 'type': 'array', + 'items': {'type': 'string'}}, + }, + 'required': ['name', 'flowId', 'catalogItemId'], + 'additionalProperties': false, +} const microserviceUpdate = { - "id": "/microserviceUpdate", - "type": "object", - "properties": { - "name": { - "type": "string", - "minLength": 1 + 'id': '/microserviceUpdate', + 'type': 'object', + 'properties': { + 'name': { + 'type': 'string', + 'minLength': 1, + }, + 'config': {'type': 'string'}, + 'rebuild': {'type': 'boolean'}, + 'iofogUuid': {'type': 'string'}, + 'rootHostAccess': {'type': 'boolean'}, + 'logSize': {'type': 'integer', 'minimum': 0}, + 'volumeMappings': { + 'type': 'array', + 'items': {'$ref': '/volumeMappings'}, }, - "config": {"type": "string"}, - "rebuild": {"type": "boolean"}, - "iofogUuid": {"type": "string"}, - "rootHostAccess": {"type": "boolean"}, - "logSize": {"type": "integer", "minimum" : 0}, - "volumeMappings": { - "type": "array", - "items": {"$ref": "/volumeMappings"} - } }, - "additionalProperties": false -}; + 'additionalProperties': false, +} const microserviceDelete = { - "id": "/microserviceDelete", - "type": "object", - "properties": { - "withCleanup": { - "type": "boolean" + 'id': '/microserviceDelete', + 'type': 'object', + 'properties': { + 'withCleanup': { + 'type': 'boolean', }, - "additionalProperties": false - } -}; + 'additionalProperties': false, + }, +} const ports = { - "id": "/ports", - "type": "object", - "properties": { - "internal": {"type": "integer"}, - "external": {"type": "integer"}, - "publicMode": {"enum": [false]} + 'id': '/ports', + 'type': 'object', + 'properties': { + 'internal': {'type': 'integer'}, + 'external': {'type': 'integer'}, + 'publicMode': {'enum': [false]}, }, - "required": ["internal", "external"], - "additionalProperties": false -}; + 'required': ['internal', 'external'], + 'additionalProperties': false, +} const portsCreate = { - "id": "/portsCreate", - "type": "object", - "properties": { - "internal": {"type": "integer"}, - "external": {"type": "integer"}, - "publicMode": {"type": "boolean"} + 'id': '/portsCreate', + 'type': 'object', + 'properties': { + 'internal': {'type': 'integer'}, + 'external': {'type': 'integer'}, + 'publicMode': {'type': 'boolean'}, }, - "required": ["internal", "external"], - "additionalProperties": false -}; + 'required': ['internal', 'external'], + 'additionalProperties': false, +} const volumeMappings = { - "id": "/volumeMappings", - "type": "object", - "properties": { - "hostDestination": {"type": "string"}, - "containerDestination": {"type": "string"}, - "accessMode": {"type": "string"} + 'id': '/volumeMappings', + 'type': 'object', + 'properties': { + 'hostDestination': {'type': 'string'}, + 'containerDestination': {'type': 'string'}, + 'accessMode': {'type': 'string'}, }, - "required": ["hostDestination", "containerDestination", "accessMode"], - "additionalProperties": false -}; + 'required': ['hostDestination', 'containerDestination', 'accessMode'], + 'additionalProperties': false, +} module.exports = { - mainSchemas: [microserviceCreate, microserviceUpdate, ports, portsCreate, microserviceDelete, volumeMappings], - innerSchemas: [volumeMappings, ports] -}; \ No newline at end of file + mainSchemas: [microserviceCreate, microserviceUpdate, ports, portsCreate, microserviceDelete, volumeMappings], + innerSchemas: [volumeMappings, ports], +} diff --git a/src/schemas/registry.js b/src/schemas/registry.js index 6acd7e6f8..f360386ee 100644 --- a/src/schemas/registry.js +++ b/src/schemas/registry.js @@ -12,52 +12,54 @@ */ const registryCreate = { - "id": "/registryCreate", - "type": "object", - "properties": { - "url": {"type": "string", "minLength": 1}, - "isPublic": {"type": "boolean"}, - "username": {"type": "string", "minLength": 1}, - "password": {"type": "string"}, - "email": { - "type": "string", - "pattern": "^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$" + 'id': '/registryCreate', + 'type': 'object', + 'properties': { + 'url': {'type': 'string', 'minLength': 1}, + 'isPublic': {'type': 'boolean'}, + 'username': {'type': 'string', 'minLength': 1}, + 'password': {'type': 'string'}, + 'email': { + 'type': 'string', + 'pattern': '^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}' + + '\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$', }, - "requiresCert": {"type": "boolean"}, - "certificate": {"type": "string"} + 'requiresCert': {'type': 'boolean'}, + 'certificate': {'type': 'string'}, }, - "required": ["url", "isPublic", "username", "password", "email"], - "additionalProperties": false -}; + 'required': ['url', 'isPublic', 'username', 'password', 'email'], + 'additionalProperties': false, +} const registryDelete = { - "id": "/registryDelete", - "type": "object", - "properties": { - "id": {"type": "integer"} + 'id': '/registryDelete', + 'type': 'object', + 'properties': { + 'id': {'type': 'integer'}, }, - "required": ["id"], - "additionalProperties": false -}; + 'required': ['id'], + 'additionalProperties': false, +} const registryUpdate = { - "id": "/registryUpdate", - "type": "object", - "properties": { - "url": {"type": "string", "minLength": 1}, - "isPublic": {"type": "boolean"}, - "username": {"type": "string", "minLength": 1}, - "password": {"type": "string"}, - "email": { - "type": "string", - "pattern": "^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$" + 'id': '/registryUpdate', + 'type': 'object', + 'properties': { + 'url': {'type': 'string', 'minLength': 1}, + 'isPublic': {'type': 'boolean'}, + 'username': {'type': 'string', 'minLength': 1}, + 'password': {'type': 'string'}, + 'email': { + 'type': 'string', + 'pattern': '^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}' + + '\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$', }, - "requiresCert": {"type": "boolean"}, - "certificate": {"type": "string"} + 'requiresCert': {'type': 'boolean'}, + 'certificate': {'type': 'string'}, }, - "additionalProperties": false -}; + 'additionalProperties': false, +} module.exports = { - mainSchemas: [registryCreate, registryDelete, registryUpdate] -}; \ No newline at end of file + mainSchemas: [registryCreate, registryDelete, registryUpdate], +} diff --git a/src/schemas/tunnel.js b/src/schemas/tunnel.js index 87f9397aa..d4be11763 100644 --- a/src/schemas/tunnel.js +++ b/src/schemas/tunnel.js @@ -12,19 +12,19 @@ */ const tunnelCreate = { - "id": "/tunnelCreate", - "type": "object", - "properties": { - "iofogUuid": {"type": "string"}, - "username": {"type": "string", "minLength": 1}, - "password": {"type": "string"}, - "rsakey": {"type": "string"}, - "lport": {"type": "integer", "minimum" : 0, "maximum" : 65535}, - "rport": {"type": "integer", "minimum" : 0, "maximum" : 65535} + 'id': '/tunnelCreate', + 'type': 'object', + 'properties': { + 'iofogUuid': {'type': 'string'}, + 'username': {'type': 'string', 'minLength': 1}, + 'password': {'type': 'string'}, + 'rsakey': {'type': 'string'}, + 'lport': {'type': 'integer', 'minimum': 0, 'maximum': 65535}, + 'rport': {'type': 'integer', 'minimum': 0, 'maximum': 65535}, }, - "required": ["iofogUuid", "username", "password", "lport", "rport"] -}; + 'required': ['iofogUuid', 'username', 'password', 'lport', 'rport'], +} module.exports = { - mainSchemas: [tunnelCreate] -}; \ No newline at end of file + mainSchemas: [tunnelCreate], +} diff --git a/src/schemas/user.js b/src/schemas/user.js index f9fde6642..f8c757b94 100644 --- a/src/schemas/user.js +++ b/src/schemas/user.js @@ -12,118 +12,122 @@ */ const signUp = { - "id": "/signUp", - "type": "object", - "properties": { - "firstName": {"type": "string", "minLength": 3}, - "lastName": {"type": "string", "minLength": 3}, - "email": { - "type": "string", - "pattern": "^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$" + 'id': '/signUp', + 'type': 'object', + 'properties': { + 'firstName': {'type': 'string', 'minLength': 3}, + 'lastName': {'type': 'string', 'minLength': 3}, + 'email': { + 'type': 'string', + 'pattern': '^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}' + + '\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$', }, - "password": {"type": "string", "minLength": 8} + 'password': {'type': 'string', 'minLength': 8}, }, - "required": ["email", "password", "firstName", "lastName"], - "additionalProperties": false -}; + 'required': ['email', 'password', 'firstName', 'lastName'], + 'additionalProperties': false, +} const login = { - "id": "/login", - "type": "object", - "properties": { - "email": { - "type": "string", - "pattern": "^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$" + 'id': '/login', + 'type': 'object', + 'properties': { + 'email': { + 'type': 'string', + 'pattern': '^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}' + + '\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$', }, - "password": {"type": "string"} + 'password': {'type': 'string'}, }, - "required": ["email", "password"], - "additionalProperties": false -}; + 'required': ['email', 'password'], + 'additionalProperties': false, +} const resendActivation = { - "id": "/resendActivation", - "type": "object", - "properties": { - "email": { - "type": "string", - "pattern": "^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$" - } + 'id': '/resendActivation', + 'type': 'object', + 'properties': { + 'email': { + 'type': 'string', + 'pattern': '^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}' + + '\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$', + }, }, - "required": ["email"], - "additionalProperties": false -}; + 'required': ['email'], + 'additionalProperties': false, +} const activateUser = { - "id": "/activateUser", - "type": "object", - "properties": { - "activationCode": {"type": "string"} + 'id': '/activateUser', + 'type': 'object', + 'properties': { + 'activationCode': {'type': 'string'}, }, - "required": ["activationCode"], - "additionalProperties": false -}; + 'required': ['activationCode'], + 'additionalProperties': false, +} const activateUserCLI = { - "id": "/activateUserCLI", - "type": "object", - "properties": { - "email": {"type": "string"} + 'id': '/activateUserCLI', + 'type': 'object', + 'properties': { + 'email': {'type': 'string'}, }, - "required": ["email"], - "additionalProperties": false -}; + 'required': ['email'], + 'additionalProperties': false, +} const updateUserProfile = { - "id": "/updateUserProfile", - "type": "object", - "properties": { - "firstName": {"type": "string", "minLength": 3}, - "lastName": {"type": "string", "minLength": 3} + 'id': '/updateUserProfile', + 'type': 'object', + 'properties': { + 'firstName': {'type': 'string', 'minLength': 3}, + 'lastName': {'type': 'string', 'minLength': 3}, }, - "required": [], - "additionalProperties": false -}; + 'required': [], + 'additionalProperties': false, +} const updateUserProfileCLI = { - "id": "/updateUserProfileCLI", - "type": "object", - "properties": { - "firstName": {"type": "string", "minLength": 3}, - "lastName": {"type": "string", "minLength": 3}, - "password": {"type": "string", "minLength": 8} + 'id': '/updateUserProfileCLI', + 'type': 'object', + 'properties': { + 'firstName': {'type': 'string', 'minLength': 3}, + 'lastName': {'type': 'string', 'minLength': 3}, + 'password': {'type': 'string', 'minLength': 8}, }, - "required": [], - "additionalProperties": false -}; + 'required': [], + 'additionalProperties': false, +} const updatePassword = { - "id": "/updatePassword", - "type": "object", - "properties": { - "oldPassword": {"type": "string"}, - "newPassword": {"type": "string", "minLength": 8} + 'id': '/updatePassword', + 'type': 'object', + 'properties': { + 'oldPassword': {'type': 'string'}, + 'newPassword': {'type': 'string', 'minLength': 8}, }, - "required": ["oldPassword", "newPassword"], - "additionalProperties": false -}; + 'required': ['oldPassword', 'newPassword'], + 'additionalProperties': false, +} const resetUserPassword = { - "id": "/resetUserPassword", - "type": "object", - "properties": { - "email": { - "type": "string", - "pattern": "^(([^<>()\\[\\]\\\\.,;:\\s@\"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@\"]+)*)|(\".+\"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$" - } + 'id': '/resetUserPassword', + 'type': 'object', + 'properties': { + 'email': { + 'type': 'string', + 'pattern': '^(([^<>()\\[\\]\\\\.,;:\\s@"]+(\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(".+"))@((\\[[0-9]{1,3}\\.[0-9]{1,3}' + + '\\.[0-9]{1,3}\\.[0-9]{1,3}])|(([a-zA-Z\\-0-9]+\\.)+[a-zA-Z]{2,}))$', + }, }, - "required": ["email"], - "additionalProperties": false -}; + 'required': ['email'], + 'additionalProperties': false, +} module.exports = { mainSchemas: [signUp, login, resendActivation, activateUser, activateUserCLI, updateUserProfile, updateUserProfileCLI, updatePassword, resetUserPassword], - innerSchemas: [] -}; \ No newline at end of file + innerSchemas: [], +} diff --git a/src/sequelize/managers/access-token-manager.js b/src/sequelize/managers/access-token-manager.js index e2a0b8c16..026f067aa 100644 --- a/src/sequelize/managers/access-token-manager.js +++ b/src/sequelize/managers/access-token-manager.js @@ -11,28 +11,26 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const AccessToken = models.AccessToken; -const AppHelper = require('../../helpers/app-helper'); - -class accessTokenManager extends BaseManager { +const BaseManager = require('./base-manager') +const models = require('./../models') +const AccessToken = models.AccessToken +class AccessTokenManager extends BaseManager { getEntity() { - return AccessToken; + return AccessToken } // no transaction required here, used by auth decorator updateExpirationTime(id, newTime) { return AccessToken.update({ - expirationTime: newTime + expirationTime: newTime, }, { where: { - id: id - } + id: id, + }, }) } } -const instance = new accessTokenManager(); -module.exports = instance; \ No newline at end of file +const instance = new AccessTokenManager() +module.exports = instance diff --git a/src/sequelize/managers/base-manager.js b/src/sequelize/managers/base-manager.js index 6292e7f07..3601335f6 100644 --- a/src/sequelize/managers/base-manager.js +++ b/src/sequelize/managers/base-manager.js @@ -11,22 +11,19 @@ * */ -const AppHelper = require('../../helpers/app-helper'); -const Errors = require('../../helpers/errors'); +const AppHelper = require('../../helpers/app-helper') +const Errors = require('../../helpers/errors') -const ChangeTracking = require('./../models').ChangeTracking; - -//TODO [when transactions concurrency issue fixed]: Transactions should be used always +// TODO [when transactions concurrency issue fixed]: Transactions should be used always module.exports = class BaseManager { - getEntity() { - throw new Error("Not implemented getEntity method in manager"); + throw new Error('Not implemented getEntity method in manager') } async findAll(object, transaction) { - AppHelper.checkTransaction(transaction); + AppHelper.checkTransaction(transaction) - object = object || {}; + object = object || {} const options = transaction.fakeTransaction ? { @@ -34,16 +31,16 @@ module.exports = class BaseManager { } : { where: object, - transaction: transaction - }; + transaction: transaction, + } - return this.getEntity().findAll(options); + return this.getEntity().findAll(options) } async findOne(object, transaction) { - AppHelper.checkTransaction(transaction); + AppHelper.checkTransaction(transaction) - object = object || {}; + object = object || {} const options = transaction.fakeTransaction ? { @@ -51,36 +48,36 @@ module.exports = class BaseManager { } : { where: object, - transaction: transaction - }; + transaction: transaction, + } - return this.getEntity().findOne(options); + return this.getEntity().findOne(options) } async create(object, transaction) { - AppHelper.checkTransaction(transaction); + AppHelper.checkTransaction(transaction) const options = transaction.fakeTransaction ? {} - : {transaction: transaction}; + : {transaction: transaction} - return this.getEntity().create(object, options); + return this.getEntity().create(object, options) } async bulkCreate(arr, transaction) { - AppHelper.checkTransaction(transaction); + AppHelper.checkTransaction(transaction) const options = transaction.fakeTransaction ? {} - : {transaction: transaction}; + : {transaction: transaction} - return this.getEntity().bulkCreate(arr, options); + return this.getEntity().bulkCreate(arr, options) } async delete(data, transaction) { - AppHelper.checkTransaction(transaction); + AppHelper.checkTransaction(transaction) - data = data || {}; + data = data || {} const options = transaction.fakeTransaction ? { @@ -88,16 +85,16 @@ module.exports = class BaseManager { } : { where: data, - transaction: transaction - }; + transaction: transaction, + } - return this.getEntity().destroy(options); + return this.getEntity().destroy(options) } async update(whereData, newData, transaction) { - AppHelper.checkTransaction(transaction); + AppHelper.checkTransaction(transaction) - whereData = whereData || {}; + whereData = whereData || {} const options = transaction.fakeTransaction ? { @@ -105,24 +102,24 @@ module.exports = class BaseManager { } : { where: whereData, - transaction: transaction - }; + transaction: transaction, + } - return this.getEntity().update(newData, options); + return this.getEntity().update(newData, options) } async upsert(data, transaction) { - AppHelper.checkTransaction(transaction); + AppHelper.checkTransaction(transaction) const options = transaction.fakeTransaction ? {} - : {transaction: transaction}; + : {transaction: transaction} - return this.getEntity().upsert(data, options); + return this.getEntity().upsert(data, options) } async updateOrCreate(whereData, data, transaction) { - AppHelper.checkTransaction(transaction); + AppHelper.checkTransaction(transaction) const obj = await this.findOne(whereData, transaction) if (obj) { @@ -134,18 +131,19 @@ module.exports = class BaseManager { } async updateIfChanged(whereData, newData, transaction) { - AppHelper.checkTransaction(transaction); + AppHelper.checkTransaction(transaction) const obj = await this.findOne(whereData, transaction) if (!obj) { throw new Errors.NotFoundError(`${this.getEntity().name} not found`) } - let hasUpdates = false; - for (let fldName in newData) { - if (newData.hasOwnProperty(fldName) && obj.dataValues.hasOwnProperty(fldName) && newData[fldName] !== obj.dataValues[fldName]) { - hasUpdates = true; - break; + let hasUpdates = false + for (const fldName in newData) { + if (newData.hasOwnProperty(fldName) && obj.dataValues.hasOwnProperty(fldName) && + newData[fldName] !== obj.dataValues[fldName]) { + hasUpdates = true + break } } @@ -153,4 +151,4 @@ module.exports = class BaseManager { return await this.update(whereData, newData, transaction) } } -}; \ No newline at end of file +} diff --git a/src/sequelize/managers/catalog-item-image-manager.js b/src/sequelize/managers/catalog-item-image-manager.js index 5ce57d8ad..a56e373ef 100644 --- a/src/sequelize/managers/catalog-item-image-manager.js +++ b/src/sequelize/managers/catalog-item-image-manager.js @@ -11,15 +11,15 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const CatalogItemImage = models.CatalogItemImage; +const BaseManager = require('./base-manager') +const models = require('./../models') +const CatalogItemImage = models.CatalogItemImage class CatalogItemImageManager extends BaseManager { getEntity() { - return CatalogItemImage; + return CatalogItemImage } } -const instance = new CatalogItemImageManager(); -module.exports = instance; \ No newline at end of file +const instance = new CatalogItemImageManager() +module.exports = instance diff --git a/src/sequelize/managers/catalog-item-input-type-manager.js b/src/sequelize/managers/catalog-item-input-type-manager.js index 128f3d043..6368d9ea5 100644 --- a/src/sequelize/managers/catalog-item-input-type-manager.js +++ b/src/sequelize/managers/catalog-item-input-type-manager.js @@ -11,15 +11,15 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const CatalogItemInputType = models.CatalogItemInputType; +const BaseManager = require('./base-manager') +const models = require('./../models') +const CatalogItemInputType = models.CatalogItemInputType class CatalogItemInputTypeManager extends BaseManager { getEntity() { - return CatalogItemInputType; + return CatalogItemInputType } } -const instance = new CatalogItemInputTypeManager(); -module.exports = instance; \ No newline at end of file +const instance = new CatalogItemInputTypeManager() +module.exports = instance diff --git a/src/sequelize/managers/catalog-item-manager.js b/src/sequelize/managers/catalog-item-manager.js index 7effb7e5d..e1b28856e 100644 --- a/src/sequelize/managers/catalog-item-manager.js +++ b/src/sequelize/managers/catalog-item-manager.js @@ -11,17 +11,16 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const CatalogItem = models.CatalogItem; -const CatalogItemImage = models.CatalogItemImage; -const CatalogItemInputType = models.CatalogItemInputType; -const CatalogItemOutputType = models.CatalogItemOutputType; -const Op = require('sequelize').Op; +const BaseManager = require('./base-manager') +const models = require('./../models') +const CatalogItem = models.CatalogItem +const CatalogItemImage = models.CatalogItemImage +const CatalogItemInputType = models.CatalogItemInputType +const CatalogItemOutputType = models.CatalogItemOutputType class CatalogItemManager extends BaseManager { getEntity() { - return CatalogItem; + return CatalogItem } findAllWithDependencies(where, attributes, transaction) { @@ -31,22 +30,22 @@ class CatalogItemManager extends BaseManager { model: CatalogItemImage, as: 'images', required: false, - attributes: ['containerImage', 'fogTypeId'] + attributes: ['containerImage', 'fogTypeId'], }, { model: CatalogItemInputType, as: 'inputType', required: false, - attributes: ['infoType', 'infoFormat'] + attributes: ['infoType', 'infoFormat'], }, { model: CatalogItemOutputType, as: 'outputType', required: false, - attributes: ['infoType', 'infoFormat'] + attributes: ['infoType', 'infoFormat'], }], where: where, - attributes: attributes + attributes: attributes, }, {transaction: transaction}) } @@ -57,25 +56,25 @@ class CatalogItemManager extends BaseManager { model: CatalogItemImage, as: 'images', required: false, - attributes: ['containerImage', 'fogTypeId'] + attributes: ['containerImage', 'fogTypeId'], }, { model: CatalogItemInputType, as: 'inputType', required: false, - attributes: ['infoType', 'infoFormat'] + attributes: ['infoType', 'infoFormat'], }, { model: CatalogItemOutputType, as: 'outputType', required: false, - attributes: ['infoType', 'infoFormat'] + attributes: ['infoType', 'infoFormat'], }], where: where, - attributes: attribures + attributes: attribures, }, {transaction: transaction}) } } -const instance = new CatalogItemManager(); -module.exports = instance; \ No newline at end of file +const instance = new CatalogItemManager() +module.exports = instance diff --git a/src/sequelize/managers/catalog-item-output-type-manager.js b/src/sequelize/managers/catalog-item-output-type-manager.js index bf8adb559..31569ad6b 100644 --- a/src/sequelize/managers/catalog-item-output-type-manager.js +++ b/src/sequelize/managers/catalog-item-output-type-manager.js @@ -11,15 +11,15 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const CatalogItemOutputType = models.CatalogItemOutputType; +const BaseManager = require('./base-manager') +const models = require('./../models') +const CatalogItemOutputType = models.CatalogItemOutputType class CatalogItemOutputTypeManager extends BaseManager { getEntity() { - return CatalogItemOutputType; + return CatalogItemOutputType } } -const instance = new CatalogItemOutputTypeManager(); -module.exports = instance; \ No newline at end of file +const instance = new CatalogItemOutputTypeManager() +module.exports = instance diff --git a/src/sequelize/managers/change-tracking-manager.js b/src/sequelize/managers/change-tracking-manager.js index 119ebc09b..e7a89cb1e 100644 --- a/src/sequelize/managers/change-tracking-manager.js +++ b/src/sequelize/managers/change-tracking-manager.js @@ -12,7 +12,7 @@ */ const BaseManager = require('../managers/base-manager') -const models = require('./../models'); +const models = require('./../models') const ChangeTracking = models.ChangeTracking class ChangeTrackingManager extends BaseManager { @@ -22,4 +22,4 @@ class ChangeTrackingManager extends BaseManager { } const instance = new ChangeTrackingManager() -module.exports = instance \ No newline at end of file +module.exports = instance diff --git a/src/sequelize/managers/connector-manager.js b/src/sequelize/managers/connector-manager.js index 08c6e571e..db845a993 100644 --- a/src/sequelize/managers/connector-manager.js +++ b/src/sequelize/managers/connector-manager.js @@ -12,7 +12,7 @@ */ const BaseManager = require('../managers/base-manager') -const models = require('./../models'); +const models = require('./../models') const Connector = models.Connector class ConnectorManager extends BaseManager { @@ -22,4 +22,4 @@ class ConnectorManager extends BaseManager { } const instance = new ConnectorManager() -module.exports = instance \ No newline at end of file +module.exports = instance diff --git a/src/sequelize/managers/connector-port-manager.js b/src/sequelize/managers/connector-port-manager.js index e98f7114e..f51eb159b 100644 --- a/src/sequelize/managers/connector-port-manager.js +++ b/src/sequelize/managers/connector-port-manager.js @@ -8,18 +8,18 @@ * * * * SPDX-License-Identifier: EPL-2.0 * ******************************************************************************* - * + * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const ConnectorPort = models.ConnectorPort; +const BaseManager = require('./base-manager') +const models = require('./../models') +const ConnectorPort = models.ConnectorPort class ConnectorPortManager extends BaseManager { getEntity() { - return ConnectorPort; + return ConnectorPort } } -const instance = new ConnectorPortManager(); -module.exports = instance; \ No newline at end of file +const instance = new ConnectorPortManager() +module.exports = instance diff --git a/src/sequelize/managers/email-activation-code-manager.js b/src/sequelize/managers/email-activation-code-manager.js index abdd28e18..2d4716d11 100644 --- a/src/sequelize/managers/email-activation-code-manager.js +++ b/src/sequelize/managers/email-activation-code-manager.js @@ -11,40 +11,40 @@ * */ -const models = require('../models'); -const EmailActivationCode = models.EmailActivationCode; -const BaseManager = require('./base-manager'); -const AppHelper = require('../../helpers/app-helper'); -const Sequelize = require('sequelize'); +const models = require('../models') +const EmailActivationCode = models.EmailActivationCode +const BaseManager = require('./base-manager') +const AppHelper = require('../../helpers/app-helper') +const Sequelize = require('sequelize') const Op = Sequelize.Op class EmailActivationCodeManager extends BaseManager { getEntity() { - return EmailActivationCode; + return EmailActivationCode } async getByActivationCode(activationCode, transaction) { - AppHelper.checkTransaction(transaction); + AppHelper.checkTransaction(transaction) return EmailActivationCode.findOne({ where: { - activationCode: activationCode - } + activationCode: activationCode, + }, }, { - transaction: transaction - }); + transaction: transaction, + }) }; async createActivationCode(userId, activationCode, expirationTime, transaction) { - AppHelper.checkTransaction(transaction); + AppHelper.checkTransaction(transaction) return EmailActivationCode.create({ userId: userId, activationCode: activationCode, - expirationTime: expirationTime + expirationTime: expirationTime, }, { - transaction: transaction - }); + transaction: transaction, + }) }; async verifyActivationCode(activationCode, transaction) { @@ -52,14 +52,14 @@ class EmailActivationCodeManager extends BaseManager { where: { activationCode: activationCode, expirationTime: { - [Op.gt]: new Date().getTime() - } - } + [Op.gt]: new Date().getTime(), + }, + }, }, { - transaction: transaction - }); + transaction: transaction, + }) } } -const instance = new EmailActivationCodeManager(); -module.exports = instance; +const instance = new EmailActivationCodeManager() +module.exports = instance diff --git a/src/sequelize/managers/flow-manager.js b/src/sequelize/managers/flow-manager.js index 10b95d455..64ff3802d 100644 --- a/src/sequelize/managers/flow-manager.js +++ b/src/sequelize/managers/flow-manager.js @@ -11,11 +11,10 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const Flow = models.Flow; -const Microservice = models.Microservice; -const sequelize = require('sequelize'); +const BaseManager = require('./base-manager') +const models = require('./../models') +const Flow = models.Flow +const Microservice = models.Microservice class FlowManager extends BaseManager { getEntity() { @@ -29,11 +28,11 @@ class FlowManager extends BaseManager { model: Microservice, as: 'microservices', required: false, - attributes: ['iofogUuid'] - } + attributes: ['iofogUuid'], + }, ], where: where, - attributes: ['id'] + attributes: ['id'], }, {transaction: transaction}) } @@ -41,18 +40,18 @@ class FlowManager extends BaseManager { return Flow.findAll({ where: where, attributes: attributes}, - {transaction: transaction}) + {transaction: transaction}) } async findOneWithAttributes(where, attributes, transaction) { return Flow.findOne({ where: where, - attributes: attributes - }, - {transaction: transaction}) - } + attributes: attributes, + }, + {transaction: transaction}) + } } -const instance = new FlowManager(); -module.exports = instance; \ No newline at end of file +const instance = new FlowManager() +module.exports = instance diff --git a/src/sequelize/managers/hw-info-manager.js b/src/sequelize/managers/hw-info-manager.js index 50f73312f..6c346262a 100644 --- a/src/sequelize/managers/hw-info-manager.js +++ b/src/sequelize/managers/hw-info-manager.js @@ -11,15 +11,15 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const HWInfo = models.HWInfo; +const BaseManager = require('./base-manager') +const models = require('./../models') +const HWInfo = models.HWInfo class HWInfoManager extends BaseManager { getEntity() { - return HWInfo; + return HWInfo } } -const instance = new HWInfoManager(); -module.exports = instance; \ No newline at end of file +const instance = new HWInfoManager() +module.exports = instance diff --git a/src/sequelize/managers/iofog-access-token-manager.js b/src/sequelize/managers/iofog-access-token-manager.js index 9620f7861..f8fc3aedf 100644 --- a/src/sequelize/managers/iofog-access-token-manager.js +++ b/src/sequelize/managers/iofog-access-token-manager.js @@ -11,9 +11,9 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const FogAccessToken = models.FogAccessToken; +const BaseManager = require('./base-manager') +const models = require('./../models') +const FogAccessToken = models.FogAccessToken class FogAccessTokenManager extends BaseManager { getEntity() { @@ -23,14 +23,14 @@ class FogAccessTokenManager extends BaseManager { // no transaction required here, used by auth decorator updateExpirationTime(id, newTime) { return FogAccessToken.update({ - expirationTime: newTime + expirationTime: newTime, }, { where: { - id: id - } + id: id, + }, }) } } -const instance = new FogAccessTokenManager(); -module.exports = instance; \ No newline at end of file +const instance = new FogAccessTokenManager() +module.exports = instance diff --git a/src/sequelize/managers/iofog-manager.js b/src/sequelize/managers/iofog-manager.js index 0ac555f4e..e654d028c 100644 --- a/src/sequelize/managers/iofog-manager.js +++ b/src/sequelize/managers/iofog-manager.js @@ -11,12 +11,12 @@ * */ -const BaseManager = require('../managers/base-manager'); -const models = require('./../models'); -const Fog = models.Fog; -const Microservice = models.Microservice; -const FogAccessToken = models.FogAccessToken; -const Strace = models.StraceDiagnostics; +const BaseManager = require('../managers/base-manager') +const models = require('./../models') +const Fog = models.Fog +const Microservice = models.Microservice +const FogAccessToken = models.FogAccessToken +const Strace = models.StraceDiagnostics class FogManager extends BaseManager { getEntity() { @@ -30,22 +30,22 @@ class FogManager extends BaseManager { model: FogAccessToken, as: 'accessToken', where: { - token: token - } - }] - }); + token: token, + }, + }], + }) } // no transaction required here, used by agent-last-active decorator updateLastActive(uuid, timestamp) { return Fog.update({ - lastActive: timestamp + lastActive: timestamp, }, { where: { - uuid: uuid - } - }); + uuid: uuid, + }, + }) } findFogStraces(where, transaction) { @@ -58,15 +58,13 @@ class FogManager extends BaseManager { include: [{ model: Strace, as: 'strace', - required: true - }] + required: true, + }], }], - where: where + where: where, }, {transaction: transaction}) } - - } -const instance = new FogManager(); -module.exports = instance; \ No newline at end of file +const instance = new FogManager() +module.exports = instance diff --git a/src/sequelize/managers/iofog-provision-key-manager.js b/src/sequelize/managers/iofog-provision-key-manager.js index 8a78bcd0a..4032c7840 100644 --- a/src/sequelize/managers/iofog-provision-key-manager.js +++ b/src/sequelize/managers/iofog-provision-key-manager.js @@ -11,9 +11,9 @@ * */ -const BaseManager = require('../managers/base-manager'); -const models = require('./../models'); -const FogProvisionKey = models.FogProvisionKey; +const BaseManager = require('../managers/base-manager') +const models = require('./../models') +const FogProvisionKey = models.FogProvisionKey class FogProvisionKeyManager extends BaseManager { getEntity() { @@ -21,5 +21,5 @@ class FogProvisionKeyManager extends BaseManager { } } -const instance = new FogProvisionKeyManager(); -module.exports = instance; \ No newline at end of file +const instance = new FogProvisionKeyManager() +module.exports = instance diff --git a/src/sequelize/managers/iofog-type-manager.js b/src/sequelize/managers/iofog-type-manager.js index 3e9af7a77..a140deb60 100644 --- a/src/sequelize/managers/iofog-type-manager.js +++ b/src/sequelize/managers/iofog-type-manager.js @@ -11,9 +11,9 @@ * */ -const BaseManager = require('../managers/base-manager'); -const models = require('./../models'); -const FogType = models.FogType; +const BaseManager = require('../managers/base-manager') +const models = require('./../models') +const FogType = models.FogType class FogTypeManager extends BaseManager { getEntity() { @@ -21,5 +21,5 @@ class FogTypeManager extends BaseManager { } } -const instance = new FogTypeManager(); -module.exports = instance; \ No newline at end of file +const instance = new FogTypeManager() +module.exports = instance diff --git a/src/sequelize/managers/iofog-version-command-manager.js b/src/sequelize/managers/iofog-version-command-manager.js index b628e033f..c8e445693 100644 --- a/src/sequelize/managers/iofog-version-command-manager.js +++ b/src/sequelize/managers/iofog-version-command-manager.js @@ -11,9 +11,9 @@ * */ -const BaseManager = require('../managers/base-manager'); -const models = require('./../models'); -const FogVersionCommand = models.FogVersionCommand; +const BaseManager = require('../managers/base-manager') +const models = require('./../models') +const FogVersionCommand = models.FogVersionCommand class FogVersionCommandManager extends BaseManager { getEntity() { @@ -21,5 +21,5 @@ class FogVersionCommandManager extends BaseManager { } } -const instance = new FogVersionCommandManager(); -module.exports = instance; \ No newline at end of file +const instance = new FogVersionCommandManager() +module.exports = instance diff --git a/src/sequelize/managers/microservice-manager.js b/src/sequelize/managers/microservice-manager.js index e1c329f2c..0168f556c 100644 --- a/src/sequelize/managers/microservice-manager.js +++ b/src/sequelize/managers/microservice-manager.js @@ -11,21 +11,21 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const Microservice = models.Microservice; -const MicroservicePort = models.MicroservicePort; -const VolumeMapping = models.VolumeMapping; -const StraceDiagnostics = models.StraceDiagnostics; -const CatalogItem = models.CatalogItem; -const CatalogItemImage = models.CatalogItemImage; -const Fog = models.Fog; -const Flow = models.Flow; -const User = models.User; -const Routing = models.Routing; -const Registry = models.Registry; -const MicroserviceStatus = models.MicroserviceStatus; -const Op = require('sequelize').Op; +const BaseManager = require('./base-manager') +const models = require('./../models') +const Microservice = models.Microservice +const MicroservicePort = models.MicroservicePort +const VolumeMapping = models.VolumeMapping +const StraceDiagnostics = models.StraceDiagnostics +const CatalogItem = models.CatalogItem +const CatalogItemImage = models.CatalogItemImage +const Fog = models.Fog +const Flow = models.Flow +const User = models.User +const Routing = models.Routing +const Registry = models.Registry +const MicroserviceStatus = models.MicroserviceStatus +const Op = require('sequelize').Op const microserviceExcludedFields = [ 'configLastUpdated', @@ -38,8 +38,8 @@ const microserviceExcludedFields = [ 'deleteWithCleanUp', 'imageSnapshot', 'catalog_item_id', - 'iofog_uuid' -]; + 'iofog_uuid', +] class MicroserviceManager extends BaseManager { getEntity() { @@ -49,57 +49,57 @@ class MicroserviceManager extends BaseManager { findAllWithDependencies(where, attributes, transaction) { return Microservice.findAll({ include: [ - { - model: MicroservicePort, - as: 'ports', - required: false, - attributes: ['portInternal', 'portExternal'] - }, - { - model: VolumeMapping, - as: 'volumeMappings', - required: false, - attributes: ['hostDestination', 'containerDestination', 'accessMode'] - }, - { - model: StraceDiagnostics, - as: 'strace', - required: false, - attributes: ['straceRun'] - }, - { - model: CatalogItem, - as: 'catalogItem', - required: true, - include: [{ - model: CatalogItemImage, - as: 'images', - attributes: ['containerImage', 'fogTypeId'] - }], - attributes: ['picture', 'registryId'] - }, - { - model: Fog, - as: 'iofog', - required: false, - attributes: ['daemonStatus'] - }, - { - model: Routing, - as: 'routes', - required: false, - include: [{ - model: Microservice, - as: 'destMicroservice', - attributes: ['uuid'] - }], - attributes: {exclude: ['id', 'source_microservice_uuid', + { + model: MicroservicePort, + as: 'ports', + required: false, + attributes: ['portInternal', 'portExternal'], + }, + { + model: VolumeMapping, + as: 'volumeMappings', + required: false, + attributes: ['hostDestination', 'containerDestination', 'accessMode'], + }, + { + model: StraceDiagnostics, + as: 'strace', + required: false, + attributes: ['straceRun'], + }, + { + model: CatalogItem, + as: 'catalogItem', + required: true, + include: [{ + model: CatalogItemImage, + as: 'images', + attributes: ['containerImage', 'fogTypeId'], + }], + attributes: ['picture', 'registryId'], + }, + { + model: Fog, + as: 'iofog', + required: false, + attributes: ['daemonStatus'], + }, + { + model: Routing, + as: 'routes', + required: false, + include: [{ + model: Microservice, + as: 'destMicroservice', + attributes: ['uuid'], + }], + attributes: {exclude: ['id', 'source_microservice_uuid', 'sourceMicroserviceUuid', 'destMicroserviceUuid', 'sourceNetworkMicroserviceUuid', - 'destNetworkMicroserviceUuid', 'sourceIofogUuid', 'destIofogUuid', 'connectorPortId']} - } + 'destNetworkMicroserviceUuid', 'sourceIofogUuid', 'destIofogUuid', 'connectorPortId']}, + }, ], where: where, - attributes: attributes + attributes: attributes, }, {transaction: transaction}) } @@ -110,13 +110,13 @@ class MicroserviceManager extends BaseManager { model: MicroservicePort, as: 'ports', required: false, - attributes: ['portInternal', 'portExternal'] + attributes: ['portInternal', 'portExternal'], }, { model: VolumeMapping, as: 'volumeMappings', required: false, - attributes: ['hostDestination', 'containerDestination', 'accessMode'] + attributes: ['hostDestination', 'containerDestination', 'accessMode'], }, { model: CatalogItem, @@ -127,96 +127,96 @@ class MicroserviceManager extends BaseManager { model: CatalogItemImage, as: 'images', required: true, - attributes: ['containerImage', 'fogTypeId'] + attributes: ['containerImage', 'fogTypeId'], }, { model: Registry, as: 'registry', required: true, - attributes: ['id'] - } + attributes: ['id'], + }, ], - attributes: ['picture', 'category'] + attributes: ['picture', 'category'], }, { model: Flow, as: 'flow', required: false, - attributes: ['isActivated'] - } + attributes: ['isActivated'], + }, ], where: { iofogUuid: iofogUuid, [Op.or]: [ { - '$flow.is_activated$': true + '$flow.is_activated$': true, }, { - '$catalogItem.category$': {[Op.eq]: 'SYSTEM'}, - '$catalogItem.id$': {[Op.ne]: 1} - } - ] + '$catalogItem.category$': {[Op.eq]: 'SYSTEM'}, + '$catalogItem.id$': {[Op.ne]: 1}, + }, + ], - } + }, }, {transaction: transaction}) } findOneWithDependencies(where, attributes, transaction) { return Microservice.findOne({ include: [ - { - model: MicroservicePort, - as: 'ports', - required: false, - attributes: ['portInternal', 'portExternal'] - }, - { - model: VolumeMapping, - as: 'volumeMappings', - required: false, - attributes: ['hostDestination', 'containerDestination', 'accessMode'] - }, - { - model: StraceDiagnostics, - as: 'strace', - required: false, - attributes: ['straceRun'] - }, - { - model: CatalogItem, - as: 'catalogItem', - required: false, - include: [{ - model: CatalogItemImage, - as: 'images', - attributes: ['containerImage', 'fogTypeId'] + { + model: MicroservicePort, + as: 'ports', + required: false, + attributes: ['portInternal', 'portExternal'], + }, + { + model: VolumeMapping, + as: 'volumeMappings', + required: false, + attributes: ['hostDestination', 'containerDestination', 'accessMode'], + }, + { + model: StraceDiagnostics, + as: 'strace', + required: false, + attributes: ['straceRun'], + }, + { + model: CatalogItem, + as: 'catalogItem', + required: false, + include: [{ + model: CatalogItemImage, + as: 'images', + attributes: ['containerImage', 'fogTypeId'], }], - attributes: ['picture', 'registryId'] - }, - { - model: Fog, - as: 'iofog', - required: false, - attributes: ['daemonStatus'] - }, - { - model: Routing, - as: 'routes', - required: false, - include: [{ - model: Microservice, - as: 'destMicroservice', - attributes: ['uuid'] - }], - attributes: {exclude: ['id', - 'sourceMicroserviceUuid', 'destMicroserviceUuid', - 'sourceNetworkMicroserviceUuid', 'destNetworkMicroserviceUuid', - 'sourceIofogUuid', 'destIofogUuid', 'connectorPortId']} - } + attributes: ['picture', 'registryId'], + }, + { + model: Fog, + as: 'iofog', + required: false, + attributes: ['daemonStatus'], + }, + { + model: Routing, + as: 'routes', + required: false, + include: [{ + model: Microservice, + as: 'destMicroservice', + attributes: ['uuid'], + }], + attributes: {exclude: ['id', + 'sourceMicroserviceUuid', 'destMicroserviceUuid', + 'sourceNetworkMicroserviceUuid', 'destNetworkMicroserviceUuid', + 'sourceIofogUuid', 'destIofogUuid', 'connectorPortId']}, + }, ], where: where, - attributes: attributes + attributes: attributes, }, {transaction: transaction}) } @@ -226,16 +226,16 @@ class MicroserviceManager extends BaseManager { { model: MicroserviceStatus, as: 'microserviceStatus', - required: false + required: false, }, { model: CatalogItem, as: 'catalogItem', required: true, - attributes: ['category'] - } + attributes: ['category'], + }, ], - where: where + where: where, }, {transaction: transaction}) } @@ -245,10 +245,10 @@ class MicroserviceManager extends BaseManager { { model: MicroserviceStatus, as: 'microserviceStatus', - required: false - } + required: false, + }, ], - where: where + where: where, }, {transaction: transaction}) } @@ -264,14 +264,14 @@ class MicroserviceManager extends BaseManager { model: User, as: 'user', required: true, - attributes: ['id'] - } + attributes: ['id'], + }, ], - attributes: ['id'] - } + attributes: ['id'], + }, ], where: where, - attributes: ['uuid'] + attributes: ['uuid'], }, {transaction: transaction}) } @@ -279,20 +279,20 @@ class MicroserviceManager extends BaseManager { return Microservice.findOne({ where: where, attributes: { - exclude: microserviceExcludedFields + exclude: microserviceExcludedFields, }}, { - transaction: transaction - }); + transaction: transaction, + }) } async findAllExcludeFields(where, transaction) { return Microservice.findAll({ where: where, attributes: { - exclude: microserviceExcludedFields + exclude: microserviceExcludedFields, }}, { - transaction: transaction - }); + transaction: transaction, + }) } findOneWithCategory(where, transaction) { @@ -302,13 +302,13 @@ class MicroserviceManager extends BaseManager { model: CatalogItem, as: 'catalogItem', required: true, - attributes: ['category'] - } + attributes: ['category'], + }, ], - where: where + where: where, }, {transaction: transaction}) } } -const instance = new MicroserviceManager(); -module.exports = instance; \ No newline at end of file +const instance = new MicroserviceManager() +module.exports = instance diff --git a/src/sequelize/managers/microservice-port-manager.js b/src/sequelize/managers/microservice-port-manager.js index 9548bf6e0..276d63379 100644 --- a/src/sequelize/managers/microservice-port-manager.js +++ b/src/sequelize/managers/microservice-port-manager.js @@ -11,9 +11,9 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const MicroservicePort = models.MicroservicePort; +const BaseManager = require('./base-manager') +const models = require('./../models') +const MicroservicePort = models.MicroservicePort class MicroservicePortManager extends BaseManager { getEntity() { @@ -21,5 +21,5 @@ class MicroservicePortManager extends BaseManager { } } -const instance = new MicroservicePortManager(); -module.exports = instance; \ No newline at end of file +const instance = new MicroservicePortManager() +module.exports = instance diff --git a/src/sequelize/managers/microservice-public-mode-manager.js b/src/sequelize/managers/microservice-public-mode-manager.js index e25e26968..673fbd78f 100644 --- a/src/sequelize/managers/microservice-public-mode-manager.js +++ b/src/sequelize/managers/microservice-public-mode-manager.js @@ -8,13 +8,13 @@ * * * * SPDX-License-Identifier: EPL-2.0 * ******************************************************************************* - * + * */ const BaseManager = require('../managers/base-manager') -const models = require('./../models'); -const MicroservicePublicMode = models.MicroservicePublicMode; -const ConnectorPort = models.ConnectorPort; +const models = require('./../models') +const MicroservicePublicMode = models.MicroservicePublicMode +const ConnectorPort = models.ConnectorPort class MicroservicePublicModeManager extends BaseManager { getEntity() { @@ -27,15 +27,15 @@ class MicroservicePublicModeManager extends BaseManager { { model: ConnectorPort, as: 'connectorPort', - required: true - } + required: true, + }, ], where: { - '$connectorPort.connector_id$': connectorId - } + '$connectorPort.connector_id$': connectorId, + }, }, {transaction: transaction}) } } const instance = new MicroservicePublicModeManager() -module.exports = instance \ No newline at end of file +module.exports = instance diff --git a/src/sequelize/managers/microservice-status-manager.js b/src/sequelize/managers/microservice-status-manager.js index 77ad85df4..c5eb13ecc 100644 --- a/src/sequelize/managers/microservice-status-manager.js +++ b/src/sequelize/managers/microservice-status-manager.js @@ -12,14 +12,14 @@ */ const BaseManager = require('../managers/base-manager') -const models = require('./../models'); -const MicroserviceStatus = models.MicroserviceStatus; +const models = require('./../models') +const MicroserviceStatus = models.MicroserviceStatus class MicroserviceStatusManager extends BaseManager { getEntity() { - return MicroserviceStatus; + return MicroserviceStatus } } -const instance = new MicroserviceStatusManager(); -module.exports = instance; \ No newline at end of file +const instance = new MicroserviceStatusManager() +module.exports = instance diff --git a/src/sequelize/managers/registry-manager.js b/src/sequelize/managers/registry-manager.js index 53bbcd074..94713d12c 100644 --- a/src/sequelize/managers/registry-manager.js +++ b/src/sequelize/managers/registry-manager.js @@ -1,12 +1,12 @@ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const Registry = models.Registry; +const BaseManager = require('./base-manager') +const models = require('./../models') +const Registry = models.Registry class RegistryManager extends BaseManager { getEntity() { - return Registry; + return Registry } } -const instance = new RegistryManager(); -module.exports = instance; \ No newline at end of file +const instance = new RegistryManager() +module.exports = instance diff --git a/src/sequelize/managers/routing-manager.js b/src/sequelize/managers/routing-manager.js index df135f232..627bee1c6 100644 --- a/src/sequelize/managers/routing-manager.js +++ b/src/sequelize/managers/routing-manager.js @@ -11,14 +11,14 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const Routing = models.Routing; -const ConnectorPort = models.ConnectorPort; +const BaseManager = require('./base-manager') +const models = require('./../models') +const Routing = models.Routing +const ConnectorPort = models.ConnectorPort class RoutingManager extends BaseManager { getEntity() { - return Routing; + return Routing } findAllRoutesByConnectorId(connectorId, transaction) { @@ -27,15 +27,15 @@ class RoutingManager extends BaseManager { { model: ConnectorPort, as: 'connectorPort', - required: true - } + required: true, + }, ], where: { - '$connectorPort.connector_id$': connectorId - } + '$connectorPort.connector_id$': connectorId, + }, }, {transaction: transaction}) } } -const instance = new RoutingManager(); -module.exports = instance; \ No newline at end of file +const instance = new RoutingManager() +module.exports = instance diff --git a/src/sequelize/managers/strace-diagnostics-manager.js b/src/sequelize/managers/strace-diagnostics-manager.js index b9c559a4c..33ebdbd95 100644 --- a/src/sequelize/managers/strace-diagnostics-manager.js +++ b/src/sequelize/managers/strace-diagnostics-manager.js @@ -11,16 +11,15 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const StraceDiagnostics = models.StraceDiagnostics; +const BaseManager = require('./base-manager') +const models = require('./../models') +const StraceDiagnostics = models.StraceDiagnostics class StraceDiagnosticsManager extends BaseManager { getEntity() { - return StraceDiagnostics; + return StraceDiagnostics } - } -const instance = new StraceDiagnosticsManager(); -module.exports = instance; \ No newline at end of file +const instance = new StraceDiagnosticsManager() +module.exports = instance diff --git a/src/sequelize/managers/strace-manager.js b/src/sequelize/managers/strace-manager.js index c35cfe21e..7fc5af021 100644 --- a/src/sequelize/managers/strace-manager.js +++ b/src/sequelize/managers/strace-manager.js @@ -11,48 +11,47 @@ * */ -const BaseManager = require('../managers/base-manager'); -const models = require('./../models'); -const Strace = models.StraceDiagnostics; +const BaseManager = require('../managers/base-manager') +const models = require('./../models') +const Strace = models.StraceDiagnostics -const Errors = require('../../helpers/errors'); -const ErrorMessages = require('../../helpers/error-messages'); -const AppHelper = require('../../helpers/app-helper'); +const Errors = require('../../helpers/errors') +const ErrorMessages = require('../../helpers/error-messages') +const AppHelper = require('../../helpers/app-helper') -const maxBufferSize = 1e8; +const maxBufferSize = 1e8 class StraceManager extends BaseManager { - getEntity() { return Strace } async pushBufferByMicroserviceUuid(uuid, pushingData, transaction) { const strace = await this.findOne({ - microserviceUuid: uuid - }, transaction); + microserviceUuid: uuid, + }, transaction) if (!strace) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, uuid)); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, uuid)) } - let newBuffer = this._updateBuffer(strace.buffer, pushingData); + const newBuffer = this._updateBuffer(strace.buffer, pushingData) return await this.update({ - microserviceUuid: uuid + microserviceUuid: uuid, }, { - buffer: newBuffer - }, transaction); + buffer: newBuffer, + }, transaction) } _updateBuffer(oldBuf, pushingData) { - let newBuffer = oldBuf + pushingData; - let delta = newBuffer.length - maxBufferSize; + let newBuffer = oldBuf + pushingData + const delta = newBuffer.length - maxBufferSize if (delta > 0) { newBuffer = '[ioFogController Info] Buffer size is limited, so some of previous data was lost \n' - + newBuffer.substring(delta); + + newBuffer.substring(delta) } - return newBuffer; + return newBuffer }; } -const instance = new StraceManager(); -module.exports = instance; \ No newline at end of file +const instance = new StraceManager() +module.exports = instance diff --git a/src/sequelize/managers/tracking-event-manager.js b/src/sequelize/managers/tracking-event-manager.js index bc08ec828..e7537c7bb 100644 --- a/src/sequelize/managers/tracking-event-manager.js +++ b/src/sequelize/managers/tracking-event-manager.js @@ -11,21 +11,21 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const TrackingEvent = models.TrackingEvent; +const BaseManager = require('./base-manager') +const models = require('./../models') +const TrackingEvent = models.TrackingEvent class TrackingEventManager extends BaseManager { getEntity() { - return TrackingEvent; + return TrackingEvent } async popAll(transaction) { - const res = await this.findAll({}, transaction); - await this.delete({} ,transaction); - return res; + const res = await this.findAll({}, transaction) + await this.delete({}, transaction) + return res } } -const instance = new TrackingEventManager(); -module.exports = instance; \ No newline at end of file +const instance = new TrackingEventManager() +module.exports = instance diff --git a/src/sequelize/managers/tunnel-manager.js b/src/sequelize/managers/tunnel-manager.js index 03dd3c66e..269fa2ced 100644 --- a/src/sequelize/managers/tunnel-manager.js +++ b/src/sequelize/managers/tunnel-manager.js @@ -1,12 +1,12 @@ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const Tunnel = models.Tunnel; +const BaseManager = require('./base-manager') +const models = require('./../models') +const Tunnel = models.Tunnel class TunnelManager extends BaseManager { getEntity() { - return Tunnel; + return Tunnel } } -const instance = new TunnelManager(); -module.exports = instance; \ No newline at end of file +const instance = new TunnelManager() +module.exports = instance diff --git a/src/sequelize/managers/usb-info-manager.js b/src/sequelize/managers/usb-info-manager.js index d898504e9..e16be2640 100644 --- a/src/sequelize/managers/usb-info-manager.js +++ b/src/sequelize/managers/usb-info-manager.js @@ -11,15 +11,15 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const USBInfo = models.USBInfo; +const BaseManager = require('./base-manager') +const models = require('./../models') +const USBInfo = models.USBInfo class USBInfoManager extends BaseManager { getEntity() { - return USBInfo; + return USBInfo } } -const instance = new USBInfoManager(); -module.exports = instance; \ No newline at end of file +const instance = new USBInfoManager() +module.exports = instance diff --git a/src/sequelize/managers/user-manager.js b/src/sequelize/managers/user-manager.js index ccde91ed3..ae002c359 100644 --- a/src/sequelize/managers/user-manager.js +++ b/src/sequelize/managers/user-manager.js @@ -11,39 +11,39 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const User = models.User; -const AccessToken = models.AccessToken; -const AppHelper = require('../../helpers/app-helper'); +const BaseManager = require('./base-manager') +const models = require('./../models') +const User = models.User +const AccessToken = models.AccessToken +const AppHelper = require('../../helpers/app-helper') class UserManager extends BaseManager { getEntity() { - return User; + return User } findByAccessToken(token, transaction) { - AppHelper.checkTransaction(transaction); + AppHelper.checkTransaction(transaction) return User.findOne({ include: [{ model: AccessToken, as: 'accessToken', where: { - token: token - } + token: token, + }, }], }, { - transaction: transaction - }); + transaction: transaction, + }) } findByEmail(email) { return User.findOne({ where: { - email: email - } - }); + email: email, + }, + }) } // no transaction required here, used by auth decorator @@ -53,44 +53,44 @@ class UserManager extends BaseManager { model: AccessToken, as: 'accessToken', where: { - token: token - } - }] - }); + token: token, + }, + }], + }) } // no transaction required here, used by cli decorator findById(id) { - return User.findOne({where: {id: id}}); + return User.findOne({where: {id: id}}) } updateDetails(user, updateObject, transaction) { return this.update({ - id: user.id - }, updateObject, transaction); + id: user.id, + }, updateObject, transaction) } updatePassword(userId, newPassword, transaction) { return this.update({ - id: userId + id: userId, }, { - password: newPassword + password: newPassword, }, transaction) } updateTempPassword(userId, tempPassword, transaction) { return this.update({ - id: userId + id: userId, }, { - tempPassword: tempPassword + tempPassword: tempPassword, }, transaction) } -// no transaction required here, used by cli decorator + // no transaction required here, used by cli decorator findById(id) { - return User.findOne({where: {id: id}}); + return User.findOne({where: {id: id}}) } } -const instance = new UserManager(); -module.exports = instance; \ No newline at end of file +const instance = new UserManager() +module.exports = instance diff --git a/src/sequelize/managers/volume-mapping-manager.js b/src/sequelize/managers/volume-mapping-manager.js index e0810b8f6..6ddb49061 100644 --- a/src/sequelize/managers/volume-mapping-manager.js +++ b/src/sequelize/managers/volume-mapping-manager.js @@ -11,9 +11,9 @@ * */ -const BaseManager = require('./base-manager'); -const models = require('./../models'); -const VolumeMapping = models.VolumeMapping; +const BaseManager = require('./base-manager') +const models = require('./../models') +const VolumeMapping = models.VolumeMapping class VolumeMappingManager extends BaseManager { getEntity() { @@ -21,12 +21,12 @@ class VolumeMappingManager extends BaseManager { } findAll(where, transaction) { - return VolumeMapping.findAll({ - where: where, - attributes: ['hostDestination', 'containerDestination', 'accessMode', 'id'] - }, {transaction: transaction}) + return VolumeMapping.findAll({ + where: where, + attributes: ['hostDestination', 'containerDestination', 'accessMode', 'id'], + }, {transaction: transaction}) } } -const instance = new VolumeMappingManager(); -module.exports = instance; \ No newline at end of file +const instance = new VolumeMappingManager() +module.exports = instance diff --git a/src/sequelize/migrations/20180930155645-create-user.js b/src/sequelize/migrations/20180930155645-create-user.js index 2b1c416d3..3fbc1746e 100644 --- a/src/sequelize/migrations/20180930155645-create-user.js +++ b/src/sequelize/migrations/20180930155645-create-user.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Users', { @@ -7,39 +7,44 @@ module.exports = { autoIncrement: true, primaryKey: true, type: Sequelize.INTEGER, - field: 'id' + field: 'id', }, firstName: { + /* eslint-disable new-cap */ type: Sequelize.STRING(100), field: 'first_name', - defaultValue: "" + defaultValue: '', }, lastName: { + /* eslint-disable new-cap */ type: Sequelize.STRING(100), field: 'last_name', - defaultValue: "" + defaultValue: '', }, email: { + /* eslint-disable new-cap */ type: Sequelize.STRING(100), field: 'email', - defaultValue: "" + defaultValue: '', }, password: { + /* eslint-disable new-cap */ type: Sequelize.STRING(100), - field: 'password' + field: 'password', }, tempPassword: { + /* eslint-disable new-cap */ type: Sequelize.STRING(100), - field: 'temp_password' + field: 'temp_password', }, emailActivated: { type: Sequelize.BOOLEAN, field: 'email_activated', - defaultValue: false - } - }); + defaultValue: false, + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('Users'); - } -}; \ No newline at end of file + return queryInterface.dropTable('Users') + }, +} diff --git a/src/sequelize/migrations/20180930164635-create-flow.js b/src/sequelize/migrations/20180930164635-create-flow.js index 4540bef37..3590a2f4c 100644 --- a/src/sequelize/migrations/20180930164635-create-flow.js +++ b/src/sequelize/migrations/20180930164635-create-flow.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Flows', { @@ -7,49 +7,49 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, name: { type: Sequelize.TEXT, field: 'name', - defaultValue: "New Flow" + defaultValue: 'New Flow', }, description: { type: Sequelize.TEXT, field: 'description', - defaultValue: "" + defaultValue: '', }, isActivated: { type: Sequelize.BOOLEAN, field: 'is_activated', - defaultValue: false + defaultValue: false, }, createdAt: { allowNull: false, type: Sequelize.DATE, - field: 'created_at' + field: 'created_at', }, updatedAt: { allowNull: false, type: Sequelize.DATE, - field: 'updated_at' + field: 'updated_at', }, userId: { type: Sequelize.INTEGER, field: 'user_id', - references: { model: 'Users', key: 'id' }, - onDelete: 'cascade' + references: {model: 'Users', key: 'id'}, + onDelete: 'cascade', }, updatedBy: { type: Sequelize.INTEGER, field: 'updated_by', - references: { model: 'Users', key: 'id' }, - onDelete: 'set null' - } - }); + references: {model: 'Users', key: 'id'}, + onDelete: 'set null', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('Flows'); - } -}; \ No newline at end of file + return queryInterface.dropTable('Flows') + }, +} diff --git a/src/sequelize/migrations/20180930173823-create-registry.js b/src/sequelize/migrations/20180930173823-create-registry.js index b5ce5f0e7..b62d47ec0 100644 --- a/src/sequelize/migrations/20180930173823-create-registry.js +++ b/src/sequelize/migrations/20180930173823-create-registry.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Registries', { @@ -7,49 +7,49 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, url: { type: Sequelize.TEXT, - field: 'url' + field: 'url', }, isPublic: { type: Sequelize.BOOLEAN, - field: 'is_public' + field: 'is_public', }, secure: { type: Sequelize.BOOLEAN, - field: 'secure' + field: 'secure', }, certificate: { type: Sequelize.TEXT, - field: 'certificate' + field: 'certificate', }, requiresCert: { type: Sequelize.BOOLEAN, - field: 'requires_cert' + field: 'requires_cert', }, username: { type: Sequelize.TEXT, - field: 'user_name' + field: 'user_name', }, password: { type: Sequelize.TEXT, - field: 'password' + field: 'password', }, userEmail: { type: Sequelize.TEXT, - field: 'user_email' + field: 'user_email', }, userId: { type: Sequelize.INTEGER, field: 'user_id', - references: { model: 'Users', key: 'id' }, - onDelete: 'cascade' - } - }); + references: {model: 'Users', key: 'id'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('Registries'); - } -}; \ No newline at end of file + return queryInterface.dropTable('Registries') + }, +} diff --git a/src/sequelize/migrations/20180930184436-create-catalog-item.js b/src/sequelize/migrations/20180930184436-create-catalog-item.js index 8a8b84957..8b14a1619 100644 --- a/src/sequelize/migrations/20180930184436-create-catalog-item.js +++ b/src/sequelize/migrations/20180930184436-create-catalog-item.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('CatalogItems', { @@ -7,68 +7,68 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, name: { type: Sequelize.TEXT, field: 'name', - defaultValue: 'New Catalog Item' + defaultValue: 'New Catalog Item', }, description: { type: Sequelize.TEXT, field: 'description', - defaultValue: '' + defaultValue: '', }, category: { type: Sequelize.TEXT, - field: 'category' + field: 'category', }, configExample: { type: Sequelize.TEXT, field: 'config_example', - defaultValue: '{}' + defaultValue: '{}', }, publisher: { type: Sequelize.TEXT, - field: 'publisher' + field: 'publisher', }, diskRequired: { type: Sequelize.BIGINT, field: 'disk_required', - defaultValue: 0 + defaultValue: 0, }, ramRequired: { type: Sequelize.BIGINT, field: 'ram_required', - defaultValue: 0 + defaultValue: 0, }, picture: { type: Sequelize.TEXT, field: 'picture', - defaultValue: 'images/shared/default.png' + defaultValue: 'images/shared/default.png', }, isPublic: { type: Sequelize.BOOLEAN, field: 'is_public', - defaultValue: false + defaultValue: false, }, userId: { type: Sequelize.INTEGER, field: 'user_id', - references: { model: 'Users', key: 'id' }, - onDelete: 'cascade' + references: {model: 'Users', key: 'id'}, + onDelete: 'cascade', }, registryId: { type: Sequelize.INTEGER, field: 'registry_id', as: 'registryId', - references: { model: 'Registries', key: 'id' }, + references: {model: 'Registries', key: 'id'}, onDelete: 'set null', - defaultValue: 1 - } - }); + defaultValue: 1, + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('CatalogItems'); - } -}; \ No newline at end of file + return queryInterface.dropTable('CatalogItems') + }, +} diff --git a/src/sequelize/migrations/20180930184703-create-fog-type.js b/src/sequelize/migrations/20180930184703-create-fog-type.js index 8536bc344..43f91c2d8 100644 --- a/src/sequelize/migrations/20180930184703-create-fog-type.js +++ b/src/sequelize/migrations/20180930184703-create-fog-type.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('FogTypes', { @@ -7,41 +7,41 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, name: { type: Sequelize.TEXT, - field: 'name' + field: 'name', }, image: { type: Sequelize.TEXT, - field: 'image' + field: 'image', }, description: { type: Sequelize.TEXT, - field: 'description' + field: 'description', }, networkCatalogItemId: { type: Sequelize.INTEGER, field: 'network_catalog_item_id', - references: { model: 'CatalogItems', key: 'id' }, - onDelete: 'cascade' + references: {model: 'CatalogItems', key: 'id'}, + onDelete: 'cascade', }, halCatalogItemId: { type: Sequelize.INTEGER, field: 'hal_catalog_item_id', - references: { model: 'CatalogItems', key: 'id' }, - onDelete: 'cascade' + references: {model: 'CatalogItems', key: 'id'}, + onDelete: 'cascade', }, bluetoothCatalogItemId: { type: Sequelize.INTEGER, field: 'bluetooth_catalog_item_id', - references: { model: 'CatalogItems', key: 'id' }, - onDelete: 'cascade' - } - }); + references: {model: 'CatalogItems', key: 'id'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('FogTypes'); - } -}; \ No newline at end of file + return queryInterface.dropTable('FogTypes') + }, +} diff --git a/src/sequelize/migrations/20180930184921-create-catalog-item-image.js b/src/sequelize/migrations/20180930184921-create-catalog-item-image.js index 3b8209496..c65f8f035 100644 --- a/src/sequelize/migrations/20180930184921-create-catalog-item-image.js +++ b/src/sequelize/migrations/20180930184921-create-catalog-item-image.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('CatalogItemImages', { @@ -7,27 +7,27 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, containerImage: { type: Sequelize.TEXT, - field: 'container_image' + field: 'container_image', }, catalogItemId: { type: Sequelize.INTEGER, field: 'catalog_item_id', - references: { model: 'CatalogItems', key: 'id' }, - onDelete: 'cascade' + references: {model: 'CatalogItems', key: 'id'}, + onDelete: 'cascade', }, fogTypeId: { type: Sequelize.INTEGER, field: 'fog_type_id', - references: { model: 'FogTypes', key: 'id' }, - onDelete: 'cascade' - } - }); + references: {model: 'FogTypes', key: 'id'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('CatalogItemImages'); - } -}; \ No newline at end of file + return queryInterface.dropTable('CatalogItemImages') + }, +} diff --git a/src/sequelize/migrations/20180930194506-create-catalog-item-input-type.js b/src/sequelize/migrations/20180930194506-create-catalog-item-input-type.js index d89604704..6d13e5f5c 100644 --- a/src/sequelize/migrations/20180930194506-create-catalog-item-input-type.js +++ b/src/sequelize/migrations/20180930194506-create-catalog-item-input-type.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('CatalogItemInputTypes', { @@ -7,25 +7,25 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, infoType: { type: Sequelize.TEXT, - field: 'info_type' + field: 'info_type', }, infoFormat: { type: Sequelize.TEXT, - field: 'info_format' + field: 'info_format', }, catalogItemId: { type: Sequelize.INTEGER, field: 'catalog_item_id', - references: { model: 'CatalogItems', key: 'id' }, - onDelete: 'cascade' - } - }); + references: {model: 'CatalogItems', key: 'id'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('CatalogItemInputTypes'); - } -}; \ No newline at end of file + return queryInterface.dropTable('CatalogItemInputTypes') + }, +} diff --git a/src/sequelize/migrations/20180930195746-create-catalog-item-output-type.js b/src/sequelize/migrations/20180930195746-create-catalog-item-output-type.js index 92992eb83..d8da6cd4a 100644 --- a/src/sequelize/migrations/20180930195746-create-catalog-item-output-type.js +++ b/src/sequelize/migrations/20180930195746-create-catalog-item-output-type.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('CatalogItemOutputTypes', { @@ -7,25 +7,25 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, infoType: { type: Sequelize.TEXT, - field: 'info_type' + field: 'info_type', }, infoFormat: { type: Sequelize.TEXT, - field: 'info_format' + field: 'info_format', }, catalogItemId: { type: Sequelize.INTEGER, field: 'catalog_item_id', - references: { model: 'CatalogItems', key: 'id' }, - onDelete: 'cascade' - } - }); + references: {model: 'CatalogItems', key: 'id'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('CatalogItemOutputTypes'); - } -}; \ No newline at end of file + return queryInterface.dropTable('CatalogItemOutputTypes') + }, +} diff --git a/src/sequelize/migrations/20180930204039-create-email-activation-code.js b/src/sequelize/migrations/20180930204039-create-email-activation-code.js index e04d6acdc..c36d217fe 100644 --- a/src/sequelize/migrations/20180930204039-create-email-activation-code.js +++ b/src/sequelize/migrations/20180930204039-create-email-activation-code.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('EmailActivationCodes', { @@ -7,25 +7,25 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, activationCode: { type: Sequelize.TEXT, - field: 'activation_code' + field: 'activation_code', }, expirationTime: { type: Sequelize.BIGINT, - field: 'expiration_time' + field: 'expiration_time', }, userId: { type: Sequelize.INTEGER, field: 'user_id', - references: { model: 'Users', key: 'id' }, - onDelete: 'cascade' - } - }); + references: {model: 'Users', key: 'id'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('EmailActivationCodes'); - } -}; \ No newline at end of file + return queryInterface.dropTable('EmailActivationCodes') + }, +} diff --git a/src/sequelize/migrations/20180930225403-create-fog.js b/src/sequelize/migrations/20180930225403-create-fog.js index bd5c56386..81b9de9c8 100644 --- a/src/sequelize/migrations/20180930225403-create-fog.js +++ b/src/sequelize/migrations/20180930225403-create-fog.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Fogs', { @@ -6,239 +6,239 @@ module.exports = { type: Sequelize.TEXT, primaryKey: true, allowNull: false, - field: 'uuid' + field: 'uuid', }, name: { type: Sequelize.TEXT, - defaultValue: "Unnamed ioFog 1", - field: 'name' + defaultValue: 'Unnamed ioFog 1', + field: 'name', }, location: { type: Sequelize.TEXT, - field: 'location' + field: 'location', }, gpsMode: { type: Sequelize.TEXT, - field: 'gps_mode' + field: 'gps_mode', }, latitude: { type: Sequelize.FLOAT, - field: 'latitude' + field: 'latitude', }, longitude: { type: Sequelize.FLOAT, - field: 'longitude' + field: 'longitude', }, description: { type: Sequelize.TEXT, - field: 'description' + field: 'description', }, lastactive: { type: Sequelize.BIGINT, - field: 'last_active' + field: 'last_active', }, daemonStatus: { type: Sequelize.TEXT, - defaultValue: "UNKNOWN", - field: 'daemon_status' + defaultValue: 'UNKNOWN', + field: 'daemon_status', }, daemonOperatingDuration: { type: Sequelize.BIGINT, defaultValue: 0, - field: 'daemon_operating_duration' + field: 'daemon_operating_duration', }, daemonLastStart: { type: Sequelize.BIGINT, - field: 'daemon_last_start' + field: 'daemon_last_start', }, memoryUsage: { type: Sequelize.FLOAT, defaultValue: 0.000, - field: 'memory_usage' + field: 'memory_usage', }, diskUsage: { type: Sequelize.FLOAT, defaultValue: 0.000, - field: 'disk_usage' + field: 'disk_usage', }, cpuUsage: { type: Sequelize.FLOAT, defaultValue: 0.00, - field: 'cpu_usage' + field: 'cpu_usage', }, memoryViolation: { type: Sequelize.TEXT, - field: 'memory_violation' + field: 'memory_violation', }, diskViolation: { type: Sequelize.TEXT, - field: 'disk_violation' + field: 'disk_violation', }, cpuViolation: { type: Sequelize.TEXT, - field: 'cpu_violation' + field: 'cpu_violation', }, catalogItemStatus: { type: Sequelize.TEXT, - field: 'catalog_item_status' + field: 'catalog_item_status', }, repositoryCount: { type: Sequelize.BIGINT, - field: 'repository_count' + field: 'repository_count', }, repositoryStatus: { type: Sequelize.TEXT, - field: 'repository_status' + field: 'repository_status', }, systemTime: { type: Sequelize.BIGINT, - field: 'system_time' + field: 'system_time', }, lastStatusTime: { type: Sequelize.BIGINT, - field: 'last_status_time' + field: 'last_status_time', }, ipAddress: { type: Sequelize.TEXT, - defaultValue: "0.0.0.0", - field: 'ip_address' + defaultValue: '0.0.0.0', + field: 'ip_address', }, processedMessages: { type: Sequelize.BIGINT, defaultValue: 0, - field: 'processed_messages' + field: 'processed_messages', }, catalogItemMessageCounts: { type: Sequelize.TEXT, - field: 'catalog_item_message_counts' + field: 'catalog_item_message_counts', }, messageSpeed: { type: Sequelize.BIGINT, - field: 'message_speed' + field: 'message_speed', }, lastCommandTime: { type: Sequelize.BIGINT, - field: 'last_command_time' + field: 'last_command_time', }, networkInterface: { type: Sequelize.TEXT, - defaultValue: "eth0", - field: 'network_interface' + defaultValue: 'eth0', + field: 'network_interface', }, dockerUrl: { type: Sequelize.TEXT, - defaultValue: "unix:///var/run/docker.sock", - field: 'docker_url' + defaultValue: 'unix:///var/run/docker.sock', + field: 'docker_url', }, diskLimit: { type: Sequelize.FLOAT, defaultValue: 50, - field: 'disk_limit' + field: 'disk_limit', }, diskDirectory: { type: Sequelize.TEXT, defaultValue: '/var/lib/iofog/', - field: 'disk_directory' + field: 'disk_directory', }, memoryLimit: { type: Sequelize.FLOAT, defaultValue: 4096, - field: 'memory_limit' + field: 'memory_limit', }, cpuLimit: { type: Sequelize.FLOAT, defaultValue: 80, - field: 'cpu_limit' + field: 'cpu_limit', }, logLimit: { type: Sequelize.FLOAT, defaultValue: 10, - field: 'log_limit' + field: 'log_limit', }, logDirectory: { type: Sequelize.TEXT, - defaultValue: "/var/log/iofog/", - field: 'log_directory' + defaultValue: '/var/log/iofog/', + field: 'log_directory', }, bluetoothEnabled: { type: Sequelize.INTEGER, defaultValue: 0, - field: 'bluetooth' + field: 'bluetooth', }, abstractedHardwareEnabled: { type: Sequelize.INTEGER, defaultValue: 0, - field: 'hal' + field: 'hal', }, logFileCount: { type: Sequelize.BIGINT, defaultValue: 10, - field: 'log_file_count' + field: 'log_file_count', }, version: { type: Sequelize.TEXT, - field: 'version' + field: 'version', }, isReadyToUpgrade: { type: Sequelize.BOOLEAN, defaultValue: 1, - field: "is_ready_to_upgrade" + field: 'is_ready_to_upgrade', }, isReadyToRollback: { type: Sequelize.BOOLEAN, defaultValue: 0, - field: "is_ready_to_rollback" + field: 'is_ready_to_rollback', }, statusFrequency: { type: Sequelize.INTEGER, defaultValue: 10, - field: 'status_frequency' + field: 'status_frequency', }, changeFrequency: { type: Sequelize.INTEGER, defaultValue: 20, - field: 'change_frequency' + field: 'change_frequency', }, deviceScanFrequency: { type: Sequelize.INTEGER, defaultValue: 20, - field: 'device_scan_frequency' + field: 'device_scan_frequency', }, tunnel: { type: Sequelize.TEXT, - defaultValue: "", - field: 'tunnel' + defaultValue: '', + field: 'tunnel', }, watchdogEnabled: { type: Sequelize.BOOLEAN, defaultValue: 1, - field: 'isolated_docker_container' + field: 'isolated_docker_container', }, createdAt: { allowNull: false, type: Sequelize.DATE, - field: 'created_at' + field: 'created_at', }, updatedAt: { allowNull: false, type: Sequelize.DATE, - field: 'updated_at' + field: 'updated_at', }, userId: { type: Sequelize.INTEGER, field: 'user_id', - references: { model: 'Users', key: 'id' }, - onDelete: 'cascade' + references: {model: 'Users', key: 'id'}, + onDelete: 'cascade', }, fogTypeId: { type: Sequelize.INTEGER, field: 'fog_type_id', - references: { model: 'FogTypes', key: 'id' }, - onDelete: 'set null' - } - }); + references: {model: 'FogTypes', key: 'id'}, + onDelete: 'set null', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('Fogs'); - } -}; \ No newline at end of file + return queryInterface.dropTable('Fogs') + }, +} diff --git a/src/sequelize/migrations/20180930225846-create-change-tracking.js b/src/sequelize/migrations/20180930225846-create-change-tracking.js index 6a3a130cb..ba9c45de7 100644 --- a/src/sequelize/migrations/20180930225846-create-change-tracking.js +++ b/src/sequelize/migrations/20180930225846-create-change-tracking.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('ChangeTrackings', { @@ -7,61 +7,61 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, containerConfig: { type: Sequelize.BOOLEAN, - field: 'container_config' + field: 'container_config', }, reboot: { type: Sequelize.BOOLEAN, - field: 'reboot' + field: 'reboot', }, deletenode: { type: Sequelize.BOOLEAN, - field: 'deletenode' + field: 'deletenode', }, version: { type: Sequelize.BOOLEAN, - field: 'version' + field: 'version', }, containerList: { type: Sequelize.BOOLEAN, - field: 'container_list' + field: 'container_list', }, config: { type: Sequelize.BOOLEAN, - field: 'config' + field: 'config', }, routing: { type: Sequelize.BOOLEAN, - field: 'routing' + field: 'routing', }, registries: { type: Sequelize.BOOLEAN, - field: 'registries' + field: 'registries', }, tunnel: { type: Sequelize.BOOLEAN, - field: 'tunnel' + field: 'tunnel', }, diagnostics: { type: Sequelize.BOOLEAN, - field: 'diagnostics' + field: 'diagnostics', }, isImageSnapshot: { type: Sequelize.BOOLEAN, - field: 'image_snapshot' + field: 'image_snapshot', }, iofogUuid: { type: Sequelize.TEXT, field: 'iofog_uuid', - references: { model: 'Fogs', key: 'uuid' }, - onDelete: 'cascade' - } - }); + references: {model: 'Fogs', key: 'uuid'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('ChangeTrackings'); - } -}; \ No newline at end of file + return queryInterface.dropTable('ChangeTrackings') + }, +} diff --git a/src/sequelize/migrations/20180930230219-create-fog-access-token.js b/src/sequelize/migrations/20180930230219-create-fog-access-token.js index 9f9076de0..3c6f26e7b 100644 --- a/src/sequelize/migrations/20180930230219-create-fog-access-token.js +++ b/src/sequelize/migrations/20180930230219-create-fog-access-token.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('FogAccessTokens', { @@ -7,31 +7,31 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, expirationTime: { type: Sequelize.BIGINT, - field: 'expiration_time' + field: 'expiration_time', }, token: { type: Sequelize.TEXT, - field: 'token' + field: 'token', }, iofogUuid: { type: Sequelize.TEXT, field: 'iofog_uuid', - references: { model: 'Fogs', key: 'uuid' }, - onDelete: 'cascade' + references: {model: 'Fogs', key: 'uuid'}, + onDelete: 'cascade', }, userId: { type: Sequelize.INTEGER, field: 'user_id', - references: { model: 'Users', key: 'id' }, - onDelete: 'cascade' - } - }); + references: {model: 'Users', key: 'id'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('FogAccessTokens'); - } -}; \ No newline at end of file + return queryInterface.dropTable('FogAccessTokens') + }, +} diff --git a/src/sequelize/migrations/20180930230626-create-fog-provision-key.js b/src/sequelize/migrations/20180930230626-create-fog-provision-key.js index 4b2808b9d..c1efdec87 100644 --- a/src/sequelize/migrations/20180930230626-create-fog-provision-key.js +++ b/src/sequelize/migrations/20180930230626-create-fog-provision-key.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('FogProvisionKeys', { @@ -7,25 +7,26 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, provisionKey: { + /* eslint-disable new-cap */ type: Sequelize.STRING(100), - field: 'provisioning_string' + field: 'provisioning_string', }, expirationTime: { type: Sequelize.BIGINT, - field: 'expiration_time' + field: 'expiration_time', }, iofogUuid: { type: Sequelize.TEXT, field: 'iofog_uuid', - references: { model: 'Fogs', key: 'uuid' }, - onDelete: 'cascade' + references: {model: 'Fogs', key: 'uuid'}, + onDelete: 'cascade', }, - }); + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('FogProvisionKeys'); - } -}; \ No newline at end of file + return queryInterface.dropTable('FogProvisionKeys') + }, +} diff --git a/src/sequelize/migrations/20180930231241-create-fog-version-command.js b/src/sequelize/migrations/20180930231241-create-fog-version-command.js index f5b34436f..9bb62b460 100644 --- a/src/sequelize/migrations/20180930231241-create-fog-version-command.js +++ b/src/sequelize/migrations/20180930231241-create-fog-version-command.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('FogVersionCommands', { @@ -6,21 +6,22 @@ module.exports = { type: Sequelize.INTEGER, primaryKey: true, autoIncrement: true, - field: 'id' + field: 'id', }, versionCommand: { + /* eslint-disable new-cap */ type: Sequelize.STRING(100), - field: 'version_command' + field: 'version_command', }, iofogUuid: { type: Sequelize.TEXT, field: 'iofog_uuid', - references: { model: 'Fogs', key: 'uuid' }, - onDelete: 'cascade' - } - }); + references: {model: 'Fogs', key: 'uuid'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('FogVersionCommands'); - } -}; \ No newline at end of file + return queryInterface.dropTable('FogVersionCommands') + }, +} diff --git a/src/sequelize/migrations/20180930231536-create-hw-info.js b/src/sequelize/migrations/20180930231536-create-hw-info.js index ba18c8966..2ee12a6c0 100644 --- a/src/sequelize/migrations/20180930231536-create-hw-info.js +++ b/src/sequelize/migrations/20180930231536-create-hw-info.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('HWInfos', { @@ -7,32 +7,32 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, info: { type: Sequelize.TEXT, - defaultValue: " ", - field: 'info' + defaultValue: ' ', + field: 'info', }, createdAt: { allowNull: false, type: Sequelize.DATE, - field: 'created_at' + field: 'created_at', }, updatedAt: { allowNull: false, type: Sequelize.DATE, - field: 'updated_at' + field: 'updated_at', }, iofogUuid: { type: Sequelize.TEXT, field: 'iofog_uuid', - references: { model: 'Fogs', key: 'uuid' }, - onDelete: 'cascade' - } - }); + references: {model: 'Fogs', key: 'uuid'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('HWInfos'); - } -}; \ No newline at end of file + return queryInterface.dropTable('HWInfos') + }, +} diff --git a/src/sequelize/migrations/20180930232242-create-usb-info.js b/src/sequelize/migrations/20180930232242-create-usb-info.js index 897224f52..c257e3cfc 100644 --- a/src/sequelize/migrations/20180930232242-create-usb-info.js +++ b/src/sequelize/migrations/20180930232242-create-usb-info.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('USBInfos', { @@ -7,32 +7,32 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, info: { type: Sequelize.TEXT, - defaultValue: " ", - field: 'info' + defaultValue: ' ', + field: 'info', }, createdAt: { allowNull: false, type: Sequelize.DATE, - field: 'created_at' + field: 'created_at', }, updatedAt: { allowNull: false, type: Sequelize.DATE, - field: 'updated_at' + field: 'updated_at', }, iofogUuid: { type: Sequelize.TEXT, field: 'iofog_uuid', - references: { model: 'Fogs', key: 'uuid' }, - onDelete: 'cascade' - } - }); + references: {model: 'Fogs', key: 'uuid'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('USBInfos'); - } -}; \ No newline at end of file + return queryInterface.dropTable('USBInfos') + }, +} diff --git a/src/sequelize/migrations/20180930232508-create-tunnel.js b/src/sequelize/migrations/20180930232508-create-tunnel.js index 9698cb08e..c1349da89 100644 --- a/src/sequelize/migrations/20180930232508-create-tunnel.js +++ b/src/sequelize/migrations/20180930232508-create-tunnel.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Tunnels', { @@ -7,47 +7,47 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, username: { type: Sequelize.TEXT, - field: 'username' + field: 'username', }, password: { type: Sequelize.TEXT, - field: 'password' + field: 'password', }, host: { type: Sequelize.TEXT, - field: 'host' + field: 'host', }, rport: { type: Sequelize.INTEGER, - field: 'remote_port' + field: 'remote_port', }, lport: { type: Sequelize.INTEGER, defaultValue: 22, - field: 'local_port' + field: 'local_port', }, rsakey: { type: Sequelize.TEXT, - field: 'rsa_key' + field: 'rsa_key', }, closed: { type: Sequelize.BOOLEAN, defaultValue: false, - field: 'closed' + field: 'closed', }, iofogUuid: { type: Sequelize.TEXT, field: 'iofog_uuid', - references: { model: 'Fogs', key: 'uuid' }, - onDelete: 'cascade' - } - }); + references: {model: 'Fogs', key: 'uuid'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('Tunnels'); - } -}; \ No newline at end of file + return queryInterface.dropTable('Tunnels') + }, +} diff --git a/src/sequelize/migrations/20181001062956-create-microservice.js b/src/sequelize/migrations/20181001062956-create-microservice.js index 0d6117b37..9ae717487 100644 --- a/src/sequelize/migrations/20181001062956-create-microservice.js +++ b/src/sequelize/migrations/20181001062956-create-microservice.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Microservices', { @@ -6,91 +6,91 @@ module.exports = { type: Sequelize.TEXT, primaryKey: true, allowNull: false, - field: 'uuid' + field: 'uuid', }, config: { type: Sequelize.TEXT, - field: 'config' + field: 'config', }, name: { type: Sequelize.TEXT, - field: 'name' + field: 'name', }, configLastUpdated: { type: Sequelize.BIGINT, - field: 'config_last_updated' + field: 'config_last_updated', }, isNetwork: { type: Sequelize.BOOLEAN, - field: 'is_network' + field: 'is_network', }, needUpdate: { type: Sequelize.BOOLEAN, - field: 'need_update' + field: 'need_update', }, rebuild: { type: Sequelize.BOOLEAN, - field: 'rebuild' + field: 'rebuild', }, rootHostAccess: { type: Sequelize.BOOLEAN, - field: 'root_host_access' + field: 'root_host_access', }, logSize: { type: Sequelize.BIGINT, - field: 'log_size' + field: 'log_size', }, imageSnapshot: { type: Sequelize.TEXT, - field: 'image_snapshot' + field: 'image_snapshot', }, deleteWithCleanup: { type: Sequelize.BOOLEAN, - field: 'delete_with_cleanup' + field: 'delete_with_cleanup', }, createdAt: { allowNull: false, type: Sequelize.DATE, - field: 'created_at' + field: 'created_at', }, updatedAt: { allowNull: false, type: Sequelize.DATE, - field: 'updated_at' + field: 'updated_at', }, iofogUuid: { type: Sequelize.TEXT, field: 'iofog_uuid', - references: { model: 'Fogs', key: 'uuid' }, - onDelete: 'set null' + references: {model: 'Fogs', key: 'uuid'}, + onDelete: 'set null', }, updatedBy: { type: Sequelize.INTEGER, field: 'updated_by', - references: { model: 'Users', key: 'id' }, - onDelete: 'set null' + references: {model: 'Users', key: 'id'}, + onDelete: 'set null', }, catalogItemId: { type: Sequelize.INTEGER, field: 'catalog_item_id', - references: { model: 'CatalogItems', key: 'id' }, - onDelete: 'cascade' + references: {model: 'CatalogItems', key: 'id'}, + onDelete: 'cascade', }, registryId: { type: Sequelize.INTEGER, field: 'registry_id', - references: { model: 'Registries', key: 'id' }, - onDelete: 'cascade' + references: {model: 'Registries', key: 'id'}, + onDelete: 'cascade', }, flowId: { type: Sequelize.INTEGER, field: 'flow_id', - references: { model: 'Flows', key: 'id' }, - onDelete: 'cascade' - } - }); + references: {model: 'Flows', key: 'id'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('Microservices'); - } -}; \ No newline at end of file + return queryInterface.dropTable('Microservices') + }, +} diff --git a/src/sequelize/migrations/20181001070828-create-microservice-port.js b/src/sequelize/migrations/20181001070828-create-microservice-port.js index 1c53f4e5a..a07cafb6d 100644 --- a/src/sequelize/migrations/20181001070828-create-microservice-port.js +++ b/src/sequelize/migrations/20181001070828-create-microservice-port.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('MicroservicePorts', { @@ -7,45 +7,45 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, portInternal: { type: Sequelize.INTEGER, - field: 'port_internal' + field: 'port_internal', }, portExternal: { type: Sequelize.INTEGER, - field: 'port_external' + field: 'port_external', }, isPublic: { type: Sequelize.BOOLEAN, - field: 'is_public' + field: 'is_public', }, createdAt: { allowNull: false, type: Sequelize.DATE, - field: 'created_at' + field: 'created_at', }, updatedAt: { allowNull: false, type: Sequelize.DATE, - field: 'updated_at' + field: 'updated_at', }, microserviceUuid: { type: Sequelize.TEXT, field: 'microservice_uuid', - references: { model: 'Microservices', key: 'uuid' }, - onDelete: 'cascade' + references: {model: 'Microservices', key: 'uuid'}, + onDelete: 'cascade', }, updatedBy: { type: Sequelize.INTEGER, field: 'updated_by', - references: { model: 'Users', key: 'id' }, - onDelete: 'cascade' - } - }); + references: {model: 'Users', key: 'id'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('MicroservicePorts'); - } -}; \ No newline at end of file + return queryInterface.dropTable('MicroservicePorts') + }, +} diff --git a/src/sequelize/migrations/20181001071315-create-microservice-status.js b/src/sequelize/migrations/20181001071315-create-microservice-status.js index e4145fe99..07c78b948 100644 --- a/src/sequelize/migrations/20181001071315-create-microservice-status.js +++ b/src/sequelize/migrations/20181001071315-create-microservice-status.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('MicroserviceStatuses', { @@ -7,45 +7,45 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, status: { type: Sequelize.TEXT, - field: 'status' + field: 'status', }, cpuUsage: { type: Sequelize.FLOAT, defaultValue: 0.000, - field: 'cpu_usage' + field: 'cpu_usage', }, memoryUsage: { type: Sequelize.BIGINT, defaultValue: 0, - field: 'memory_usage' + field: 'memory_usage', }, containerId: { type: Sequelize.TEXT, - field: 'container_id' + field: 'container_id', }, createdAt: { allowNull: false, type: Sequelize.DATE, - field: 'created_at' + field: 'created_at', }, updatedAt: { allowNull: false, type: Sequelize.DATE, - field: 'updated_at' + field: 'updated_at', }, microserviceUuid: { type: Sequelize.TEXT, field: 'microservice_uuid', - references: { model: 'Microservices', key: 'uuid' }, - onDelete: 'cascade' - } - }); + references: {model: 'Microservices', key: 'uuid'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('MicroserviceStatuses'); - } -}; \ No newline at end of file + return queryInterface.dropTable('MicroserviceStatuses') + }, +} diff --git a/src/sequelize/migrations/20181001071628-create-connector.js b/src/sequelize/migrations/20181001071628-create-connector.js index c264d3a5c..7237ea592 100644 --- a/src/sequelize/migrations/20181001071628-create-connector.js +++ b/src/sequelize/migrations/20181001071628-create-connector.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Connectors', { @@ -7,45 +7,45 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, name: { type: Sequelize.TEXT, - field: 'name' + field: 'name', }, domain: { type: Sequelize.TEXT, - field: 'domain' + field: 'domain', }, publicIp: { type: Sequelize.TEXT, - field: 'public_ip' + field: 'public_ip', }, cert: { type: Sequelize.TEXT, - field: 'cert' + field: 'cert', }, selfSignedCerts: { type: Sequelize.BOOLEAN, - field: 'self_signed_certs' + field: 'self_signed_certs', }, devMode: { type: Sequelize.BOOLEAN, - field: 'dev_mode' + field: 'dev_mode', }, createdAt: { allowNull: false, type: Sequelize.DATE, - field: 'created_at' + field: 'created_at', }, updatedAt: { allowNull: false, type: Sequelize.DATE, - field: 'updated_at' - } - }); + field: 'updated_at', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('Connectors'); - } -}; \ No newline at end of file + return queryInterface.dropTable('Connectors') + }, +} diff --git a/src/sequelize/migrations/20181001071858-create-connector-port.js b/src/sequelize/migrations/20181001071858-create-connector-port.js index 7fa75ebb9..ca2437d88 100644 --- a/src/sequelize/migrations/20181001071858-create-connector-port.js +++ b/src/sequelize/migrations/20181001071858-create-connector-port.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('ConnectorPorts', { @@ -7,63 +7,63 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, port1: { type: Sequelize.INTEGER, - field: 'port1' + field: 'port1', }, port2: { type: Sequelize.INTEGER, - field: 'port2' + field: 'port2', }, maxConnectionsPort1: { type: Sequelize.INTEGER, - field: 'max_connections_port1' + field: 'max_connections_port1', }, maxConnectionsPort2: { type: Sequelize.INTEGER, - field: 'max_connection_port2' + field: 'max_connection_port2', }, passcodePort1: { type: Sequelize.TEXT, - field: 'passcode_port1' + field: 'passcode_port1', }, passcodePort2: { type: Sequelize.TEXT, - field: 'passcode_port2' + field: 'passcode_port2', }, heartBeatAbsenceThresholdPort1: { type: Sequelize.INTEGER, - field: 'heartbeat_absence_threshold_port1' + field: 'heartbeat_absence_threshold_port1', }, heartBeatAbsenceThresholdPort2: { type: Sequelize.INTEGER, - field: 'heartbeat_absence_threshold_port2' + field: 'heartbeat_absence_threshold_port2', }, mappingId: { type: Sequelize.TEXT, - field: 'mapping_id' + field: 'mapping_id', }, createdAt: { allowNull: false, type: Sequelize.DATE, - field: 'created_at' + field: 'created_at', }, updatedAt: { allowNull: false, type: Sequelize.DATE, - field: 'updated_at' + field: 'updated_at', }, connectorId: { type: Sequelize.INTEGER, field: 'connector_id', - references: { model: 'Connectors', key: 'id' }, - onDelete: 'cascade' - } - }); + references: {model: 'Connectors', key: 'id'}, + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('ConnectorPorts'); - } -}; \ No newline at end of file + return queryInterface.dropTable('ConnectorPorts') + }, +} diff --git a/src/sequelize/migrations/20181001073429-create-strace-diagnostics.js b/src/sequelize/migrations/20181001073429-create-strace-diagnostics.js index f8efcd6b3..778e3fd39 100644 --- a/src/sequelize/migrations/20181001073429-create-strace-diagnostics.js +++ b/src/sequelize/migrations/20181001073429-create-strace-diagnostics.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('StraceDiagnostics', { @@ -7,11 +7,11 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, straceRun: { type: Sequelize.BOOLEAN, - field: 'strace_run' + field: 'strace_run', }, buffer: { type: Sequelize.TEXT, @@ -21,12 +21,12 @@ module.exports = { microserviceUuid: { type: Sequelize.TEXT, field: 'microservice_uuid', - references: { model: 'Microservices', key: 'uuid' }, - onDelete: 'cascade' + references: {model: 'Microservices', key: 'uuid'}, + onDelete: 'cascade', }, - }); + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('StraceDiagnostics'); - } -}; \ No newline at end of file + return queryInterface.dropTable('StraceDiagnostics') + }, +} diff --git a/src/sequelize/migrations/20181003102815-create-volume-mapping.js b/src/sequelize/migrations/20181003102815-create-volume-mapping.js index 6c18009ae..90f69d347 100644 --- a/src/sequelize/migrations/20181003102815-create-volume-mapping.js +++ b/src/sequelize/migrations/20181003102815-create-volume-mapping.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('VolumeMappings', { @@ -7,29 +7,29 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'uuid' + field: 'uuid', }, hostDestination: { type: Sequelize.TEXT, - field: 'host_destination' + field: 'host_destination', }, containerDestination: { type: Sequelize.TEXT, - field: 'container_destination' + field: 'container_destination', }, accessMode: { type: Sequelize.TEXT, - field: 'access_mode' + field: 'access_mode', }, microserviceUuid: { type: Sequelize.TEXT, field: 'microservice_uuid', references: {model: 'Microservices', key: 'uuid'}, - onDelete: 'cascade' + onDelete: 'cascade', }, - }); + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('VolumeMappings'); - } -}; \ No newline at end of file + return queryInterface.dropTable('VolumeMappings') + }, +} diff --git a/src/sequelize/migrations/20181003104606-create-access-token.js b/src/sequelize/migrations/20181003104606-create-access-token.js index df723a728..148e62181 100644 --- a/src/sequelize/migrations/20181003104606-create-access-token.js +++ b/src/sequelize/migrations/20181003104606-create-access-token.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('AccessTokens', { @@ -7,25 +7,25 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, token: { type: Sequelize.STRING, - field: 'token' + field: 'token', }, expirationTime: { type: Sequelize.BIGINT, - field: 'expiration_time' + field: 'expiration_time', }, userId: { type: Sequelize.INTEGER, field: 'user_id', references: {model: 'Users', key: 'id'}, - onDelete: 'cascade' - } - }); + onDelete: 'cascade', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('AccessTokens'); - } -}; \ No newline at end of file + return queryInterface.dropTable('AccessTokens') + }, +} diff --git a/src/sequelize/migrations/20181022110529-create-routing.js b/src/sequelize/migrations/20181022110529-create-routing.js index e0f373477..d8b0fdbac 100644 --- a/src/sequelize/migrations/20181022110529-create-routing.js +++ b/src/sequelize/migrations/20181022110529-create-routing.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('Routings', { @@ -7,58 +7,58 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, isNetworkConnection: { type: Sequelize.BOOLEAN, defaultValue: false, - field: 'is_network_connection' + field: 'is_network_connection', }, sourceMicroserviceUuid: { type: Sequelize.TEXT, field: 'source_microservice_uuid', - references: { model: 'Microservices', key: 'uuid' }, - onDelete: 'cascade' + references: {model: 'Microservices', key: 'uuid'}, + onDelete: 'cascade', }, destMicroserviceUuid: { type: Sequelize.TEXT, field: 'dest_microservice_uuid', - references: { model: 'Microservices', key: 'uuid' }, - onDelete: 'cascade' + references: {model: 'Microservices', key: 'uuid'}, + onDelete: 'cascade', }, sourceNetworkMicroserviceUuid: { type: Sequelize.TEXT, field: 'source_network_microservice_uuid', - references: { model: 'Microservices', key: 'uuid' }, - onDelete: 'set null' + references: {model: 'Microservices', key: 'uuid'}, + onDelete: 'set null', }, destNetworkMicroserviceUuid: { type: Sequelize.TEXT, field: 'dest_network_microservice_uuid', - references: { model: 'Microservices', key: 'uuid' }, - onDelete: 'set null' + references: {model: 'Microservices', key: 'uuid'}, + onDelete: 'set null', }, sourceIofogUuid: { type: Sequelize.TEXT, field: 'source_iofog_uuid', - references: { model: 'Fogs', key: 'uuid' }, - onDelete: 'set null' + references: {model: 'Fogs', key: 'uuid'}, + onDelete: 'set null', }, destIofogUuid: { type: Sequelize.TEXT, field: 'dest_iofog_uuid', - references: { model: 'Fogs', key: 'uuid' }, - onDelete: 'set null' + references: {model: 'Fogs', key: 'uuid'}, + onDelete: 'set null', }, connectorPortId: { type: Sequelize.TEXT, field: 'connector_port_id', - references: { model: 'ConnectorPorts', key: 'id' }, - onDelete: 'set null' - } - }); + references: {model: 'ConnectorPorts', key: 'id'}, + onDelete: 'set null', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('Routings'); - } -}; \ No newline at end of file + return queryInterface.dropTable('Routings') + }, +} diff --git a/src/sequelize/migrations/20181022114905-create-microservice-public-mode.js b/src/sequelize/migrations/20181022114905-create-microservice-public-mode.js index dab98481d..68583403c 100644 --- a/src/sequelize/migrations/20181022114905-create-microservice-public-mode.js +++ b/src/sequelize/migrations/20181022114905-create-microservice-public-mode.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('MicroservicePublicModes', { @@ -7,41 +7,41 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, microserviceUuid: { type: Sequelize.TEXT, field: 'microservice_uuid', - references: { model: 'Microservices', key: 'uuid' }, - onDelete: 'cascade' + references: {model: 'Microservices', key: 'uuid'}, + onDelete: 'cascade', }, networkMicroserviceUuid: { type: Sequelize.TEXT, field: 'network_microservice_uuid', - references: { model: 'Microservices', key: 'uuid' }, - onDelete: 'set null' + references: {model: 'Microservices', key: 'uuid'}, + onDelete: 'set null', }, iofogUuid: { type: Sequelize.TEXT, field: 'iofog_uuid', - references: { model: 'Fogs', key: 'uuid' }, - onDelete: 'set null' + references: {model: 'Fogs', key: 'uuid'}, + onDelete: 'set null', }, microservicePortId: { type: Sequelize.TEXT, field: 'microservice_port_id', - references: { model: 'MicroservicePorts', key: 'id' }, - onDelete: 'set null' + references: {model: 'MicroservicePorts', key: 'id'}, + onDelete: 'set null', }, connectorPortId: { type: Sequelize.TEXT, field: 'connector_port_id', - references: { model: 'ConnectorPorts', key: 'id' }, - onDelete: 'set null' - } - }); + references: {model: 'ConnectorPorts', key: 'id'}, + onDelete: 'set null', + }, + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('MicroservicePublicModes'); - } -}; \ No newline at end of file + return queryInterface.dropTable('MicroservicePublicModes') + }, +} diff --git a/src/sequelize/migrations/20181031094923-drop-need-update-col-microservices.js b/src/sequelize/migrations/20181031094923-drop-need-update-col-microservices.js index b1d3f82a5..bc8e27bad 100644 --- a/src/sequelize/migrations/20181031094923-drop-need-update-col-microservices.js +++ b/src/sequelize/migrations/20181031094923-drop-need-update-col-microservices.js @@ -1,14 +1,14 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { - return queryInterface.removeColumn('Microservices', 'need_update'); + return queryInterface.removeColumn('Microservices', 'need_update') }, down: (queryInterface, Sequelize) => { return queryInterface.addColumn('Microservices', - 'need_update', - Sequelize.BOOLEAN - ); - } -}; + 'need_update', + Sequelize.BOOLEAN + ) + }, +} diff --git a/src/sequelize/migrations/20181102105758-microservice-status-add-missing-time-cols.js b/src/sequelize/migrations/20181102105758-microservice-status-add-missing-time-cols.js index 0844e5fe6..ffaee6599 100644 --- a/src/sequelize/migrations/20181102105758-microservice-status-add-missing-time-cols.js +++ b/src/sequelize/migrations/20181102105758-microservice-status-add-missing-time-cols.js @@ -1,18 +1,18 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.addColumn('MicroserviceStatuses', - 'operating_duration', - Sequelize.BIGINT + 'operating_duration', + Sequelize.BIGINT ) - .then(() => queryInterface.addColumn('MicroserviceStatuses', - 'start_time', - Sequelize.BIGINT)); + .then(() => queryInterface.addColumn('MicroserviceStatuses', + 'start_time', + Sequelize.BIGINT)) }, down: (queryInterface, Sequelize) => { return queryInterface.removeColumn('MicroserviceStatuses', 'operating_duration') - .then(() => queryInterface.removeColumn('MicroserviceStatuses', 'start_time')); - } -}; + .then(() => queryInterface.removeColumn('MicroserviceStatuses', 'start_time')) + }, +} diff --git a/src/sequelize/migrations/20181102163657-microservice-add-col-remove.js b/src/sequelize/migrations/20181102163657-microservice-add-col-remove.js index 6138b1178..07fcbfa4c 100644 --- a/src/sequelize/migrations/20181102163657-microservice-add-col-remove.js +++ b/src/sequelize/migrations/20181102163657-microservice-add-col-remove.js @@ -1,14 +1,14 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.addColumn('Microservices', - 'delete', - Sequelize.BOOLEAN + 'delete', + Sequelize.BOOLEAN ) }, down: (queryInterface, Sequelize) => { return queryInterface.removeColumn('Microservices', 'delete') - } -}; + }, +} diff --git a/src/sequelize/migrations/20181105120036-change-tracking-container-to-microservice-renaming.js b/src/sequelize/migrations/20181105120036-change-tracking-container-to-microservice-renaming.js index 346a7128d..fd24786ea 100644 --- a/src/sequelize/migrations/20181105120036-change-tracking-container-to-microservice-renaming.js +++ b/src/sequelize/migrations/20181105120036-change-tracking-container-to-microservice-renaming.js @@ -1,17 +1,17 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.renameColumn('ChangeTrackings', 'container_config', 'microservice_config') - .then(() => { - return queryInterface.renameColumn('ChangeTrackings', 'container_list', 'microservice_list') - }) + .then(() => { + return queryInterface.renameColumn('ChangeTrackings', 'container_list', 'microservice_list') + }) }, down: (queryInterface, Sequelize) => { return queryInterface.renameColumn('ChangeTrackings', 'microservice_config', 'container_config') - .then(() => { - return queryInterface.renameColumn('ChangeTrackings', 'microservice_list', 'container_list') - }) - } -}; + .then(() => { + return queryInterface.renameColumn('ChangeTrackings', 'microservice_list', 'container_list') + }) + }, +} diff --git a/src/sequelize/migrations/20181109132609-microservice-rename-updatedBy-to-userId.js b/src/sequelize/migrations/20181109132609-microservice-rename-updatedBy-to-userId.js index 5a1789d81..3a20d0d47 100644 --- a/src/sequelize/migrations/20181109132609-microservice-rename-updatedBy-to-userId.js +++ b/src/sequelize/migrations/20181109132609-microservice-rename-updatedBy-to-userId.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { @@ -7,5 +7,5 @@ module.exports = { down: (queryInterface, Sequelize) => { return queryInterface.renameColumn('Microservices', 'user_id', 'updated_by') - } -}; + }, +} diff --git a/src/sequelize/migrations/20181109132704-microservice-port-rename-updatedBy-to-userId.js b/src/sequelize/migrations/20181109132704-microservice-port-rename-updatedBy-to-userId.js index bb29277f6..d8f2008af 100644 --- a/src/sequelize/migrations/20181109132704-microservice-port-rename-updatedBy-to-userId.js +++ b/src/sequelize/migrations/20181109132704-microservice-port-rename-updatedBy-to-userId.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { @@ -7,5 +7,5 @@ module.exports = { down: (queryInterface, Sequelize) => { return queryInterface.renameColumn('MicroservicePorts', 'user_id', 'updated_by') - } -}; + }, +} diff --git a/src/sequelize/migrations/20181109132723-flow-remove-updatedBy.js b/src/sequelize/migrations/20181109132723-flow-remove-updatedBy.js index 85d4fd00f..cc26fa1b6 100644 --- a/src/sequelize/migrations/20181109132723-flow-remove-updatedBy.js +++ b/src/sequelize/migrations/20181109132723-flow-remove-updatedBy.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { @@ -7,8 +7,8 @@ module.exports = { down: (queryInterface, Sequelize) => { return queryInterface.addColumn('Flows', - 'updated_by', - Sequelize.INTEGER + 'updated_by', + Sequelize.INTEGER ) - } -}; + }, +} diff --git a/src/sequelize/migrations/20181113094807-add-missing-constraints.js b/src/sequelize/migrations/20181113094807-add-missing-constraints.js index 7ffae3a94..6e4615f16 100644 --- a/src/sequelize/migrations/20181113094807-add-missing-constraints.js +++ b/src/sequelize/migrations/20181113094807-add-missing-constraints.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { @@ -8,9 +8,9 @@ module.exports = { references: { name: 'userId', table: 'Users', - field: 'id' + field: 'id', }, - onDelete: 'cascade' + onDelete: 'cascade', }).then(() => { return queryInterface.addConstraint('Microservices', ['user_id'], { type: 'FOREIGN KEY', @@ -18,9 +18,9 @@ module.exports = { references: { name: 'userId', table: 'Users', - field: 'id' + field: 'id', }, - onDelete: 'cascade' + onDelete: 'cascade', }).then(() => { return queryInterface.addConstraint('Microservices', ['iofog_uuid'], { type: 'FOREIGN KEY', @@ -28,9 +28,9 @@ module.exports = { references: { name: 'iofogUuid', table: 'Fogs', - field: 'uuid' + field: 'uuid', }, - onDelete: 'cascade' + onDelete: 'cascade', }) }).then(() => { return queryInterface.addConstraint('Microservices', ['catalog_item_id'], { @@ -39,9 +39,9 @@ module.exports = { references: { name: 'catalogItemId', table: 'CatalogItems', - field: 'id' + field: 'id', }, - onDelete: 'cascade' + onDelete: 'cascade', }) }).then(() => { return queryInterface.addConstraint('Microservices', ['registry_id'], { @@ -50,9 +50,9 @@ module.exports = { references: { name: 'registryId', table: 'Registries', - field: 'id' + field: 'id', }, - onDelete: 'cascade' + onDelete: 'cascade', }) }).then(() => { return queryInterface.addConstraint('Microservices', ['flow_id'], { @@ -61,9 +61,9 @@ module.exports = { references: { name: 'flowId', table: 'Flows', - field: 'id' + field: 'id', }, - onDelete: 'cascade' + onDelete: 'cascade', }) }).then(() => { return queryInterface.addConstraint('ChangeTrackings', ['iofog_uuid'], { @@ -72,9 +72,9 @@ module.exports = { references: { name: 'iofogUuid', table: 'Fogs', - field: 'uuid' + field: 'uuid', }, - onDelete: 'cascade' + onDelete: 'cascade', }) }) }).then(() => { @@ -84,9 +84,9 @@ module.exports = { references: { name: 'userId', table: 'Users', - field: 'id' + field: 'id', }, - onDelete: 'cascade' + onDelete: 'cascade', }) }).then(() => { return queryInterface.addConstraint('MicroservicePorts', ['microservice_uuid'], { @@ -95,33 +95,32 @@ module.exports = { references: { name: 'microserviceUuid', table: 'Microservices', - field: 'uuid' + field: 'uuid', }, - onDelete: 'cascade' + onDelete: 'cascade', }) - }); + }) }, down: (queryInterface, Sequelize) => { - // for SQLite return queryInterface.renameColumn('Flows', 'user_id', 'user_id1') - .then(() => { - return queryInterface.renameColumn('Flows', 'user_id1', 'user_id') - }).then(() => { - return queryInterface.renameColumn('Microservices', 'user_id', 'user_id1') - }).then(() => { - return queryInterface.renameColumn('Microservices', 'user_id1', 'user_id') - }).then(() => { - return queryInterface.renameColumn('ChangeTrackings', 'iofog_uuid', 'iofog_uuid1') - }).then(() => { - return queryInterface.renameColumn('ChangeTrackings', 'iofog_uuid1', 'iofog_uuid') - }).then(() => { - return queryInterface.renameColumn('MicroservicePorts', 'user_id', 'user_id1') - }).then(() => { - return queryInterface.renameColumn('MicroservicePorts', 'user_id1', 'user_id') - }) + .then(() => { + return queryInterface.renameColumn('Flows', 'user_id1', 'user_id') + }).then(() => { + return queryInterface.renameColumn('Microservices', 'user_id', 'user_id1') + }).then(() => { + return queryInterface.renameColumn('Microservices', 'user_id1', 'user_id') + }).then(() => { + return queryInterface.renameColumn('ChangeTrackings', 'iofog_uuid', 'iofog_uuid1') + }).then(() => { + return queryInterface.renameColumn('ChangeTrackings', 'iofog_uuid1', 'iofog_uuid') + }).then(() => { + return queryInterface.renameColumn('MicroservicePorts', 'user_id', 'user_id1') + }).then(() => { + return queryInterface.renameColumn('MicroservicePorts', 'user_id1', 'user_id') + }) // for other DB @@ -143,5 +142,5 @@ module.exports = { // }).then(() => { // return queryInterface.removeConstraint('MicroservicePorts', 'microserviceUuid') // }); - } -}; + }, +} diff --git a/src/sequelize/migrations/20190117110458-create-tracking-event.js b/src/sequelize/migrations/20190117110458-create-tracking-event.js index 701278d18..b926b65ba 100644 --- a/src/sequelize/migrations/20190117110458-create-tracking-event.js +++ b/src/sequelize/migrations/20190117110458-create-tracking-event.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.createTable('TrackingEvents', { @@ -7,32 +7,32 @@ module.exports = { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, uuid: { type: Sequelize.TEXT, allowNull: false, - field: 'uuid' + field: 'uuid', }, sourceType: { type: Sequelize.TEXT, - field: 'source_type' + field: 'source_type', }, timestamp: { type: Sequelize.BIGINT, - field: 'timestamp' + field: 'timestamp', }, type: { type: Sequelize.TEXT, - field: 'type' + field: 'type', }, data: { type: Sequelize.TEXT, - field: 'data' + field: 'data', }, - }); + }) }, down: (queryInterface, Sequelize) => { - return queryInterface.dropTable('TrackingEvents'); - } -}; \ No newline at end of file + return queryInterface.dropTable('TrackingEvents') + }, +} diff --git a/src/sequelize/models/accesstoken.js b/src/sequelize/models/accesstoken.js index ab8bc34a1..0614ddc2c 100644 --- a/src/sequelize/models/accesstoken.js +++ b/src/sequelize/models/accesstoken.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const AccessToken = sequelize.define('AccessToken', { id: { @@ -6,28 +6,28 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, token: { type: DataTypes.STRING, - field: 'token' + field: 'token', }, expirationTime: { type: DataTypes.BIGINT, - field: 'expiration_time' - } + field: 'expiration_time', + }, }, { timestamps: false, - underscored: true - }); - AccessToken.associate = function (models) { + underscored: true, + }) + AccessToken.associate = function(models) { AccessToken.belongsTo(models.User, { foreignKey: { name: 'userId', - field: 'user_id' + field: 'user_id', }, - as: 'user' - }); - }; - return AccessToken; -}; \ No newline at end of file + as: 'user', + }) + } + return AccessToken +} diff --git a/src/sequelize/models/catalogitem.js b/src/sequelize/models/catalogitem.js index 2b400a815..a5f207cb9 100644 --- a/src/sequelize/models/catalogitem.js +++ b/src/sequelize/models/catalogitem.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const CatalogItem = sequelize.define('CatalogItem', { id: { @@ -6,95 +6,94 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, name: { type: DataTypes.TEXT, field: 'name', - defaultValue: 'New Catalog Item' + defaultValue: 'New Catalog Item', }, description: { type: DataTypes.TEXT, field: 'description', - defaultValue: '' + defaultValue: '', }, category: { type: DataTypes.TEXT, - field: 'category' + field: 'category', }, configExample: { type: DataTypes.TEXT, field: 'config_example', - defaultValue: '{}' + defaultValue: '{}', }, publisher: { type: DataTypes.TEXT, - field: 'publisher' + field: 'publisher', }, diskRequired: { type: DataTypes.BIGINT, field: 'disk_required', - defaultValue: 0 + defaultValue: 0, }, ramRequired: { type: DataTypes.BIGINT, field: 'ram_required', - defaultValue: 0 + defaultValue: 0, }, picture: { type: DataTypes.TEXT, field: 'picture', - defaultValue: 'images/shared/default.png' + defaultValue: 'images/shared/default.png', }, isPublic: { type: DataTypes.BOOLEAN, field: 'is_public', - defaultValue: false - } + defaultValue: false, + }, }, { timestamps: false, - underscored: true - }); - CatalogItem.associate = function (models) { - + underscored: true, + }) + CatalogItem.associate = function(models) { CatalogItem.belongsTo(models.Registry, { foreignKey: { name: 'registryId', - field: 'registry_id' + field: 'registry_id', }, as: 'registry', onDelete: 'set null', - defaultValue: 1 - }); + defaultValue: 1, + }) CatalogItem.belongsTo(models.User, { foreignKey: { name: 'userId', - field: 'user_id' + field: 'user_id', }, as: 'user', - onDelete: 'cascade' - }); + onDelete: 'cascade', + }) CatalogItem.hasMany(models.CatalogItemImage, { foreignKey: 'catalog_item_id', - as: 'images' - }); + as: 'images', + }) CatalogItem.hasOne(models.CatalogItemInputType, { foreignKey: 'catalog_item_id', - as: 'inputType' - }); + as: 'inputType', + }) CatalogItem.hasOne(models.CatalogItemOutputType, { foreignKey: 'catalog_item_id', - as: 'outputType' - }); + as: 'outputType', + }) CatalogItem.hasMany(models.Microservice, { foreignKey: 'catalog_item_id', - as: 'microservices' - }); - }; - return CatalogItem; -}; \ No newline at end of file + as: 'microservices', + }) + } + return CatalogItem +} diff --git a/src/sequelize/models/catalogitemimage.js b/src/sequelize/models/catalogitemimage.js index 7844d68a8..ac969e9f6 100644 --- a/src/sequelize/models/catalogitemimage.js +++ b/src/sequelize/models/catalogitemimage.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const CatalogItemImage = sequelize.define('CatalogItemImage', { id: { @@ -6,35 +6,34 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, containerImage: { type: DataTypes.TEXT, - field: 'container_image' - } + field: 'container_image', + }, }, { timestamps: false, - underscored: true - }); - CatalogItemImage.associate = function (models) { - + underscored: true, + }) + CatalogItemImage.associate = function(models) { CatalogItemImage.belongsTo(models.CatalogItem, { foreignKey: { name: 'catalogItemId', - field: 'catalog_item_id' + field: 'catalog_item_id', }, as: 'catalogItem', - onDelete: 'cascade' - }); + onDelete: 'cascade', + }) CatalogItemImage.belongsTo(models.FogType, { foreignKey: { name: 'fogTypeId', - field: 'fog_type_id' + field: 'fog_type_id', }, as: 'fogType', - onDelete: 'cascade' - }); - }; - return CatalogItemImage; -}; \ No newline at end of file + onDelete: 'cascade', + }) + } + return CatalogItemImage +} diff --git a/src/sequelize/models/catalogiteminputtype.js b/src/sequelize/models/catalogiteminputtype.js index 3daf9576f..a31baff91 100644 --- a/src/sequelize/models/catalogiteminputtype.js +++ b/src/sequelize/models/catalogiteminputtype.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const CatalogItemInputType = sequelize.define('CatalogItemInputType', { id: { @@ -6,29 +6,28 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, infoType: { type: DataTypes.TEXT, - field: 'info_type' + field: 'info_type', }, infoFormat: { type: DataTypes.TEXT, - field: 'info_format' - } + field: 'info_format', + }, }, { timestamps: false, - underscored: true - }); - CatalogItemInputType.associate = function (models) { - + underscored: true, + }) + CatalogItemInputType.associate = function(models) { CatalogItemInputType.belongsTo(models.CatalogItem, { foreignKey: { name: 'catalogItemId', - field: 'catalog_item_id' + field: 'catalog_item_id', }, - as: 'catalogItem' - }); - }; - return CatalogItemInputType; -}; \ No newline at end of file + as: 'catalogItem', + }) + } + return CatalogItemInputType +} diff --git a/src/sequelize/models/catalogitemoutputtype.js b/src/sequelize/models/catalogitemoutputtype.js index 9df736b32..917ceafad 100644 --- a/src/sequelize/models/catalogitemoutputtype.js +++ b/src/sequelize/models/catalogitemoutputtype.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const CatalogItemOutputType = sequelize.define('CatalogItemOutputType', { id: { @@ -6,29 +6,28 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, infoType: { type: DataTypes.TEXT, - field: 'info_type' + field: 'info_type', }, infoFormat: { type: DataTypes.TEXT, - field: 'info_format' - } + field: 'info_format', + }, }, { timestamps: false, - underscored: true - }); - CatalogItemOutputType.associate = function (models) { - + underscored: true, + }) + CatalogItemOutputType.associate = function(models) { CatalogItemOutputType.belongsTo(models.CatalogItem, { foreignKey: { name: 'catalogItemId', - field: 'catalog_item_id' + field: 'catalog_item_id', }, - as: 'catalogItem' - }); - }; - return CatalogItemOutputType; -}; \ No newline at end of file + as: 'catalogItem', + }) + } + return CatalogItemOutputType +} diff --git a/src/sequelize/models/changetracking.js b/src/sequelize/models/changetracking.js index 23034e264..3ba56bbe3 100644 --- a/src/sequelize/models/changetracking.js +++ b/src/sequelize/models/changetracking.js @@ -11,7 +11,7 @@ * */ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const ChangeTracking = sequelize.define('ChangeTracking', { id: { @@ -19,77 +19,76 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, microserviceConfig: { type: DataTypes.BOOLEAN, field: 'microservice_config', - defaultValue: false + defaultValue: false, }, reboot: { type: DataTypes.BOOLEAN, field: 'reboot', - defaultValue: false + defaultValue: false, }, deleteNode: { type: DataTypes.BOOLEAN, field: 'deletenode', - defaultValue: false + defaultValue: false, }, version: { type: DataTypes.BOOLEAN, field: 'version', - defaultValue: false + defaultValue: false, }, microserviceList: { type: DataTypes.BOOLEAN, field: 'microservice_list', - defaultValue: false + defaultValue: false, }, config: { type: DataTypes.BOOLEAN, field: 'config', - defaultValue: false + defaultValue: false, }, routing: { type: DataTypes.BOOLEAN, field: 'routing', - defaultValue: false + defaultValue: false, }, registries: { type: DataTypes.BOOLEAN, field: 'registries', - defaultValue: false + defaultValue: false, }, tunnel: { type: DataTypes.BOOLEAN, field: 'tunnel', - defaultValue: false + defaultValue: false, }, diagnostics: { type: DataTypes.BOOLEAN, field: 'diagnostics', - defaultValue: false + defaultValue: false, }, isImageSnapshot: { type: DataTypes.BOOLEAN, field: 'image_snapshot', - defaultValue: false - } + defaultValue: false, + }, }, { timestamps: false, - underscored: true - }); - ChangeTracking.associate = function (models) { - + underscored: true, + }) + ChangeTracking.associate = function(models) { ChangeTracking.belongsTo(models.Fog, { foreignKey: { name: 'iofogUuid', - field: 'iofog_uuid' + field: 'iofog_uuid', }, as: 'iofog', - onDelete: 'cascade' - }); - }; - return ChangeTracking; -}; \ No newline at end of file + onDelete: 'cascade', + }) + } + return ChangeTracking +} diff --git a/src/sequelize/models/connector.js b/src/sequelize/models/connector.js index b580bf478..a4ba57785 100644 --- a/src/sequelize/models/connector.js +++ b/src/sequelize/models/connector.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const Connector = sequelize.define('Connector', { id: { @@ -6,38 +6,38 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, name: { type: DataTypes.TEXT, - field: 'name' + field: 'name', }, domain: { type: DataTypes.TEXT, - field: 'domain' + field: 'domain', }, publicIp: { type: DataTypes.TEXT, - field: 'public_ip' + field: 'public_ip', }, cert: { type: DataTypes.TEXT, - field: 'cert' + field: 'cert', }, isSelfSignedCert: { type: DataTypes.BOOLEAN, - field: 'self_signed_certs' + field: 'self_signed_certs', }, devMode: { type: DataTypes.BOOLEAN, - field: 'dev_mode' - } + field: 'dev_mode', + }, }, { timestamps: true, - underscored: true - }); - Connector.associate = function (models) { + underscored: true, + }) + Connector.associate = function(models) { - }; - return Connector; -}; \ No newline at end of file + } + return Connector +} diff --git a/src/sequelize/models/connectorport.js b/src/sequelize/models/connectorport.js index 97d6db193..e965513be 100644 --- a/src/sequelize/models/connectorport.js +++ b/src/sequelize/models/connectorport.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const ConnectorPort = sequelize.define('ConnectorPort', { id: { @@ -6,58 +6,57 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, port1: { type: DataTypes.INTEGER, - field: 'port1' + field: 'port1', }, port2: { type: DataTypes.INTEGER, - field: 'port2' + field: 'port2', }, maxConnectionsPort1: { type: DataTypes.INTEGER, - field: 'max_connections_port1' + field: 'max_connections_port1', }, maxConnectionsPort2: { type: DataTypes.INTEGER, - field: 'max_connection_port2' + field: 'max_connection_port2', }, passcodePort1: { type: DataTypes.TEXT, - field: 'passcode_port1' + field: 'passcode_port1', }, passcodePort2: { type: DataTypes.TEXT, - field: 'passcode_port2' + field: 'passcode_port2', }, heartBeatAbsenceThresholdPort1: { type: DataTypes.INTEGER, - field: 'heartbeat_absence_threshold_port1' + field: 'heartbeat_absence_threshold_port1', }, heartBeatAbsenceThresholdPort2: { type: DataTypes.INTEGER, - field: 'heartbeat_absence_threshold_port2' + field: 'heartbeat_absence_threshold_port2', }, mappingId: { type: DataTypes.TEXT, - field: 'mapping_id' - } + field: 'mapping_id', + }, }, { timestamps: true, - underscored: true - }); - ConnectorPort.associate = function (models) { - + underscored: true, + }) + ConnectorPort.associate = function(models) { ConnectorPort.belongsTo(models.Connector, { foreignKey: { name: 'connectorId', - field: 'connector_id' + field: 'connector_id', }, as: 'connector', - onDelete: 'cascade' - }); - }; - return ConnectorPort; -}; \ No newline at end of file + onDelete: 'cascade', + }) + } + return ConnectorPort +} diff --git a/src/sequelize/models/emailactivationcode.js b/src/sequelize/models/emailactivationcode.js index 840d869e5..183a54994 100644 --- a/src/sequelize/models/emailactivationcode.js +++ b/src/sequelize/models/emailactivationcode.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const EmailActivationCode = sequelize.define('EmailActivationCode', { id: { @@ -6,30 +6,29 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, activationCode: { type: DataTypes.TEXT, - field: 'activation_code' + field: 'activation_code', }, expirationTime: { type: DataTypes.BIGINT, - field: 'expiration_time' - } + field: 'expiration_time', + }, }, { timestamps: false, - underscored: true - }); - EmailActivationCode.associate = function (models) { - + underscored: true, + }) + EmailActivationCode.associate = function(models) { EmailActivationCode.belongsTo(models.User, { foreignKey: { name: 'userId', - field: 'user_id' + field: 'user_id', }, as: 'user', - onDelete: 'cascade' - }); - }; - return EmailActivationCode; -}; \ No newline at end of file + onDelete: 'cascade', + }) + } + return EmailActivationCode +} diff --git a/src/sequelize/models/flow.js b/src/sequelize/models/flow.js index a4e8439f5..0fd84c2ab 100644 --- a/src/sequelize/models/flow.js +++ b/src/sequelize/models/flow.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const Flow = sequelize.define('Flow', { id: { @@ -6,46 +6,45 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, name: { type: DataTypes.TEXT, field: 'name', - defaultValue: "New Flow" + defaultValue: 'New Flow', }, description: { type: DataTypes.TEXT, field: 'description', - defaultValue: "" + defaultValue: '', }, isActivated: { type: DataTypes.BOOLEAN, field: 'is_activated', - defaultValue: false - } + defaultValue: false, + }, }, { timestamps: true, - underscored: true - }); - Flow.associate = function (models) { - + underscored: true, + }) + Flow.associate = function(models) { Flow.belongsTo(models.User, { foreignKey: { name: 'userId', - field: 'user_id' + field: 'user_id', }, as: 'user', - onDelete: 'cascade' - }); + onDelete: 'cascade', + }) Flow.hasMany(models.Microservice, { foreignKey: { name: 'flowId', - field: 'flow_id' + field: 'flow_id', }, - as: 'microservices' + as: 'microservices', }) - }; - return Flow; -}; \ No newline at end of file + } + return Flow +} diff --git a/src/sequelize/models/fog.js b/src/sequelize/models/fog.js index d25743ab2..747d322d6 100644 --- a/src/sequelize/models/fog.js +++ b/src/sequelize/models/fog.js @@ -1,254 +1,252 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const Fog = sequelize.define('Fog', { uuid: { type: DataTypes.TEXT, primaryKey: true, allowNull: false, - field: 'uuid' + field: 'uuid', }, name: { type: DataTypes.TEXT, - defaultValue: "Unnamed ioFog 1", - field: 'name' + defaultValue: 'Unnamed ioFog 1', + field: 'name', }, location: { type: DataTypes.TEXT, - field: 'location' + field: 'location', }, gpsMode: { type: DataTypes.TEXT, - field: 'gps_mode' + field: 'gps_mode', }, latitude: { type: DataTypes.FLOAT, - field: 'latitude' + field: 'latitude', }, longitude: { type: DataTypes.FLOAT, - field: 'longitude' + field: 'longitude', }, description: { type: DataTypes.TEXT, - field: 'description' + field: 'description', }, lastActive: { type: DataTypes.BIGINT, - field: 'last_active' + field: 'last_active', }, daemonStatus: { type: DataTypes.TEXT, - defaultValue: "UNKNOWN", - field: 'daemon_status' + defaultValue: 'UNKNOWN', + field: 'daemon_status', }, daemonOperatingDuration: { type: DataTypes.BIGINT, defaultValue: 0, - field: 'daemon_operating_duration' + field: 'daemon_operating_duration', }, daemonLastStart: { type: DataTypes.BIGINT, - field: 'daemon_last_start' + field: 'daemon_last_start', }, memoryUsage: { type: DataTypes.FLOAT, defaultValue: 0.000, - field: 'memory_usage' + field: 'memory_usage', }, diskUsage: { type: DataTypes.FLOAT, defaultValue: 0.000, - field: 'disk_usage' + field: 'disk_usage', }, cpuUsage: { type: DataTypes.FLOAT, defaultValue: 0.00, - field: 'cpu_usage' + field: 'cpu_usage', }, memoryViolation: { type: DataTypes.TEXT, - field: 'memory_violation' + field: 'memory_violation', }, diskViolation: { type: DataTypes.TEXT, - field: 'disk_violation' + field: 'disk_violation', }, cpuViolation: { type: DataTypes.TEXT, - field: 'cpu_violation' + field: 'cpu_violation', }, catalogItemStatus: { type: DataTypes.TEXT, - field: 'catalog_item_status' + field: 'catalog_item_status', }, repositoryCount: { type: DataTypes.BIGINT, - field: 'repository_count' + field: 'repository_count', }, repositoryStatus: { type: DataTypes.TEXT, - field: 'repository_status' + field: 'repository_status', }, systemTime: { type: DataTypes.BIGINT, - field: 'system_time' + field: 'system_time', }, lastStatusTime: { type: DataTypes.BIGINT, - field: 'last_status_time' + field: 'last_status_time', }, ipAddress: { type: DataTypes.TEXT, - defaultValue: "0.0.0.0", - field: 'ip_address' + defaultValue: '0.0.0.0', + field: 'ip_address', }, processedMessages: { type: DataTypes.BIGINT, defaultValue: 0, - field: 'processed_messages' + field: 'processed_messages', }, catalogItemMessageCounts: { type: DataTypes.TEXT, - field: 'catalog_item_message_counts' + field: 'catalog_item_message_counts', }, messageSpeed: { type: DataTypes.BIGINT, - field: 'message_speed' + field: 'message_speed', }, lastCommandTime: { type: DataTypes.BIGINT, - field: 'last_command_time' + field: 'last_command_time', }, networkInterface: { type: DataTypes.TEXT, - defaultValue: "eth0", - field: 'network_interface' + defaultValue: 'eth0', + field: 'network_interface', }, dockerUrl: { type: DataTypes.TEXT, - defaultValue: "unix:///var/run/docker.sock", - field: 'docker_url' + defaultValue: 'unix:///var/run/docker.sock', + field: 'docker_url', }, diskLimit: { type: DataTypes.FLOAT, defaultValue: 50, - field: 'disk_limit' + field: 'disk_limit', }, diskDirectory: { type: DataTypes.TEXT, defaultValue: '/var/lib/iofog/', - field: 'disk_directory' + field: 'disk_directory', }, memoryLimit: { type: DataTypes.FLOAT, defaultValue: 4096, - field: 'memory_limit' + field: 'memory_limit', }, cpuLimit: { type: DataTypes.FLOAT, defaultValue: 80, - field: 'cpu_limit' + field: 'cpu_limit', }, logLimit: { type: DataTypes.FLOAT, defaultValue: 10, - field: 'log_limit' + field: 'log_limit', }, logDirectory: { type: DataTypes.TEXT, - defaultValue: "/var/log/iofog/", - field: 'log_directory' + defaultValue: '/var/log/iofog/', + field: 'log_directory', }, bluetoothEnabled: { type: DataTypes.BOOLEAN, defaultValue: false, - field: 'bluetooth' + field: 'bluetooth', }, abstractedHardwareEnabled: { type: DataTypes.BOOLEAN, defaultValue: false, - field: 'hal' + field: 'hal', }, logFileCount: { type: DataTypes.BIGINT, defaultValue: 10, - field: 'log_file_count' + field: 'log_file_count', }, version: { type: DataTypes.TEXT, - field: 'version' + field: 'version', }, isReadyToUpgrade: { type: DataTypes.BOOLEAN, defaultValue: true, - field: "is_ready_to_upgrade" + field: 'is_ready_to_upgrade', }, isReadyToRollback: { type: DataTypes.BOOLEAN, defaultValue: false, - field: "is_ready_to_rollback" + field: 'is_ready_to_rollback', }, statusFrequency: { type: DataTypes.INTEGER, defaultValue: 10, - field: 'status_frequency' + field: 'status_frequency', }, changeFrequency: { type: DataTypes.INTEGER, defaultValue: 20, - field: 'change_frequency' + field: 'change_frequency', }, deviceScanFrequency: { type: DataTypes.INTEGER, defaultValue: 20, - field: 'device_scan_frequency' + field: 'device_scan_frequency', }, tunnel: { type: DataTypes.TEXT, - defaultValue: "", - field: 'tunnel' + defaultValue: '', + field: 'tunnel', }, watchdogEnabled: { type: DataTypes.BOOLEAN, defaultValue: true, - field: 'isolated_docker_container' - } + field: 'isolated_docker_container', + }, }, { timestamps: true, - underscored: true - }); - Fog.associate = function (models) { - + underscored: true, + }) + Fog.associate = function(models) { Fog.belongsTo(models.FogType, { foreignKey: { name: 'fogTypeId', - field: 'fog_type_id' + field: 'fog_type_id', }, as: 'fogType', - defaultValue: 0 - }); + defaultValue: 0, + }) Fog.belongsTo(models.User, { foreignKey: { name: 'userId', - field: 'user_id' + field: 'user_id', }, as: 'user', defaultValue: 0, - onDelete: 'cascade' - }); + onDelete: 'cascade', + }) Fog.hasOne(models.FogAccessToken, { foreignKey: 'iofog_uuid', - as: 'accessToken' - }); + as: 'accessToken', + }) Fog.hasMany(models.Microservice, { foreignKey: 'iofog_uuid', - as: 'microservice' - }); - - }; + as: 'microservice', + }) + } - return Fog; -}; \ No newline at end of file + return Fog +} diff --git a/src/sequelize/models/fogaccesstoken.js b/src/sequelize/models/fogaccesstoken.js index 9e9245fa7..b8f2df204 100644 --- a/src/sequelize/models/fogaccesstoken.js +++ b/src/sequelize/models/fogaccesstoken.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const FogAccessToken = sequelize.define('FogAccessToken', { id: { @@ -6,39 +6,38 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, expirationTime: { type: DataTypes.BIGINT, - field: 'expiration_time' + field: 'expiration_time', }, token: { type: DataTypes.TEXT, - field: 'token' - } + field: 'token', + }, }, { timestamps: false, - underscored: true - }); - FogAccessToken.associate = function (models) { - + underscored: true, + }) + FogAccessToken.associate = function(models) { FogAccessToken.belongsTo(models.User, { foreignKey: { name: 'userId', - field: 'user_id' + field: 'user_id', }, as: 'user', - onDelete: 'cascade' - }); + onDelete: 'cascade', + }) FogAccessToken.belongsTo(models.Fog, { foreignKey: { name: 'iofogUuid', - field: 'iofog_uuid' + field: 'iofog_uuid', }, as: 'iofog', - onDelete: 'cascade' - }); - }; - return FogAccessToken; -}; \ No newline at end of file + onDelete: 'cascade', + }) + } + return FogAccessToken +} diff --git a/src/sequelize/models/fogprovisionkey.js b/src/sequelize/models/fogprovisionkey.js index 2a34bab5e..7b89b00e2 100644 --- a/src/sequelize/models/fogprovisionkey.js +++ b/src/sequelize/models/fogprovisionkey.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const FogProvisionKey = sequelize.define('FogProvisionKey', { id: { @@ -6,30 +6,30 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, provisionKey: { + /* eslint-disable new-cap */ type: DataTypes.STRING(100), - field: 'provisioning_string' + field: 'provisioning_string', }, expirationTime: { type: DataTypes.BIGINT, - field: 'expiration_time' - } + field: 'expiration_time', + }, }, { timestamps: false, - underscored: true - }); - FogProvisionKey.associate = function (models) { - + underscored: true, + }) + FogProvisionKey.associate = function(models) { FogProvisionKey.belongsTo(models.Fog, { foreignKey: { name: 'iofogUuid', - field: 'iofog_uuid' + field: 'iofog_uuid', }, as: 'iofog', - onDelete: 'cascade' - }); - }; - return FogProvisionKey; -}; \ No newline at end of file + onDelete: 'cascade', + }) + } + return FogProvisionKey +} diff --git a/src/sequelize/models/fogtype.js b/src/sequelize/models/fogtype.js index 742eb18fd..a346a956a 100644 --- a/src/sequelize/models/fogtype.js +++ b/src/sequelize/models/fogtype.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const FogType = sequelize.define('FogType', { id: { @@ -6,48 +6,48 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, name: { type: DataTypes.TEXT, - field: 'name' + field: 'name', }, image: { type: DataTypes.TEXT, - field: 'image' + field: 'image', }, description: { type: DataTypes.TEXT, - field: 'description' - } + field: 'description', + }, }, { timestamps: false, - underscored: true - }); - FogType.associate = function (models) { + underscored: true, + }) + FogType.associate = function(models) { FogType.belongsTo(models.CatalogItem, { foreignKey: { name: 'networkCatalogItemId', - field: 'network_catalog_item_id' + field: 'network_catalog_item_id', }, - as: 'networkCatalogItem' - }); + as: 'networkCatalogItem', + }) FogType.belongsTo(models.CatalogItem, { foreignKey: { name: 'halCatalogItemId', - field: 'hal_catalog_item_id' + field: 'hal_catalog_item_id', }, - as: 'halCatalogItem' - }); + as: 'halCatalogItem', + }) FogType.belongsTo(models.CatalogItem, { foreignKey: { name: 'bluetoothCatalogItemId', - field: 'bluetooth_catalog_item_id' + field: 'bluetooth_catalog_item_id', }, - as: 'bluetoothCatalogItem' - }); - }; - return FogType; -}; \ No newline at end of file + as: 'bluetoothCatalogItem', + }) + } + return FogType +} diff --git a/src/sequelize/models/fogversioncommand.js b/src/sequelize/models/fogversioncommand.js index 3d8a1616b..ec9f2f6fa 100644 --- a/src/sequelize/models/fogversioncommand.js +++ b/src/sequelize/models/fogversioncommand.js @@ -1,30 +1,30 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const FogVersionCommand = sequelize.define('FogVersionCommand', { id: { type: DataTypes.INTEGER, primaryKey: true, autoIncrement: true, - field: 'id' + field: 'id', }, versionCommand: { + /* eslint-disable new-cap */ type: DataTypes.STRING(100), - field: 'version_command' - } + field: 'version_command', + }, }, { timestamps: false, - underscored: true - }); - FogVersionCommand.associate = function (models) { - + underscored: true, + }) + FogVersionCommand.associate = function(models) { FogVersionCommand.belongsTo(models.Fog, { foreignKey: { name: 'iofogUuid', - field: 'iofog_uuid' + field: 'iofog_uuid', }, as: 'iofog', - onDelete: 'cascade' - }); - }; - return FogVersionCommand; -}; \ No newline at end of file + onDelete: 'cascade', + }) + } + return FogVersionCommand +} diff --git a/src/sequelize/models/hwinfo.js b/src/sequelize/models/hwinfo.js index fdd31c969..b22af3598 100644 --- a/src/sequelize/models/hwinfo.js +++ b/src/sequelize/models/hwinfo.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const HWInfo = sequelize.define('HWInfo', { id: { @@ -6,28 +6,27 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, info: { type: DataTypes.TEXT, - defaultValue: " ", - field: 'info' - } + defaultValue: ' ', + field: 'info', + }, }, { // add the timestamp attributes (updatedAt, createdAt) timestamps: true, - underscored: true - }); - HWInfo.associate = function (models) { - + underscored: true, + }) + HWInfo.associate = function(models) { HWInfo.belongsTo(models.Fog, { foreignKey: { name: 'iofogUuid', - field: 'iofog_uuid' + field: 'iofog_uuid', }, as: 'iofog', - onDelete: 'cascade' - }); - }; - return HWInfo; -}; \ No newline at end of file + onDelete: 'cascade', + }) + } + return HWInfo +} diff --git a/src/sequelize/models/index.js b/src/sequelize/models/index.js index 57540ed14..6f62c8a79 100644 --- a/src/sequelize/models/index.js +++ b/src/sequelize/models/index.js @@ -1,23 +1,23 @@ -'use strict'; +'use strict' -const fs = require('fs'); -const path = require('path'); -const Sequelize = require('sequelize'); -const Umzug = require('umzug'); +const fs = require('fs') +const path = require('path') +const Sequelize = require('sequelize') +const Umzug = require('umzug') -const basename = path.basename(__filename); -const env = process.env.NODE_ENV || 'production'; -const config = require(__dirname + '/../config/config.json')[env]; -const db = {}; +const basename = path.basename(__filename) +const env = process.env.NODE_ENV || 'production' +const config = require(__dirname + '/../config/config.json')[env] +const db = {} -let sequelize; +let sequelize -config.storage = path.resolve(__dirname, '../' + config.storage); +config.storage = path.resolve(__dirname, '../' + config.storage) if (config.use_env_variable) { - sequelize = new Sequelize(process.env[config.use_env_variable], config); + sequelize = new Sequelize(process.env[config.use_env_variable], config) } else { - sequelize = new Sequelize(config.database, config.username, config.password, config); + sequelize = new Sequelize(config.database, config.username, config.password, config) } const createUmzug = (path) => { @@ -33,31 +33,31 @@ const createUmzug = (path) => { Sequelize, ], path, - pattern: /\.js$/ + pattern: /\.js$/, }, - }); + }) } fs - .readdirSync(__dirname) - .filter(file => { - return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'); - }) - .forEach(file => { - const model = sequelize.import(path.join(__dirname, file)); - db[model.name] = model; - }); - -Object.keys(db).forEach(modelName => { + .readdirSync(__dirname) + .filter((file) => { + return (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js') + }) + .forEach((file) => { + const model = sequelize.import(path.join(__dirname, file)) + db[model.name] = model + }) + +Object.keys(db).forEach((modelName) => { if (db[modelName].associate) { - db[modelName].associate(db); + db[modelName].associate(db) } -}); +}) -db.sequelize = sequelize; -db.Sequelize = Sequelize; +db.sequelize = sequelize +db.Sequelize = Sequelize -db.migrate = () => createUmzug(path.resolve(__dirname, '../migrations')).up(); -db.seed = () => createUmzug(path.resolve(__dirname, '../seeders')).up(); +db.migrate = () => createUmzug(path.resolve(__dirname, '../migrations')).up() +db.seed = () => createUmzug(path.resolve(__dirname, '../seeders')).up() -module.exports = db; +module.exports = db diff --git a/src/sequelize/models/microservice.js b/src/sequelize/models/microservice.js index a96c22d32..12c92ce78 100644 --- a/src/sequelize/models/microservice.js +++ b/src/sequelize/models/microservice.js @@ -1,128 +1,127 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const Microservice = sequelize.define('Microservice', { uuid: { type: DataTypes.TEXT, primaryKey: true, allowNull: false, - field: 'uuid' + field: 'uuid', }, config: { type: DataTypes.TEXT, field: 'config', - defaultValue: "" + defaultValue: '', }, name: { type: DataTypes.TEXT, field: 'name', - defaultValue: "New Microservice" + defaultValue: 'New Microservice', }, configLastUpdated: { type: DataTypes.BIGINT, - field: 'config_last_updated' + field: 'config_last_updated', }, isNetwork: { type: DataTypes.BOOLEAN, field: 'is_network', - defaultValue: false + defaultValue: false, }, rebuild: { type: DataTypes.BOOLEAN, field: 'rebuild', - defaultValue: false + defaultValue: false, }, rootHostAccess: { type: DataTypes.BOOLEAN, field: 'root_host_access', - defaultValue: false + defaultValue: false, }, logSize: { type: DataTypes.BIGINT, field: 'log_size', - defaultValue: 0 + defaultValue: 0, }, imageSnapshot: { type: DataTypes.TEXT, field: 'image_snapshot', - defaultValue: "" + defaultValue: '', }, delete: { type: DataTypes.BOOLEAN, field: 'delete', - defaultValue: false + defaultValue: false, }, deleteWithCleanup: { type: DataTypes.BOOLEAN, field: 'delete_with_cleanup', - defaultValue: false - } + defaultValue: false, + }, }, { timestamps: true, - underscored: true - }); - Microservice.associate = function (models) { - + underscored: true, + }) + Microservice.associate = function(models) { Microservice.belongsTo(models.CatalogItem, { foreignKey: { name: 'catalogItemId', - field: 'catalog_item_id' + field: 'catalog_item_id', }, as: 'catalogItem', - onDelete: 'cascade' + onDelete: 'cascade', - }); + }) Microservice.belongsTo(models.Fog, { foreignKey: { name: 'iofogUuid', - field: 'iofog_uuid' + field: 'iofog_uuid', }, as: 'iofog', - onDelete: 'set null' - }); + onDelete: 'set null', + }) Microservice.belongsTo(models.Flow, { foreignKey: { name: 'flowId', - field: 'flow_id' + field: 'flow_id', }, as: 'flow', - onDelete: 'cascade' - }); + onDelete: 'cascade', + }) Microservice.belongsTo(models.User, { foreignKey: { name: 'userId', - field: 'user_id' + field: 'user_id', }, as: 'user', - onDelete: 'cascade' - }); + onDelete: 'cascade', + }) Microservice.hasMany(models.MicroservicePort, { foreignKey: 'microservice_uuid', - as: 'ports' - }); + as: 'ports', + }) Microservice.hasMany(models.VolumeMapping, { foreignKey: 'microservice_uuid', - as: 'volumeMappings' - }); + as: 'volumeMappings', + }) Microservice.hasOne(models.StraceDiagnostics, { foreignKey: 'microservice_uuid', - as: 'strace' - }); + as: 'strace', + }) Microservice.hasMany(models.Routing, { foreignKey: 'source_microservice_uuid', - as: 'routes' - }); + as: 'routes', + }) Microservice.hasOne(models.MicroserviceStatus, { foreignKey: 'microservice_uuid', - as: 'microserviceStatus' - }); - }; - return Microservice; -}; \ No newline at end of file + as: 'microserviceStatus', + }) + } + return Microservice +} diff --git a/src/sequelize/models/microserviceport.js b/src/sequelize/models/microserviceport.js index cca3aeedc..31f8403d7 100644 --- a/src/sequelize/models/microserviceport.js +++ b/src/sequelize/models/microserviceport.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const MicroservicePort = sequelize.define('MicroservicePort', { id: { @@ -6,43 +6,42 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, portInternal: { type: DataTypes.INTEGER, - field: 'port_internal' + field: 'port_internal', }, portExternal: { type: DataTypes.INTEGER, - field: 'port_external' + field: 'port_external', }, isPublic: { type: DataTypes.BOOLEAN, - field: 'is_public' - } + field: 'is_public', + }, }, { timestamps: true, - underscored: true - }); - MicroservicePort.associate = function (models) { - + underscored: true, + }) + MicroservicePort.associate = function(models) { MicroservicePort.belongsTo(models.Microservice, { foreignKey: { name: 'microserviceUuid', - field: 'microservice_uuid' + field: 'microservice_uuid', }, as: 'microservice', - onDelete: 'cascade' - }); + onDelete: 'cascade', + }) MicroservicePort.belongsTo(models.User, { foreignKey: { name: 'userId', - field: 'user_id' + field: 'user_id', }, as: 'user', - onDelete: 'cascade' - }); - }; - return MicroservicePort; -}; \ No newline at end of file + onDelete: 'cascade', + }) + } + return MicroservicePort +} diff --git a/src/sequelize/models/microservicepublicmode.js b/src/sequelize/models/microservicepublicmode.js index c025fe31a..685623bde 100644 --- a/src/sequelize/models/microservicepublicmode.js +++ b/src/sequelize/models/microservicepublicmode.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const MicroservicePublicMode = sequelize.define('MicroservicePublicMode', { id: { @@ -6,57 +6,57 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' - } + field: 'id', + }, }, { timestamps: false, - underscored: true - }); + underscored: true, + }) MicroservicePublicMode.associate = function(models) { MicroservicePublicMode.belongsTo(models.Microservice, { foreignKey: { name: 'microserviceUuid', - field: 'microservice_uuid' + field: 'microservice_uuid', }, as: 'microservice', - onDelete: 'cascade' - }); + onDelete: 'cascade', + }) MicroservicePublicMode.belongsTo(models.Microservice, { foreignKey: { name: 'networkMicroserviceUuid', - field: 'network_microservice_uuid' + field: 'network_microservice_uuid', }, as: 'networkMicroservice', - onDelete: 'set null' - }); + onDelete: 'set null', + }) MicroservicePublicMode.belongsTo(models.Fog, { foreignKey: { name: 'iofogUuid', - field: 'iofog_uuid' + field: 'iofog_uuid', }, as: 'iofog', - onDelete: 'set null' - }); + onDelete: 'set null', + }) MicroservicePublicMode.belongsTo(models.MicroservicePort, { foreignKey: { name: 'microservicePortId', - field: 'microservice_port_id' + field: 'microservice_port_id', }, as: 'microservicePort', - onDelete: 'set null' - }); + onDelete: 'set null', + }) MicroservicePublicMode.belongsTo(models.ConnectorPort, { foreignKey: { name: 'connectorPortId', - field: 'connector_port_id' + field: 'connector_port_id', }, as: 'connectorPort', - onDelete: 'set null' - }); - }; - return MicroservicePublicMode; -}; \ No newline at end of file + onDelete: 'set null', + }) + } + return MicroservicePublicMode +} diff --git a/src/sequelize/models/microservicestatus.js b/src/sequelize/models/microservicestatus.js index c886603a3..4e672fb06 100644 --- a/src/sequelize/models/microservicestatus.js +++ b/src/sequelize/models/microservicestatus.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const MicroserviceStatus = sequelize.define('MicroserviceStatus', { id: { @@ -6,52 +6,52 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, status: { type: DataTypes.TEXT, defaultValue: 'NOT_RUNNING', - field: 'status' + field: 'status', }, operatingDuration: { type: DataTypes.BIGINT, defaultValue: 0, - field: 'operating_duration' + field: 'operating_duration', }, startTime: { type: DataTypes.BIGINT, defaultValue: 0, - field: 'start_time' + field: 'start_time', }, cpuUsage: { type: DataTypes.FLOAT, defaultValue: 0.000, - field: 'cpu_usage' + field: 'cpu_usage', }, memoryUsage: { type: DataTypes.BIGINT, defaultValue: 0, - field: 'memory_usage' + field: 'memory_usage', }, containerId: { type: DataTypes.TEXT, defaultValue: '', - field: 'container_id' - } + field: 'container_id', + }, }, { // add the timestamp attributes (updatedAt, createdAt) timestamps: true, - underscored: true - }); - MicroserviceStatus.associate = function (models) { + underscored: true, + }) + MicroserviceStatus.associate = function(models) { MicroserviceStatus.belongsTo(models.Microservice, { foreignKey: { name: 'microserviceUuid', - field: 'microservice_uuid' + field: 'microservice_uuid', }, as: 'microservice', - onDelete: 'cascade' - }); - }; - return MicroserviceStatus; -}; \ No newline at end of file + onDelete: 'cascade', + }) + } + return MicroserviceStatus +} diff --git a/src/sequelize/models/registry.js b/src/sequelize/models/registry.js index 7be5803dc..84d79db0a 100644 --- a/src/sequelize/models/registry.js +++ b/src/sequelize/models/registry.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const Registry = sequelize.define('Registry', { id: { @@ -6,53 +6,52 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, url: { type: DataTypes.TEXT, - field: 'url' + field: 'url', }, isPublic: { type: DataTypes.BOOLEAN, - field: 'is_public' + field: 'is_public', }, isSecure: { type: DataTypes.BOOLEAN, - field: 'secure' + field: 'secure', }, certificate: { type: DataTypes.TEXT, - field: 'certificate' + field: 'certificate', }, requiresCert: { type: DataTypes.BOOLEAN, - field: 'requires_cert' + field: 'requires_cert', }, username: { type: DataTypes.TEXT, - field: 'user_name' + field: 'user_name', }, password: { type: DataTypes.TEXT, - field: 'password' + field: 'password', }, userEmail: { type: DataTypes.TEXT, - field: 'user_email' - } + field: 'user_email', + }, }, { timestamps: false, - underscored: true - }); - Registry.associate = function (models) { - + underscored: true, + }) + Registry.associate = function(models) { Registry.belongsTo(models.User, { foreignKey: { name: 'userId', - field: 'user_id' + field: 'user_id', }, as: 'user', - }); - }; - return Registry; -}; \ No newline at end of file + }) + } + return Registry +} diff --git a/src/sequelize/models/routing.js b/src/sequelize/models/routing.js index 263a0eccd..1b515dbe1 100644 --- a/src/sequelize/models/routing.js +++ b/src/sequelize/models/routing.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const Routing = sequelize.define('Routing', { id: { @@ -6,81 +6,80 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, isNetworkConnection: { type: DataTypes.BOOLEAN, defaultValue: false, - field: 'is_network_connection' - } + field: 'is_network_connection', + }, }, { timestamps: false, - underscored: true - }); + underscored: true, + }) Routing.associate = function(models) { - Routing.belongsTo(models.Microservice, { foreignKey: { name: 'sourceMicroserviceUuid', - field: 'source_microservice_uuid' + field: 'source_microservice_uuid', }, as: 'sourceMicroservice', - onDelete: 'cascade' - }); + onDelete: 'cascade', + }) Routing.belongsTo(models.Microservice, { foreignKey: { name: 'destMicroserviceUuid', - field: 'dest_microservice_uuid' + field: 'dest_microservice_uuid', }, as: 'destMicroservice', - onDelete: 'cascade' - }); + onDelete: 'cascade', + }) Routing.belongsTo(models.Microservice, { foreignKey: { name: 'sourceNetworkMicroserviceUuid', - field: 'source_network_microservice_uuid' + field: 'source_network_microservice_uuid', }, as: 'sourceNetworkMicroservice', - onDelete: 'set null' - }); + onDelete: 'set null', + }) Routing.belongsTo(models.Microservice, { foreignKey: { name: 'destNetworkMicroserviceUuid', - field: 'dest_network_microservice_uuid' + field: 'dest_network_microservice_uuid', }, as: 'destNetworkMicroservice', - onDelete: 'set null' - }); + onDelete: 'set null', + }) Routing.belongsTo(models.Fog, { foreignKey: { name: 'sourceIofogUuid', - field: 'source_iofog_uuid' + field: 'source_iofog_uuid', }, as: 'sourceIofog', - onDelete: 'set null' - }); + onDelete: 'set null', + }) Routing.belongsTo(models.Fog, { foreignKey: { name: 'destIofogUuid', - field: 'dest_iofog_uuid' + field: 'dest_iofog_uuid', }, as: 'destIofog', - onDelete: 'set null' - }); + onDelete: 'set null', + }) Routing.belongsTo(models.ConnectorPort, { foreignKey: { name: 'connectorPortId', - field: 'connector_port_id' + field: 'connector_port_id', }, as: 'connectorPort', - onDelete: 'set null' - }); - }; - return Routing; -}; \ No newline at end of file + onDelete: 'set null', + }) + } + return Routing +} diff --git a/src/sequelize/models/stracediagnostics.js b/src/sequelize/models/stracediagnostics.js index c529dba38..b766257a7 100644 --- a/src/sequelize/models/stracediagnostics.js +++ b/src/sequelize/models/stracediagnostics.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const StraceDiagnostics = sequelize.define('StraceDiagnostics', { id: { @@ -6,32 +6,31 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, straceRun: { type: DataTypes.BOOLEAN, - field: 'strace_run' + field: 'strace_run', }, buffer: { type: DataTypes.TEXT, field: 'buffer', defaultValue: '', - } + }, }, { timestamps: false, - underscored: true - }); - StraceDiagnostics.associate = function (models) { - + underscored: true, + }) + StraceDiagnostics.associate = function(models) { StraceDiagnostics.belongsTo(models.Microservice, { foreignKey: { name: 'microserviceUuid', - field: 'microservice_uuid' + field: 'microservice_uuid', }, as: 'microservice', - onDelete: 'cascade' + onDelete: 'cascade', - }); - }; - return StraceDiagnostics; -}; \ No newline at end of file + }) + } + return StraceDiagnostics +} diff --git a/src/sequelize/models/trackingevent.js b/src/sequelize/models/trackingevent.js index 0973e8e42..606645cac 100644 --- a/src/sequelize/models/trackingevent.js +++ b/src/sequelize/models/trackingevent.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const TrackingEvent = sequelize.define('TrackingEvent', { id: { @@ -6,35 +6,35 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, uuid: { type: DataTypes.TEXT, allowNull: false, - field: 'uuid' + field: 'uuid', }, sourceType: { type: DataTypes.TEXT, - field: 'source_type' + field: 'source_type', }, timestamp: { type: DataTypes.BIGINT, - field: 'timestamp' + field: 'timestamp', }, type: { type: DataTypes.TEXT, - field: 'type' + field: 'type', }, data: { type: DataTypes.TEXT, - field: 'data' - } + field: 'data', + }, }, { timestamps: false, - underscored: true - }); + underscored: true, + }) TrackingEvent.associate = function(models) { // associations can be defined here - }; - return TrackingEvent; -}; \ No newline at end of file + } + return TrackingEvent +} diff --git a/src/sequelize/models/tunnel.js b/src/sequelize/models/tunnel.js index b7c511175..f441af3ca 100644 --- a/src/sequelize/models/tunnel.js +++ b/src/sequelize/models/tunnel.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const Tunnel = sequelize.define('Tunnel', { id: { @@ -6,52 +6,51 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, username: { type: DataTypes.TEXT, - field: 'username' + field: 'username', }, password: { type: DataTypes.TEXT, - field: 'password' + field: 'password', }, host: { type: DataTypes.TEXT, - field: 'host' + field: 'host', }, rport: { type: DataTypes.INTEGER, - field: 'remote_port' + field: 'remote_port', }, lport: { type: DataTypes.INTEGER, defaultValue: 22, - field: 'local_port' + field: 'local_port', }, rsakey: { type: DataTypes.TEXT, - field: 'rsa_key' + field: 'rsa_key', }, closed: { type: DataTypes.BOOLEAN, defaultValue: false, - field: 'closed' - } + field: 'closed', + }, }, { timestamps: false, - underscored: true - }); - Tunnel.associate = function (models) { - + underscored: true, + }) + Tunnel.associate = function(models) { Tunnel.belongsTo(models.Fog, { foreignKey: { name: 'iofogUuid', - field: 'iofog_uuid' + field: 'iofog_uuid', }, as: 'iofog', - onDelete: 'cascade' - }); - }; - return Tunnel; -}; \ No newline at end of file + onDelete: 'cascade', + }) + } + return Tunnel +} diff --git a/src/sequelize/models/usbinfo.js b/src/sequelize/models/usbinfo.js index 1a184b28b..af4991ae7 100644 --- a/src/sequelize/models/usbinfo.js +++ b/src/sequelize/models/usbinfo.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const USBInfo = sequelize.define('USBInfo', { id: { @@ -6,28 +6,27 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'id' + field: 'id', }, info: { type: DataTypes.TEXT, - defaultValue: " ", - field: 'info' - } + defaultValue: ' ', + field: 'info', + }, }, { // add the timestamp attributes (updatedAt, createdAt) timestamps: true, - underscored: true - }); - USBInfo.associate = function (models) { - + underscored: true, + }) + USBInfo.associate = function(models) { USBInfo.belongsTo(models.Fog, { foreignKey: { name: 'iofogUuid', - field: 'iofog_uuid' + field: 'iofog_uuid', }, as: 'iofog', - onDelete: 'cascade' - }); - }; - return USBInfo; -}; \ No newline at end of file + onDelete: 'cascade', + }) + } + return USBInfo +} diff --git a/src/sequelize/models/user.js b/src/sequelize/models/user.js index f18b1fa83..e728d5fb7 100644 --- a/src/sequelize/models/user.js +++ b/src/sequelize/models/user.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const User = sequelize.define('User', { id: { @@ -6,71 +6,74 @@ module.exports = (sequelize, DataTypes) => { autoIncrement: true, primaryKey: true, type: DataTypes.INTEGER, - field: 'id' + field: 'id', }, firstName: { + /* eslint-disable new-cap */ type: DataTypes.STRING(100), field: 'first_name', - defaultValue: "" + defaultValue: '', }, lastName: { + /* eslint-disable new-cap */ type: DataTypes.STRING(100), field: 'last_name', - defaultValue: "" + defaultValue: '', }, email: { + /* eslint-disable new-cap */ type: DataTypes.STRING(100), field: 'email', - defaultValue: "" + defaultValue: '', }, password: { + /* eslint-disable new-cap */ type: DataTypes.STRING(100), - field: 'password' + field: 'password', }, tempPassword: { + /* eslint-disable new-cap */ type: DataTypes.STRING(100), - field: 'temp_password' + field: 'temp_password', }, emailActivated: { type: DataTypes.BOOLEAN, field: 'email_activated', - defaultValue: false - } + defaultValue: false, + }, }, { timestamps: false, - underscored: true - }); - User.associate = function (models) { - + underscored: true, + }) + User.associate = function(models) { User.hasOne(models.AccessToken, { foreignKey: 'user_id', - as: 'accessToken' - }); + as: 'accessToken', + }) User.hasMany(models.Flow, { foreignKey: { name: 'userId', - field: 'user_id' + field: 'user_id', }, - as: 'flow' - }); + as: 'flow', + }) User.hasMany(models.Fog, { foreignKey: { name: 'userId', - field: 'user_id' + field: 'user_id', }, - as: 'fog' - }); + as: 'fog', + }) User.hasMany(models.Microservice, { foreignKey: { name: 'userId', - field: 'user_id' + field: 'user_id', }, - as: 'microservice' - }); - - }; - return User; -}; \ No newline at end of file + as: 'microservice', + }) + } + return User +} diff --git a/src/sequelize/models/volumemapping.js b/src/sequelize/models/volumemapping.js index 6298c9a80..df0cfff92 100644 --- a/src/sequelize/models/volumemapping.js +++ b/src/sequelize/models/volumemapping.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = (sequelize, DataTypes) => { const VolumeMapping = sequelize.define('VolumeMapping', { id: { @@ -6,33 +6,33 @@ module.exports = (sequelize, DataTypes) => { primaryKey: true, autoIncrement: true, allowNull: false, - field: 'uuid' + field: 'uuid', }, hostDestination: { type: DataTypes.TEXT, - field: 'host_destination' + field: 'host_destination', }, containerDestination: { type: DataTypes.TEXT, - field: 'container_destination' + field: 'container_destination', }, accessMode: { type: DataTypes.TEXT, - field: 'access_mode' - } + field: 'access_mode', + }, }, { timestamps: false, - underscored: true - }); - VolumeMapping.associate = function (models) { + underscored: true, + }) + VolumeMapping.associate = function(models) { VolumeMapping.belongsTo(models.Microservice, { foreignKey: { name: 'microserviceUuid', - field: 'microservice_uuid' + field: 'microservice_uuid', }, as: 'microservice', - onDelete: 'cascade' - }); - }; - return VolumeMapping; -}; \ No newline at end of file + onDelete: 'cascade', + }) + } + return VolumeMapping +} diff --git a/src/sequelize/seeders/20180928110125-insert-registry.js b/src/sequelize/seeders/20180928110125-insert-registry.js index 92a04a230..b2900a871 100644 --- a/src/sequelize/seeders/20180928110125-insert-registry.js +++ b/src/sequelize/seeders/20180928110125-insert-registry.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { @@ -13,7 +13,7 @@ module.exports = { user_name: '', password: '', user_email: '', - user_id: null + user_id: null, }, { ID: 2, @@ -25,12 +25,12 @@ module.exports = { user_name: '', password: '', user_email: '', - user_id: null - } - ]); + user_id: null, + }, + ]) }, down: (queryInterface, Sequelize) => { - return queryInterface.bulkDelete('Registries', null, {}); - } -}; \ No newline at end of file + return queryInterface.bulkDelete('Registries', null, {}) + }, +} diff --git a/src/sequelize/seeders/20180928111532-insert-catalog-item.js b/src/sequelize/seeders/20180928111532-insert-catalog-item.js index 75f21bd60..3e50b4102 100644 --- a/src/sequelize/seeders/20180928111532-insert-catalog-item.js +++ b/src/sequelize/seeders/20180928111532-insert-catalog-item.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { @@ -15,7 +15,7 @@ module.exports = { config_example: null, is_public: 0, registry_id: 1, - user_id: null + user_id: null, }, { ID: 2, @@ -29,7 +29,7 @@ module.exports = { config_example: null, is_public: 0, registry_id: 1, - user_id: null + user_id: null, }, { ID: 3, @@ -43,7 +43,7 @@ module.exports = { config_example: null, is_public: 0, registry_id: 1, - user_id: null + user_id: null, }, { ID: 4, @@ -57,7 +57,7 @@ module.exports = { config_example: null, is_public: 1, registry_id: 1, - user_id: null + user_id: null, }, { ID: 5, @@ -71,7 +71,7 @@ module.exports = { config_example: null, is_public: 1, registry_id: 1, - user_id: null + user_id: null, }, { ID: 6, @@ -85,7 +85,7 @@ module.exports = { config_example: null, is_public: 1, registry_id: 1, - user_id: null + user_id: null, }, { ID: 7, @@ -99,7 +99,7 @@ module.exports = { config_example: null, is_public: 1, registry_id: 1, - user_id: null + user_id: null, }, { ID: 8, @@ -113,7 +113,7 @@ module.exports = { config_example: null, is_public: 1, registry_id: 1, - user_id: null + user_id: null, }, { ID: 9, @@ -127,7 +127,7 @@ module.exports = { config_example: null, is_public: 1, registry_id: 1, - user_id: null + user_id: null, }, { ID: 10, @@ -141,7 +141,7 @@ module.exports = { config_example: null, is_public: 1, registry_id: 1, - user_id: null + user_id: null, }, { ID: 11, @@ -155,7 +155,7 @@ module.exports = { config_example: null, is_public: 1, registry_id: 1, - user_id: null + user_id: null, }, { ID: 12, @@ -169,15 +169,15 @@ module.exports = { config_example: null, is_public: 1, registry_id: 1, - user_id: null - } - ]); + user_id: null, + }, + ]) }, down: (queryInterface, Sequelize) => { - return queryInterface.bulkDelete('CatalogItems', null, {}); - } -}; + return queryInterface.bulkDelete('CatalogItems', null, {}) + }, +} diff --git a/src/sequelize/seeders/20180928112152-insert-iofog-type.js b/src/sequelize/seeders/20180928112152-insert-iofog-type.js index 5a375a6b5..0a06e80db 100644 --- a/src/sequelize/seeders/20180928112152-insert-iofog-type.js +++ b/src/sequelize/seeders/20180928112152-insert-iofog-type.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { @@ -10,39 +10,41 @@ module.exports = { description: 'Unspecified device. Fog Type will be selected on provision', network_catalog_item_id: 1, hal_catalog_item_id: 3, - bluetooth_catalog_item_id: 2 + bluetooth_catalog_item_id: 2, }, { ID: 1, name: 'Standard Linux (x86)', image: 'iointegrator1.png', - description: 'A standard Linux server of at least moderate processing power and capacity. Compatible with common Linux types such as Ubuntu, Red Hat, and CentOS.', + description: 'A standard Linux server of at least moderate processing power and capacity. ' + + 'Compatible with common Linux types such as Ubuntu, Red Hat, and CentOS.', network_catalog_item_id: 1, hal_catalog_item_id: 3, - bluetooth_catalog_item_id: 2 + bluetooth_catalog_item_id: 2, }, { ID: 2, name: 'ARM Linux', image: 'iointegrator2.png', - description: 'A version of ioFog meant to run on Linux systems with ARM processors. Microservices for this ioFog type will be tailored to ARM systems.', + description: 'A version of ioFog meant to run on Linux systems with ARM processors. ' + + 'Microservices for this ioFog type will be tailored to ARM systems.', network_catalog_item_id: 1, hal_catalog_item_id: 3, - bluetooth_catalog_item_id: 2 - } + bluetooth_catalog_item_id: 2, + }, ]).then(() => { return queryInterface.bulkUpdate('Fogs', - { - fog_type_id: 0 - }, - { - fog_type_id: null - } + { + fog_type_id: 0, + }, + { + fog_type_id: null, + }, ) - }); + }) }, down: (queryInterface, Sequelize) => { return queryInterface.bulkDelete('FogTypes', null, {}) - } -}; \ No newline at end of file + }, +} diff --git a/src/sequelize/seeders/20180928121334-insert-catalog-item-image.js b/src/sequelize/seeders/20180928121334-insert-catalog-item-image.js index 972fb97b9..b75c4a7ea 100644 --- a/src/sequelize/seeders/20180928121334-insert-catalog-item-image.js +++ b/src/sequelize/seeders/20180928121334-insert-catalog-item-image.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { @@ -7,151 +7,151 @@ module.exports = { ID: 1, catalog_item_id: 1, fog_type_id: 1, - container_image: 'iofog/core-networking' + container_image: 'iofog/core-networking', }, { ID: 2, catalog_item_id: 1, fog_type_id: 2, - container_image: 'iofog/core-networking-arm' + container_image: 'iofog/core-networking-arm', }, { ID: 3, catalog_item_id: 2, fog_type_id: 1, - container_image: 'iofog/restblue' + container_image: 'iofog/restblue', }, { ID: 4, catalog_item_id: 2, fog_type_id: 2, - container_image: 'iofog/restblue-arm' + container_image: 'iofog/restblue-arm', }, { ID: 5, catalog_item_id: 3, fog_type_id: 1, - container_image: 'iofog/hal' + container_image: 'iofog/hal', }, { ID: 6, catalog_item_id: 3, fog_type_id: 2, - container_image: 'iofog/hal-arm' + container_image: 'iofog/hal-arm', }, { ID: 7, catalog_item_id: 4, fog_type_id: 1, - container_image: 'iofog/diagnostics' + container_image: 'iofog/diagnostics', }, { ID: 8, catalog_item_id: 4, fog_type_id: 2, - container_image: 'iofog/diagnostics-arm' + container_image: 'iofog/diagnostics-arm', }, { ID: 9, catalog_item_id: 5, fog_type_id: 1, - container_image: 'iofog/hello-web' + container_image: 'iofog/hello-web', }, { ID: 10, catalog_item_id: 5, fog_type_id: 2, - container_image: 'iofog/hello-web-arm' + container_image: 'iofog/hello-web-arm', }, { ID: 11, catalog_item_id: 6, fog_type_id: 1, - container_image: 'iofog/open-weather-map' + container_image: 'iofog/open-weather-map', }, { ID: 12, catalog_item_id: 6, fog_type_id: 2, - container_image: 'iofog/open-weather-map-arm' + container_image: 'iofog/open-weather-map-arm', }, { ID: 13, catalog_item_id: 7, fog_type_id: 1, - container_image: 'iofog/json-rest-api' + container_image: 'iofog/json-rest-api', }, { ID: 14, catalog_item_id: 7, fog_type_id: 2, - container_image: 'iofog/json-rest-api-arm' + container_image: 'iofog/json-rest-api-arm', }, { ID: 15, catalog_item_id: 8, fog_type_id: 1, - container_image: 'iofog/temperature-conversion' + container_image: 'iofog/temperature-conversion', }, { ID: 16, catalog_item_id: 8, fog_type_id: 2, - container_image: 'iofog/temperature-conversion-arm' + container_image: 'iofog/temperature-conversion-arm', }, { ID: 17, catalog_item_id: 9, fog_type_id: 1, - container_image: 'iofog/json-subselect' + container_image: 'iofog/json-subselect', }, { ID: 18, catalog_item_id: 9, fog_type_id: 2, - container_image: 'iofog/json-subselect-arm' + container_image: 'iofog/json-subselect-arm', }, { ID: 19, catalog_item_id: 10, fog_type_id: 1, - container_image: 'iofog/humidity-sensor-simulator' + container_image: 'iofog/humidity-sensor-simulator', }, { ID: 20, catalog_item_id: 10, fog_type_id: 2, - container_image: 'iofog/humidity-sensor-simulator-arm' + container_image: 'iofog/humidity-sensor-simulator-arm', }, { ID: 21, catalog_item_id: 11, fog_type_id: 1, - container_image: 'iofog/seismic-sensor-simulator' + container_image: 'iofog/seismic-sensor-simulator', }, { ID: 22, catalog_item_id: 11, fog_type_id: 2, - container_image: 'iofog/seismic-sensor-simulator-arm' + container_image: 'iofog/seismic-sensor-simulator-arm', }, { ID: 23, catalog_item_id: 12, fog_type_id: 1, - container_image: 'iofog/temperature-sensor-simulator' + container_image: 'iofog/temperature-sensor-simulator', }, { ID: 24, catalog_item_id: 12, fog_type_id: 2, - container_image: 'iofog/temperature-sensor-simulator-arm' - } - ]); + container_image: 'iofog/temperature-sensor-simulator-arm', + }, + ]) }, down: (queryInterface, Sequelize) => { - return queryInterface.bulkDelete('CatalogItemImages', null, {}); - } -}; \ No newline at end of file + return queryInterface.bulkDelete('CatalogItemImages', null, {}) + }, +} diff --git a/src/sequelize/seeders/20190130112616-insert-logging-catalog-item.js b/src/sequelize/seeders/20190130112616-insert-logging-catalog-item.js index 4a0c405ef..cf000c929 100644 --- a/src/sequelize/seeders/20190130112616-insert-logging-catalog-item.js +++ b/src/sequelize/seeders/20190130112616-insert-logging-catalog-item.js @@ -1,4 +1,4 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { @@ -16,30 +16,30 @@ module.exports = { config_example: '{"access_tokens": ["Some_Access_Token"], "cleanfrequency": "1h40m", "ttl": "24h"}', is_public: 0, registry_id: 1, - user_id: null + user_id: null, }] ).then(() => { return queryInterface.bulkInsert('CatalogItemImages', [ - { - ID: 101, - catalog_item_id: 100, - fog_type_id: 1, - container_image: 'iofog/common-logging' - }, - { - ID: 102, - catalog_item_id: 100, - fog_type_id: 2, - container_image: 'iofog/common-logging-arm' - } - ] + { + ID: 101, + catalog_item_id: 100, + fog_type_id: 1, + container_image: 'iofog/common-logging', + }, + { + ID: 102, + catalog_item_id: 100, + fog_type_id: 2, + container_image: 'iofog/common-logging-arm', + }, + ] ) - }); + }) }, down: (queryInterface, Sequelize) => { return queryInterface.bulkDelete('CatalogItems', {ID: 100}, {}).then(() => { return queryInterface.bulkDelete('CatalogItemImages', {catalog_item_id: 100}) - }); - } -}; \ No newline at end of file + }) + }, +} diff --git a/src/sequelize/seeders/20190131111441-insert-json-generator-catalog-item.js b/src/sequelize/seeders/20190131111441-insert-json-generator-catalog-item.js index faa36d195..0cb16b3eb 100644 --- a/src/sequelize/seeders/20190131111441-insert-json-generator-catalog-item.js +++ b/src/sequelize/seeders/20190131111441-insert-json-generator-catalog-item.js @@ -13,30 +13,29 @@ module.exports = { config_example: '{}', is_public: 1, registry_id: 1, - user_id: null + user_id: null, }] ).then(() => { return queryInterface.bulkInsert('CatalogItemImages', [ - { - ID: 103, - catalog_item_id: 101, - fog_type_id: 1, - container_image: 'iofog/json-generator' - }, - { - ID: 104, - catalog_item_id: 101, - fog_type_id: 2, - container_image: 'iofog/json-generator-arm' - } - ] - ) - }); + { + ID: 103, + catalog_item_id: 101, + fog_type_id: 1, + container_image: 'iofog/json-generator', + }, + { + ID: 104, + catalog_item_id: 101, + fog_type_id: 2, + container_image: 'iofog/json-generator-arm', + }, + ]) + }) }, down: (queryInterface, Sequelize) => { return queryInterface.bulkDelete('CatalogItems', {ID: 101}, {}).then(() => { return queryInterface.bulkDelete('CatalogItemImages', {catalog_item_id: 101}) - }); - } -}; \ No newline at end of file + }) + }, +} diff --git a/src/sequelize/seeders/20190218103641-adding-default-configs.js b/src/sequelize/seeders/20190218103641-adding-default-configs.js index b08b6193e..fd3457a52 100644 --- a/src/sequelize/seeders/20190218103641-adding-default-configs.js +++ b/src/sequelize/seeders/20190218103641-adding-default-configs.js @@ -1,78 +1,80 @@ -'use strict'; +'use strict' module.exports = { up: (queryInterface, Sequelize) => { return queryInterface.bulkUpdate('CatalogItems', - { - config_example: '{"citycode":"5391997","apikey":"6141811a6136148a00133488eadff0fb","frequency":1000}' - }, - { - name: 'Open Weather Map Data' - }).then(() => { - return queryInterface.bulkUpdate('CatalogItems', { - config_example: '{"buffersize":3,"contentdataencoding":"utf8","contextdataencoding":"utf8",outputfields":{"publisher":"source","contentdata":"temperature","timestamp":"time"}}' + config_example: '{"citycode":"5391997","apikey":"6141811a6136148a00133488eadff0fb","frequency":1000}', }, { - name: 'JSON REST API' - } + name: 'Open Weather Map Data', + }, + ).then(() => { + return queryInterface.bulkUpdate('CatalogItems', + { + config_example: '{"buffersize":3,"contentdataencoding":"utf8","contextdataencoding":"utf8",' + + 'outputfields":{"publisher":"source","contentdata":"temperature","timestamp":"time"}}', + }, + { + name: 'JSON REST API', + }, ) }).then(() => { return queryInterface.bulkUpdate('CatalogItems', - { - config_example: '{}' - }, - { - name: 'JSON Sub-Select' - } + { + config_example: '{}', + }, + { + name: 'JSON Sub-Select', + }, ) }).then(() => { return queryInterface.bulkUpdate('CatalogItems', - { - is_public: 1, - }, - { - name: 'Common Logging', - } + { + is_public: 1, + }, + { + name: 'Common Logging', + }, ) }) - }, down: (queryInterface, Sequelize) => { return queryInterface.bulkUpdate('CatalogItems', - { - config_example: '{}' - }, - { - name: 'Open Weather Map Data' - }).then(() => { - return queryInterface.bulkUpdate('CatalogItems', { - config_example: '{}' + config_example: '{}', }, { - name: 'JSON REST API' - } + name: 'Open Weather Map Data', + }, + ).then(() => { + return queryInterface.bulkUpdate('CatalogItems', + { + config_example: '{}', + }, + { + name: 'JSON REST API', + }, ) }).then(() => { return queryInterface.bulkUpdate('CatalogItems', - { - config_example: '{}' - }, - { - name: 'JSON Sub-Select' - } + { + config_example: '{}', + }, + { + name: 'JSON Sub-Select', + }, ) }).then(() => { return queryInterface.bulkUpdate('CatalogItems', - { - is_public: 0, - }, - { - name: 'Common Logging', - } + { + is_public: 0, + }, + { + name: 'Common Logging', + }, ) }) - } -}; + }, +} diff --git a/src/server.js b/src/server.js index cc5d808e1..81d9fc1c8 100644 --- a/src/server.js +++ b/src/server.js @@ -11,116 +11,114 @@ * */ -const config = require('./config'); -const logger = require('./logger'); - -const bodyParser = require('body-parser'); -const cookieParser = require('cookie-parser'); -const express = require('express'); -const fs = require('fs'); -const helmet = require('helmet'); +const config = require('./config') +const logger = require('./logger') + +const bodyParser = require('body-parser') +const cookieParser = require('cookie-parser') +const express = require('express') +const fs = require('fs') +const helmet = require('helmet') const https = require('https') -const path = require('path'); -const {renderFile} = require('ejs'); -const xss = require('xss-clean'); -const morgan = require('morgan'); -const fogStatusJob = require('./jobs/fog-status-job'); -const packageJson = require('../package'); +const path = require('path') +const {renderFile} = require('ejs') +const xss = require('xss-clean') +const packageJson = require('../package') -const app = express(); -const Sentry = require('@sentry/node'); +const app = express() +const Sentry = require('@sentry/node') -const Tracking = require('./tracking'); -const TrackingEventType = require('./enums/tracking-event-type'); +const Tracking = require('./tracking') +const TrackingEventType = require('./enums/tracking-event-type') -Sentry.init({ dsn: 'https://a15f11352d404c2aa4c8f321ad9e759a@sentry.io/1378602' }); -Sentry.configureScope(scope => { - scope.setExtra('version', packageJson.version); -}); +Sentry.init({dsn: 'https://a15f11352d404c2aa4c8f321ad9e759a@sentry.io/1378602'}) +Sentry.configureScope((scope) => { + scope.setExtra('version', packageJson.version) +}) -app.use(Sentry.Handlers.requestHandler()); -app.use(Sentry.Handlers.errorHandler()); +app.use(Sentry.Handlers.requestHandler()) +app.use(Sentry.Handlers.errorHandler()) -app.use(helmet()); -app.use(xss()); +app.use(helmet()) +app.use(xss()) -//express logs +// express logs // app.use(morgan('combined')); app.use(bodyParser.urlencoded({ extended: true, -})); -app.use(bodyParser.json()); +})) +app.use(bodyParser.json()) -app.engine('ejs', renderFile); -app.set('view engine', 'ejs'); -app.use(cookieParser()); +app.engine('ejs', renderFile) +app.set('view engine', 'ejs') +app.use(cookieParser()) -app.set('views', path.join(__dirname, 'views')); +app.set('views', path.join(__dirname, 'views')) app.on('uncaughtException', (req, res, route, err) => { // TODO -}); +}) app.use((req, res, next) => { - res.append('X-Timestamp', Date.now()); + res.append('X-Timestamp', Date.now()) next() -}); +}) -global.appRoot = path.resolve(__dirname); +global.appRoot = path.resolve(__dirname) const registerRoute = (route) => { app[route.method.toLowerCase()](route.path, route.middleware) -}; +} -const setupMiddleware = function (routeName) { +const setupMiddleware = function(routeName) { const routes = [].concat(require(path.join(__dirname, 'routes', routeName)) || []) routes.forEach(registerRoute) -}; +} fs.readdirSync(path.join(__dirname, 'routes')) - .forEach(setupMiddleware); + .forEach(setupMiddleware) -let jobs = []; +const jobs = [] -const setupJobs = function (file) { - jobs.push((require(path.join(__dirname, 'jobs', file)) || [])); -}; +const setupJobs = function(file) { + jobs.push((require(path.join(__dirname, 'jobs', file)) || [])) +} fs.readdirSync(path.join(__dirname, 'jobs')) - .filter(file => { - return (file.indexOf('.') !== 0) && (file.slice(-3) === '.js'); - }) - .forEach(setupJobs); + .filter((file) => { + return (file.indexOf('.') !== 0) && (file.slice(-3) === '.js') + }) + .forEach(setupJobs) function startHttpServer(app, port, jobs) { - logger.info("SSL not configured, starting HTTP server."); + logger.info('SSL not configured, starting HTTP server.') app.listen(port, function onStart(err) { if (err) { logger.error(err) } - logger.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`, port, port); - jobs.forEach(job => job.run()); + logger.info(`==> 🌎 Listening on port ${port}. Open up http://localhost:${port}/ in your browser.`, port, port) + jobs.forEach((job) => job.run()) }) } function startHttpsServer(app, port, sslKey, sslCert, intermedKey, jobs) { try { - let sslOptions = { + const sslOptions = { key: fs.readFileSync(sslKey), cert: fs.readFileSync(sslCert), ca: fs.readFileSync(intermedKey), requestCert: true, - rejectUnauthorized: false // currently for some reason iofog agent doesn't work without this option - }; + rejectUnauthorized: false, // currently for some reason iofog agent doesn't work without this option + } https.createServer(sslOptions, app).listen(port, function onStart(err) { if (err) { logger.error(err) } - logger.info(`==> 🌎 HTTPS server listening on port ${port}. Open up https://localhost:${port}/ in your browser.`); - jobs.forEach(job => job.run()); + logger.info(`==> 🌎 HTTPS server listening on port ${port}. Open up https://localhost:${port}/ in your browser.`) + jobs.forEach((job) => job.run()) }) } catch (e) { logger.error('ssl_key or ssl_cert or intermediate_cert is either missing or invalid. Provide valid SSL configurations.') @@ -128,11 +126,11 @@ function startHttpsServer(app, port, sslKey, sslCert, intermedKey, jobs) { } const - devMode = config.get('Server:DevMode'), - port = config.get('Server:Port'), - sslKey = config.get('Server:SslKey'), - sslCert = config.get('Server:SslCert'), - intermedKey = config.get('Server:IntermediateCert'); + devMode = config.get('Server:DevMode') +const port = config.get('Server:Port') +const sslKey = config.get('Server:SslKey') +const sslCert = config.get('Server:SslCert') +const intermedKey = config.get('Server:IntermediateCert') if (!devMode && sslKey && sslCert && intermedKey) { startHttpsServer(app, port, sslKey, sslCert, intermedKey, jobs) @@ -140,5 +138,5 @@ if (!devMode && sslKey && sslCert && intermedKey) { startHttpServer(app, port, jobs) } -const event = Tracking.buildEvent(TrackingEventType.START, `devMode is ${devMode}`); -Tracking.processEvent(event); +const event = Tracking.buildEvent(TrackingEventType.START, `devMode is ${devMode}`) +Tracking.processEvent(event) diff --git a/src/services/access-token-service.js b/src/services/access-token-service.js index f0fb09da4..732abb4a0 100644 --- a/src/services/access-token-service.js +++ b/src/services/access-token-service.js @@ -11,19 +11,19 @@ * */ -const AccessTokenManager = require('../sequelize/managers/access-token-manager'); +const AccessTokenManager = require('../sequelize/managers/access-token-manager') -const createAccessToken = async function (accessToken, transaction) { - return await AccessTokenManager.create(accessToken, transaction); -}; +const createAccessToken = async function(accessToken, transaction) { + return await AccessTokenManager.create(accessToken, transaction) +} -const removeAccessTokenByUserId = async function (userId, transaction) { +const removeAccessTokenByUserId = async function(userId, transaction) { return await AccessTokenManager.delete({ - userId: userId - }, transaction); -}; + userId: userId, + }, transaction) +} module.exports = { createAccessToken: createAccessToken, - removeAccessTokenByUserId: removeAccessTokenByUserId -}; \ No newline at end of file + removeAccessTokenByUserId: removeAccessTokenByUserId, +} diff --git a/src/services/agent-service.js b/src/services/agent-service.js index b01980f58..1888adc71 100644 --- a/src/services/agent-service.js +++ b/src/services/agent-service.js @@ -11,103 +11,102 @@ * */ -const TransactionDecorator = require('../decorators/transaction-decorator'); - -const FogProvisionKeyManager = require('../sequelize/managers/iofog-provision-key-manager'); -const FogManager = require('../sequelize/managers/iofog-manager'); -const FogAccessTokenService = require('../services/iofog-access-token-service'); -const ChangeTrackingService = require('./change-tracking-service'); -const FogVersionCommandManager = require('../sequelize/managers/iofog-version-command-manager'); -const StraceManager = require('../sequelize/managers/strace-manager'); -const RegistryManager = require('../sequelize/managers/registry-manager'); +const TransactionDecorator = require('../decorators/transaction-decorator') + +const FogProvisionKeyManager = require('../sequelize/managers/iofog-provision-key-manager') +const FogManager = require('../sequelize/managers/iofog-manager') +const FogAccessTokenService = require('../services/iofog-access-token-service') +const ChangeTrackingService = require('./change-tracking-service') +const FogVersionCommandManager = require('../sequelize/managers/iofog-version-command-manager') +const StraceManager = require('../sequelize/managers/strace-manager') +const RegistryManager = require('../sequelize/managers/registry-manager') const MicroserviceStatusManager = require('../sequelize/managers/microservice-status-manager') -const MicroserviceStates = require('../enums/microservice-state'); -const FogStates = require('../enums/fog-state'); -const Validator = require('../schemas'); -const Errors = require('../helpers/errors'); -const AppHelper = require('../helpers/app-helper'); -const ErrorMessages = require('../helpers/error-messages'); -const HWInfoManager = require('../sequelize/managers/hw-info-manager'); -const USBInfoManager = require('../sequelize/managers/usb-info-manager'); -const TunnelManager = require('../sequelize/managers/tunnel-manager'); -const MicroserviceManager = require('../sequelize/managers/microservice-manager'); -const MicroserviceService = require('../services/microservices-service'); -const path = require('path'); -const fs = require('fs'); -const formidable = require('formidable'); -const Sequelize = require('sequelize'); -const Op = Sequelize.Op; -const TrackingDecorator = require('../decorators/tracking-decorator'); -const TrackingEventType = require('../enums/tracking-event-type'); -const TrackingEventManager = require('../sequelize/managers/tracking-event-manager'); - -const IncomingForm = formidable.IncomingForm; - -const agentProvision = async function (provisionData, transaction) { - await Validator.validate(provisionData, Validator.schemas.agentProvision); +const MicroserviceStates = require('../enums/microservice-state') +const FogStates = require('../enums/fog-state') +const Validator = require('../schemas') +const Errors = require('../helpers/errors') +const AppHelper = require('../helpers/app-helper') +const ErrorMessages = require('../helpers/error-messages') +const HWInfoManager = require('../sequelize/managers/hw-info-manager') +const USBInfoManager = require('../sequelize/managers/usb-info-manager') +const TunnelManager = require('../sequelize/managers/tunnel-manager') +const MicroserviceManager = require('../sequelize/managers/microservice-manager') +const MicroserviceService = require('../services/microservices-service') +const path = require('path') +const fs = require('fs') +const formidable = require('formidable') +const Sequelize = require('sequelize') +const Op = Sequelize.Op +const TrackingDecorator = require('../decorators/tracking-decorator') +const TrackingEventType = require('../enums/tracking-event-type') +const TrackingEventManager = require('../sequelize/managers/tracking-event-manager') + +const IncomingForm = formidable.IncomingForm + +const agentProvision = async function(provisionData, transaction) { + await Validator.validate(provisionData, Validator.schemas.agentProvision) const provision = await FogProvisionKeyManager.findOne({ - provisionKey: provisionData.key - }, transaction); + provisionKey: provisionData.key, + }, transaction) if (!provision) { throw new Errors.NotFoundError(ErrorMessages.INVALID_PROVISIONING_KEY) } - let currentTime = new Date(); + const currentTime = new Date() if (provision.expirationTime < currentTime) { throw new Errors.AuthenticationError(ErrorMessages.EXPIRED_PROVISION_KEY) } const fog = await FogManager.findOne({ - uuid: provision.iofogUuid - }, transaction); + uuid: provision.iofogUuid, + }, transaction) - await _checkMicroservicesFogType(fog, provisionData.type, transaction); + await _checkMicroservicesFogType(fog, provisionData.type, transaction) - const newAccessToken = await FogAccessTokenService.generateAccessToken(transaction); + const newAccessToken = await FogAccessTokenService.generateAccessToken(transaction) - await FogAccessTokenService.updateAccessToken(fog.uuid, newAccessToken, transaction); + await FogAccessTokenService.updateAccessToken(fog.uuid, newAccessToken, transaction) await FogManager.update({ - uuid: fog.uuid + uuid: fog.uuid, }, { - fogTypeId: provisionData.type - }, transaction); + fogTypeId: provisionData.type, + }, transaction) await FogProvisionKeyManager.delete({ - provisionKey: provisionData.key - }, transaction); + provisionKey: provisionData.key, + }, transaction) return { uuid: fog.uuid, - token: newAccessToken.token - }; - -}; + token: newAccessToken.token, + } +} -const agentDeprovision = async function (deprovisionData, fog, transaction) { - await Validator.validate(deprovisionData, Validator.schemas.agentDeprovision); +const agentDeprovision = async function(deprovisionData, fog, transaction) { + await Validator.validate(deprovisionData, Validator.schemas.agentDeprovision) await MicroserviceStatusManager.update( - {microserviceUuid: deprovisionData.microserviceUuids}, - {status: MicroserviceStates.NOT_RUNNING}, - transaction - ); - - await _invalidateFogNode(fog, transaction); -}; - -const _invalidateFogNode = async function (fog, transaction) { - const where = {uuid: fog.uuid}; - const data = {daemonStatus: FogStates.UNKNOWN, ipAddress: '0.0.0.0'}; - await FogManager.update(where, data, transaction); - const updatedFog = Object.assign({}, fog); - updatedFog.daemonStatus = FogStates.UNKNOWN; - updatedFog.ipAddress = '0.0.0.0'; - return updatedFog; -}; - -const getAgentConfig = async function (fog) { + {microserviceUuid: deprovisionData.microserviceUuids}, + {status: MicroserviceStates.NOT_RUNNING}, + transaction + ) + + await _invalidateFogNode(fog, transaction) +} + +const _invalidateFogNode = async function(fog, transaction) { + const where = {uuid: fog.uuid} + const data = {daemonStatus: FogStates.UNKNOWN, ipAddress: '0.0.0.0'} + await FogManager.update(where, data, transaction) + const updatedFog = Object.assign({}, fog) + updatedFog.daemonStatus = FogStates.UNKNOWN + updatedFog.ipAddress = '0.0.0.0' + return updatedFog +} + +const getAgentConfig = async function(fog) { return { networkInterface: fog.networkInterface, dockerUrl: fog.dockerUrl, @@ -123,12 +122,12 @@ const getAgentConfig = async function (fog) { deviceScanFrequency: fog.deviceScanFrequency, watchdogEnabled: fog.watchdogEnabled, latitude: fog.latitude, - longitude: fog.longitude - }; -}; + longitude: fog.longitude, + } +} -const updateAgentConfig = async function (updateData, fog, transaction) { - await Validator.validate(updateData, Validator.schemas.updateAgentConfig); +const updateAgentConfig = async function(updateData, fog, transaction) { + await Validator.validate(updateData, Validator.schemas.updateAgentConfig) let update = { networkInterface: updateData.networkInterface, @@ -146,23 +145,22 @@ const updateAgentConfig = async function (updateData, fog, transaction) { watchdogEnabled: updateData.watchdogEnabled, latitude: updateData.latitude, longitude: updateData.longitude, - gpsMode: updateData.gpsMode - }; - update = AppHelper.deleteUndefinedFields(update); + gpsMode: updateData.gpsMode, + } + update = AppHelper.deleteUndefinedFields(update) await FogManager.update({ - uuid: fog.uuid - }, update, transaction); -}; - -const getAgentConfigChanges = async function (ioFog, transaction) { + uuid: fog.uuid, + }, update, transaction) +} - const changeTracking = await ChangeTrackingService.getByIoFogUuid(ioFog.uuid, transaction); +const getAgentConfigChanges = async function(ioFog, transaction) { + const changeTracking = await ChangeTrackingService.getByIoFogUuid(ioFog.uuid, transaction) if (!changeTracking) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_IOFOG_UUID), ioFog.uuid); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_IOFOG_UUID), ioFog.uuid) } - await ChangeTrackingService.updateIfChanged(ioFog.uuid, ChangeTrackingService.events.clean, transaction); + await ChangeTrackingService.updateIfChanged(ioFog.uuid, ChangeTrackingService.events.clean, transaction) return { config: changeTracking.config, @@ -175,12 +173,12 @@ const getAgentConfigChanges = async function (ioFog, transaction) { registries: changeTracking.registries, tunnel: changeTracking.tunnel, diagnostics: changeTracking.diagnostics, - isImageSnapshot: changeTracking.isImageSnapshot - }; -}; + isImageSnapshot: changeTracking.isImageSnapshot, + } +} -const updateAgentStatus = async function (agentStatus, fog, transaction) { - await Validator.validate(agentStatus, Validator.schemas.updateAgentStatus); +const updateAgentStatus = async function(agentStatus, fog, transaction) { + await Validator.validate(agentStatus, Validator.schemas.updateAgentStatus) let fogStatus = { daemonStatus: agentStatus.daemonStatus, @@ -204,21 +202,21 @@ const updateAgentStatus = async function (agentStatus, fog, transaction) { tunnelStatus: agentStatus.tunnelStatus, version: agentStatus.version, isReadyToUpgrade: agentStatus.isReadyToUpgrade, - isReadyToRollback: agentStatus.isReadyToRollback - }; + isReadyToRollback: agentStatus.isReadyToRollback, + } - fogStatus = AppHelper.deleteUndefinedFields(fogStatus); + fogStatus = AppHelper.deleteUndefinedFields(fogStatus) await FogManager.update({ - uuid: fog.uuid - }, fogStatus, transaction); + uuid: fog.uuid, + }, fogStatus, transaction) - await _updateMicroserviceStatuses(JSON.parse(agentStatus.microserviceStatus), transaction); - await MicroserviceService.deleteNotRunningMicroservices(fog, transaction); -}; + await _updateMicroserviceStatuses(JSON.parse(agentStatus.microserviceStatus), transaction) + await MicroserviceService.deleteNotRunningMicroservices(fog, transaction) +} -const _updateMicroserviceStatuses = async function (microserviceStatus, transaction) { +const _updateMicroserviceStatuses = async function(microserviceStatus, transaction) { for (status of microserviceStatus) { let microserviceStatus = { containerId: status.containerId, @@ -226,31 +224,31 @@ const _updateMicroserviceStatuses = async function (microserviceStatus, transact startTime: status.startTime, operatingDuration: status.operatingDuration, cpuUsage: status.cpuUsage, - memoryUsage: status.memoryUsage - }; - microserviceStatus = AppHelper.deleteUndefinedFields(microserviceStatus); + memoryUsage: status.memoryUsage, + } + microserviceStatus = AppHelper.deleteUndefinedFields(microserviceStatus) await MicroserviceStatusManager.update({ - microserviceUuid: status.id - }, microserviceStatus, transaction); + microserviceUuid: status.id, + }, microserviceStatus, transaction) } -}; +} -const getAgentMicroservices = async function (fog, transaction) { - const microservices = await MicroserviceManager.findAllActiveFlowMicroservices(fog.uuid, transaction); +const getAgentMicroservices = async function(fog, transaction) { + const microservices = await MicroserviceManager.findAllActiveFlowMicroservices(fog.uuid, transaction) - const fogTypeId = fog.fogTypeId; + const fogTypeId = fog.fogTypeId - const response = []; + const response = [] for (const microservice of microservices) { - const images = microservice.catalogItem.images; - const image = images.find(image => image.fogTypeId === fogTypeId); - const imageId = image ? image.containerImage : ''; + const images = microservice.catalogItem.images + const image = images.find((image) => image.fogTypeId === fogTypeId) + const imageId = image ? image.containerImage : '' if (!imageId || imageId === '') { - continue; + continue } - const routes = await MicroserviceService.getPhysicalConnections(microservice, transaction); + const routes = await MicroserviceService.getPhysicalConnections(microservice, transaction) const responseMicroservice = { uuid: microservice.uuid, @@ -265,249 +263,246 @@ const getAgentMicroservices = async function (fog, transaction) { imageSnapshot: microservice.imageSnapshot, delete: microservice.delete, deleteWithCleanup: microservice.deleteWithCleanup, - routes: routes - }; + routes: routes, + } - response.push(responseMicroservice); + response.push(responseMicroservice) await MicroserviceManager.update({ - uuid: microservice.uuid + uuid: microservice.uuid, }, { - rebuild: false - }, transaction); - + rebuild: false, + }, transaction) } return { - microservices: response + microservices: response, } -}; +} -const getAgentMicroservice = async function (microserviceUuid, fog, transaction) { +const getAgentMicroservice = async function(microserviceUuid, fog, transaction) { const microservice = await MicroserviceManager.findOneWithDependencies({ uuid: microserviceUuid, - iofogUuid: fog.uuid - }, {}, transaction); + iofogUuid: fog.uuid, + }, {}, transaction) if (!microservice) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)) } return { - microservice: microservice + microservice: microservice, } -}; +} -const getAgentRegistries = async function (fog, transaction) { +const getAgentRegistries = async function(fog, transaction) { const registries = await RegistryManager.findAll({ [Op.or]: [ { - userId: fog.userId + userId: fog.userId, }, { - isPublic: true - } - ] - }, transaction); + isPublic: true, + }, + ], + }, transaction) return { - registries: registries + registries: registries, } -}; +} -const getAgentTunnel = async function (fog, transaction) { +const getAgentTunnel = async function(fog, transaction) { const tunnel = await TunnelManager.findOne({ - iofogUuid: fog.uuid - }, transaction); + iofogUuid: fog.uuid, + }, transaction) if (!tunnel) { - throw new Errors.NotFoundError(ErrorMessages.TUNNEL_NOT_FOUND); + throw new Errors.NotFoundError(ErrorMessages.TUNNEL_NOT_FOUND) } return { - tunnel: tunnel + tunnel: tunnel, } -}; +} -const getAgentStrace = async function (fog, transaction) { +const getAgentStrace = async function(fog, transaction) { const fogWithStrace = await FogManager.findFogStraces({ - uuid: fog.uuid - }, transaction); + uuid: fog.uuid, + }, transaction) if (!fogWithStrace) { - throw new Errors.NotFoundError(ErrorMessages.STRACE_NOT_FOUND); + throw new Errors.NotFoundError(ErrorMessages.STRACE_NOT_FOUND) } - const straceArr = []; + const straceArr = [] for (const msData of fogWithStrace.microservice) { straceArr.push({ microserviceUuid: msData.strace.microserviceUuid, - straceRun: msData.strace.straceRun + straceRun: msData.strace.straceRun, }) } return { - straceValues: straceArr + straceValues: straceArr, } -}; +} -const updateAgentStrace = async function (straceData, fog, transaction) { - await Validator.validate(straceData, Validator.schemas.updateAgentStrace); +const updateAgentStrace = async function(straceData, fog, transaction) { + await Validator.validate(straceData, Validator.schemas.updateAgentStrace) for (const strace of straceData.straceData) { - const microserviceUuid = strace.microserviceUuid; - const buffer = strace.buffer; + const microserviceUuid = strace.microserviceUuid + const buffer = strace.buffer await StraceManager.pushBufferByMicroserviceUuid(microserviceUuid, buffer, transaction) } -}; +} -const getAgentChangeVersionCommand = async function (fog, transaction) { +const getAgentChangeVersionCommand = async function(fog, transaction) { const versionCommand = await FogVersionCommandManager.findOne({ - iofogUuid: fog.uuid - }, transaction); + iofogUuid: fog.uuid, + }, transaction) if (!versionCommand) { - throw new Errors.NotFoundError(ErrorMessages.VERSION_COMMAND_NOT_FOUND); + throw new Errors.NotFoundError(ErrorMessages.VERSION_COMMAND_NOT_FOUND) } const provision = await FogProvisionKeyManager.findOne({ - iofogUuid: fog.uuid - }, transaction); + iofogUuid: fog.uuid, + }, transaction) return { versionCommand: versionCommand.versionCommand, provisionKey: provision.provisionKey, - expirationTime: provision.expirationTime + expirationTime: provision.expirationTime, } -}; +} -const updateHalHardwareInfo = async function (hardwareData, fog, transaction) { - await Validator.validate(hardwareData, Validator.schemas.updateHardwareInfo); +const updateHalHardwareInfo = async function(hardwareData, fog, transaction) { + await Validator.validate(hardwareData, Validator.schemas.updateHardwareInfo) - hardwareData.iofogUuid = fog.uuid; + hardwareData.iofogUuid = fog.uuid await HWInfoManager.updateOrCreate({ - iofogUuid: fog.uuid - }, hardwareData, transaction); -}; + iofogUuid: fog.uuid, + }, hardwareData, transaction) +} -const updateHalUsbInfo = async function (usbData, fog, transaction) { - await Validator.validate(usbData, Validator.schemas.updateUsbInfo); +const updateHalUsbInfo = async function(usbData, fog, transaction) { + await Validator.validate(usbData, Validator.schemas.updateUsbInfo) - usbData.iofogUuid = fog.uuid; + usbData.iofogUuid = fog.uuid await USBInfoManager.updateOrCreate({ - iofogUuid: fog.uuid - }, usbData, transaction); -}; + iofogUuid: fog.uuid, + }, usbData, transaction) +} -const deleteNode = async function (fog, transaction) { +const deleteNode = async function(fog, transaction) { await FogManager.delete({ - uuid: fog.uuid - }, transaction); -}; + uuid: fog.uuid, + }, transaction) +} -const getImageSnapshot = async function (fog, transaction) { +const getImageSnapshot = async function(fog, transaction) { const microservice = await MicroserviceManager.findOne({ iofogUuid: fog.uuid, - imageSnapshot: 'get_image' - }, transaction); + imageSnapshot: 'get_image', + }, transaction) if (!microservice) { - throw new Errors.NotFoundError(ErrorMessages.IMAGE_SNAPSHOT_NOT_FOUND); + throw new Errors.NotFoundError(ErrorMessages.IMAGE_SNAPSHOT_NOT_FOUND) } return { - uuid: microservice.uuid + uuid: microservice.uuid, } -}; +} -const putImageSnapshot = async function (req, fog, transaction) { +const putImageSnapshot = async function(req, fog, transaction) { const opts = { maxFieldsSize: 500 * 1024 * 1024, - maxFileSize: 500 * 1024 * 1024 - }; + maxFileSize: 500 * 1024 * 1024, + } if (!req.headers['content-type'].includes('multipart/form-data')) { - throw new Errors.ValidationError(ErrorMessages.INVALID_CONTENT_TYPE); + throw new Errors.ValidationError(ErrorMessages.INVALID_CONTENT_TYPE) } - const form = new IncomingForm(opts); - form.uploadDir = path.join(appRoot, '../') + 'data'; + const form = new IncomingForm(opts) + form.uploadDir = path.join(appRoot, '../') + 'data' if (!fs.existsSync(form.uploadDir)) { - fs.mkdirSync(form.uploadDir); + fs.mkdirSync(form.uploadDir) } - await _saveSnapShot(req, form, fog, transaction); - return {}; -}; + await _saveSnapShot(req, form, fog, transaction) + return {} +} -const _saveSnapShot = function (req, form, fog, transaction) { +const _saveSnapShot = function(req, form, fog, transaction) { return new Promise((resolve, reject) => { - form.parse(req, async function (error, fields, files) { - const file = files['upstream']; + form.parse(req, async function(error, fields, files) { + const file = files['upstream'] if (file === undefined) { - reject(new Errors.ValidationError(ErrorMessages.UPLOADED_FILE_NOT_FOUND)); - return; + reject(new Errors.ValidationError(ErrorMessages.UPLOADED_FILE_NOT_FOUND)) + return } - const filePath = file['path']; + const filePath = file['path'] - let absolutePath = path.resolve(filePath); - fs.renameSync(absolutePath, absolutePath + '.tar.gz'); + const absolutePath = path.resolve(filePath) + fs.renameSync(absolutePath, absolutePath + '.tar.gz') await MicroserviceManager.update({ iofogUuid: fog.uuid, - imageSnapshot: 'get_image' + imageSnapshot: 'get_image', }, { - imageSnapshot: absolutePath + '.tar.gz' - }, transaction); - - resolve(); + imageSnapshot: absolutePath + '.tar.gz', + }, transaction) - }); - }); -}; + resolve() + }) + }) +} async function _checkMicroservicesFogType(fog, fogTypeId, transaction) { const where = { - iofogUuid: fog.uuid - }; - const microservices = await MicroserviceManager.findAllWithDependencies(where, {}, transaction); + iofogUuid: fog.uuid, + } + const microservices = await MicroserviceManager.findAllWithDependencies(where, {}, transaction) if (microservices) { - - let invalidMicroservices = []; + const invalidMicroservices = [] for (const microservice of microservices) { - let exists = false; - for (let image of microservice.catalogItem.images) { + let exists = false + for (const image of microservice.catalogItem.images) { if (image.fogTypeId === fogTypeId) { - exists = true; - break; + exists = true + break } } if (!exists) { - invalidMicroservices.push(microservice); + invalidMicroservices.push(microservice) } } if (invalidMicroservices.length > 0) { - let errorMsg = ErrorMessages.INVALID_MICROSERVICES_FOG_TYPE; + let errorMsg = ErrorMessages.INVALID_MICROSERVICES_FOG_TYPE for (error of invalidMicroservices) { - errorMsg = errorMsg + ' "' + error.name + '" microservice\n'; + errorMsg = errorMsg + ' "' + error.name + '" microservice\n' } - throw new Errors.ValidationError(errorMsg); + throw new Errors.ValidationError(errorMsg) } } } async function postTracking(events, fog, transaction) { - await Validator.validate(events, Validator.schemas.trackingArray); + await Validator.validate(events, Validator.schemas.trackingArray) for (const event of events) { event.data = JSON.stringify(event.data) } - await TrackingEventManager.bulkCreate(events, transaction); + await TrackingEventManager.bulkCreate(events, transaction) } -//decorated functions -const agentProvisionWithTracking = TrackingDecorator.trackEvent(agentProvision, TrackingEventType.IOFOG_PROVISION); +// decorated functions +const agentProvisionWithTracking = TrackingDecorator.trackEvent(agentProvision, TrackingEventType.IOFOG_PROVISION) module.exports = { @@ -530,4 +525,4 @@ module.exports = { getImageSnapshot: TransactionDecorator.generateFakeTransaction(getImageSnapshot), putImageSnapshot: TransactionDecorator.generateFakeTransaction(putImageSnapshot), postTracking: TransactionDecorator.generateFakeTransaction(postTracking), -}; \ No newline at end of file +} diff --git a/src/services/catalog-service.js b/src/services/catalog-service.js index 69aaf578b..79c276502 100644 --- a/src/services/catalog-service.js +++ b/src/services/catalog-service.js @@ -11,116 +11,114 @@ * */ -const TransactionDecorator = require('../decorators/transaction-decorator'); -const AppHelper = require('../helpers/app-helper'); -const Errors = require('../helpers/errors'); -const ErrorMessages = require('../helpers/error-messages'); -const CatalogItemManager = require('../sequelize/managers/catalog-item-manager'); -const CatalogItemImageManager = require('../sequelize/managers/catalog-item-image-manager'); -const CatalogItemInputTypeManager = require('../sequelize/managers/catalog-item-input-type-manager'); -const CatalogItemOutputTypeManager = require('../sequelize/managers/catalog-item-output-type-manager'); -const Op = require('sequelize').Op; -const Validator = require('../schemas/index'); -const RegistryManager = require('../sequelize/managers/registry-manager'); -const MicroserviceManager = require('../sequelize/managers/microservice-manager'); -const ChangeTrackingService = require('./change-tracking-service'); -const MicroseriveStates = require('../enums/microservice-state'); -const TrackingDecorator = require('../decorators/tracking-decorator'); -const TrackingEventType = require('../enums/tracking-event-type'); - -const createCatalogItem = async function (data, user, transaction) { - await Validator.validate(data, Validator.schemas.catalogItemCreate); - await _checkForDuplicateName(data.name, {userId: user.id}, transaction); - await _checkForRestrictedPublisher(data.publisher); - const catalogItem = await _createCatalogItem(data, user, transaction); - await _createCatalogImages(data, catalogItem, transaction); - await _createCatalogItemInputType(data, catalogItem, transaction); - await _createCatalogItemOutputType(data, catalogItem, transaction); +const TransactionDecorator = require('../decorators/transaction-decorator') +const AppHelper = require('../helpers/app-helper') +const Errors = require('../helpers/errors') +const ErrorMessages = require('../helpers/error-messages') +const CatalogItemManager = require('../sequelize/managers/catalog-item-manager') +const CatalogItemImageManager = require('../sequelize/managers/catalog-item-image-manager') +const CatalogItemInputTypeManager = require('../sequelize/managers/catalog-item-input-type-manager') +const CatalogItemOutputTypeManager = require('../sequelize/managers/catalog-item-output-type-manager') +const Op = require('sequelize').Op +const Validator = require('../schemas/index') +const RegistryManager = require('../sequelize/managers/registry-manager') +const MicroserviceManager = require('../sequelize/managers/microservice-manager') +const MicroseriveStates = require('../enums/microservice-state') +const TrackingDecorator = require('../decorators/tracking-decorator') +const TrackingEventType = require('../enums/tracking-event-type') + +const createCatalogItem = async function(data, user, transaction) { + await Validator.validate(data, Validator.schemas.catalogItemCreate) + await _checkForDuplicateName(data.name, {userId: user.id}, transaction) + await _checkForRestrictedPublisher(data.publisher) + const catalogItem = await _createCatalogItem(data, user, transaction) + await _createCatalogImages(data, catalogItem, transaction) + await _createCatalogItemInputType(data, catalogItem, transaction) + await _createCatalogItemOutputType(data, catalogItem, transaction) return { - id: catalogItem.id + id: catalogItem.id, } -}; +} -const updateCatalogItem = async function (id, data, user, isCLI, transaction) { - await Validator.validate(data, Validator.schemas.catalogItemUpdate); +const updateCatalogItem = async function(id, data, user, isCLI, transaction) { + await Validator.validate(data, Validator.schemas.catalogItemUpdate) const where = isCLI ? { - id: id - } + id: id, + } : { - id: id, - userId: user.id - }; + id: id, + userId: user.id, + } - data.id = id; - await _updateCatalogItem(data, where, transaction); - await _updateCatalogItemImages(data, transaction); - await _updateCatalogItemIOTypes(data, where, transaction); -}; + data.id = id + await _updateCatalogItem(data, where, transaction) + await _updateCatalogItemImages(data, transaction) + await _updateCatalogItemIOTypes(data, where, transaction) +} -const listCatalogItems = async function (user, isCLI, transaction) { +const listCatalogItems = async function(user, isCLI, transaction) { const where = isCLI ? {} : { [Op.or]: [{userId: user.id}, {userId: null}], - [Op.or]: [{category: {[Op.ne]: 'SYSTEM'}}, {category: null}] - }; + [Op.or]: [{category: {[Op.ne]: 'SYSTEM'}}, {category: null}], + } const attributes = isCLI ? {} - : {exclude: ["userId"]}; + : {exclude: ['userId']} - const catalogItems = await CatalogItemManager.findAllWithDependencies(where, attributes, transaction); + const catalogItems = await CatalogItemManager.findAllWithDependencies(where, attributes, transaction) return { - catalogItems: catalogItems + catalogItems: catalogItems, } -}; +} -const getCatalogItem = async function (id, user, isCLI, transaction) { +const getCatalogItem = async function(id, user, isCLI, transaction) { const where = isCLI ? {id: id} : { id: id, [Op.or]: [{userId: user.id}, {userId: null}], - [Op.or]: [{category: {[Op.ne]: 'SYSTEM'}}, {category: null}] - }; + [Op.or]: [{category: {[Op.ne]: 'SYSTEM'}}, {category: null}], + } const attributes = isCLI ? {} - : {exclude: ["userId"]}; + : {exclude: ['userId']} - const item = await CatalogItemManager.findOneWithDependencies(where, attributes, transaction); + const item = await CatalogItemManager.findOneWithDependencies(where, attributes, transaction) if (!item) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_CATALOG_ITEM_ID, id)); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_CATALOG_ITEM_ID, id)) } - return item; -}; - -const deleteCatalogItem = async function (id, user, isCLI, transaction) { + return item +} +const deleteCatalogItem = async function(id, user, isCLI, transaction) { const where = isCLI ? { - id: id - } + id: id, + } : { - userId: user.id, - id: id - }; + userId: user.id, + id: id, + } - const item = await _checkIfItemExists(where, transaction); + const item = await _checkIfItemExists(where, transaction) - if (item.category == "SYSTEM"){ - throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.SYSTEM_CATALOG_ITEM_DELETE, id)); + if (item.category == 'SYSTEM') { + throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.SYSTEM_CATALOG_ITEM_DELETE, id)) } - const affectedRows = await CatalogItemManager.delete(where, transaction); + const affectedRows = await CatalogItemManager.delete(where, transaction) if (affectedRows === 0) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_CATALOG_ITEM_ID, id)); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_CATALOG_ITEM_ID, id)) } - return affectedRows; -}; + return affectedRows +} async function getNetworkCatalogItem(transaction) { return await CatalogItemManager.findOne({ @@ -128,7 +126,7 @@ async function getNetworkCatalogItem(transaction) { category: 'SYSTEM', publisher: 'Eclipse ioFog', registry_id: 1, - user_id: null + user_id: null, }, transaction) } @@ -138,7 +136,7 @@ async function getBluetoothCatalogItem(transaction) { category: 'SYSTEM', publisher: 'Eclipse ioFog', registry_id: 1, - user_id: null + user_id: null, }, transaction) } @@ -148,40 +146,39 @@ async function getHalCatalogItem(transaction) { category: 'SYSTEM', publisher: 'Eclipse ioFog', registry_id: 1, - user_id: null + user_id: null, }, transaction) } -const _checkForDuplicateName = async function (name, item, transaction) { +const _checkForDuplicateName = async function(name, item, transaction) { if (name) { const where = item.id ? {[Op.or]: [{userId: item.userId}, {userId: null}], name: name, id: {[Op.ne]: item.id}} - : {[Op.or]: [{userId: item.userId}, {userId: null}], name: name}; + : {[Op.or]: [{userId: item.userId}, {userId: null}], name: name} - const result = await CatalogItemManager.findOne(where, transaction); + const result = await CatalogItemManager.findOne(where, transaction) if (result) { - throw new Errors.DuplicatePropertyError(AppHelper.formatMessage(ErrorMessages.DUPLICATE_NAME, name)); + throw new Errors.DuplicatePropertyError(AppHelper.formatMessage(ErrorMessages.DUPLICATE_NAME, name)) } } -}; +} -const _checkForRestrictedPublisher = async function (publisher) { +const _checkForRestrictedPublisher = async function(publisher) { if (publisher === 'Eclipse ioFog') { - throw new Errors.ValidationError(ErrorMessages.RESTRICTED_PUBLISHER); + throw new Errors.ValidationError(ErrorMessages.RESTRICTED_PUBLISHER) } -}; +} -const _checkIfItemExists = async function (where, transaction) { - const item = await CatalogItemManager.findOne(where, transaction); +const _checkIfItemExists = async function(where, transaction) { + const item = await CatalogItemManager.findOne(where, transaction) if (!item) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_CATALOG_ITEM_ID, where.id)); - + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_CATALOG_ITEM_ID, where.id)) } - return item; -}; + return item +} -const _createCatalogItem = async function (data, user, transaction) { +const _createCatalogItem = async function(data, user, transaction) { let catalogItem = { name: data.name, description: data.description, @@ -193,80 +190,80 @@ const _createCatalogItem = async function (data, user, transaction) { picture: data.picture, isPublic: data.isPublic, registryId: data.registryId, - userId: user.id - }; + userId: user.id, + } - catalogItem = AppHelper.deleteUndefinedFields(catalogItem); + catalogItem = AppHelper.deleteUndefinedFields(catalogItem) if (catalogItem.registryId) { - const registry = await RegistryManager.findOne({id: catalogItem.registryId}, transaction); - if (!registry) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_REGISTRY_ID, data.registryId)); - } + const registry = await RegistryManager.findOne({id: catalogItem.registryId}, transaction) + if (!registry) { + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_REGISTRY_ID, data.registryId)) + } } - return await CatalogItemManager.create(catalogItem, transaction); -}; + return await CatalogItemManager.create(catalogItem, transaction) +} -const _createCatalogImages = async function (data, catalogItem, transaction) { +const _createCatalogImages = async function(data, catalogItem, transaction) { const catalogItemImages = [ { fogTypeId: 1, - catalogItemId: catalogItem.id + catalogItemId: catalogItem.id, }, { fogTypeId: 2, - catalogItemId: catalogItem.id - } - ]; + catalogItemId: catalogItem.id, + }, + ] if (data.images) { - for (let image of data.images) { + for (const image of data.images) { switch (image.fogTypeId) { case 1: - catalogItemImages[0].containerImage = image.containerImage; - break; + catalogItemImages[0].containerImage = image.containerImage + break case 2: - catalogItemImages[1].containerImage = image.containerImage; - break; + catalogItemImages[1].containerImage = image.containerImage + break } } } - return await CatalogItemImageManager.bulkCreate(catalogItemImages, transaction); -}; + return await CatalogItemImageManager.bulkCreate(catalogItemImages, transaction) +} -const _createCatalogItemInputType = async function (data, catalogItem, transaction) { +const _createCatalogItemInputType = async function(data, catalogItem, transaction) { let catalogItemInputType = { - catalogItemId: catalogItem.id - }; + catalogItemId: catalogItem.id, + } if (data.inputType) { - catalogItemInputType.infoType = data.inputType.infoType; - catalogItemInputType.infoFormat = data.inputType.infoFormat; + catalogItemInputType.infoType = data.inputType.infoType + catalogItemInputType.infoFormat = data.inputType.infoFormat } - catalogItemInputType = AppHelper.deleteUndefinedFields(catalogItemInputType); + catalogItemInputType = AppHelper.deleteUndefinedFields(catalogItemInputType) - return await CatalogItemInputTypeManager.create(catalogItemInputType, transaction); -}; + return await CatalogItemInputTypeManager.create(catalogItemInputType, transaction) +} -const _createCatalogItemOutputType = async function (data, catalogItem, transaction) { +const _createCatalogItemOutputType = async function(data, catalogItem, transaction) { let catalogItemOutputType = { - catalogItemId: catalogItem.id - }; + catalogItemId: catalogItem.id, + } if (data.outputType) { - catalogItemOutputType.infoType = data.outputType.infoType; - catalogItemOutputType.infoFormat = data.outputType.infoFormat; + catalogItemOutputType.infoType = data.outputType.infoType + catalogItemOutputType.infoFormat = data.outputType.infoFormat } - catalogItemOutputType = AppHelper.deleteUndefinedFields(catalogItemOutputType); + catalogItemOutputType = AppHelper.deleteUndefinedFields(catalogItemOutputType) - return await CatalogItemOutputTypeManager.create(catalogItemOutputType, transaction); -}; + return await CatalogItemOutputTypeManager.create(catalogItemOutputType, transaction) +} -const _updateCatalogItem = async function (data, where, transaction) { +const _updateCatalogItem = async function(data, where, transaction) { let catalogItem = { name: data.name, description: data.description, @@ -277,33 +274,33 @@ const _updateCatalogItem = async function (data, where, transaction) { ramRequired: data.ramRequired, picture: data.picture, isPublic: data.isPublic, - registryId: data.registryId - }; + registryId: data.registryId, + } - catalogItem = AppHelper.deleteUndefinedFields(catalogItem); + catalogItem = AppHelper.deleteUndefinedFields(catalogItem) if (!catalogItem || AppHelper.isEmpty(catalogItem)) { return } if (data.registryId) { - const registry = await RegistryManager.findOne({id: data.registryId}, transaction); + const registry = await RegistryManager.findOne({id: data.registryId}, transaction) if (!registry) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_REGISTRY_ID, data.registryId)); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_REGISTRY_ID, data.registryId)) } } - const item = await _checkIfItemExists(where, transaction); + const item = await _checkIfItemExists(where, transaction) - if (item.category === "SYSTEM"){ - throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.SYSTEM_CATALOG_ITEM_UPDATE, data.id)); + if (item.category === 'SYSTEM') { + throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.SYSTEM_CATALOG_ITEM_UPDATE, data.id)) } - await _checkForDuplicateName(data.name, item, transaction); - await CatalogItemManager.update(where, catalogItem, transaction); -}; + await _checkForDuplicateName(data.name, item, transaction) + await CatalogItemManager.update(where, catalogItem, transaction) +} -const _updateCatalogItemImages = async function (data, transaction) { +const _updateCatalogItemImages = async function(data, transaction) { if (data.images) { - const microservices = await MicroserviceManager.findAllWithStatuses({catalogItemId: data.id}, transaction); + const microservices = await MicroserviceManager.findAllWithStatuses({catalogItemId: data.id}, transaction) for (const ms of microservices) { if (ms.microserviceStatus.status === MicroseriveStates.RUNNING) { throw new Errors.ValidationError(ErrorMessages.CATALOG_ITEM_IMAGES_IS_FROZEN) @@ -313,39 +310,39 @@ const _updateCatalogItemImages = async function (data, transaction) { for (const image of data.images) { await CatalogItemImageManager.updateOrCreate({ catalogItemId: data.id, - fogTypeId: image.fogTypeId + fogTypeId: image.fogTypeId, }, { catalogItemId: data.id, fogTypeId: image.fogTypeId, - containerImage: image.containerImage - }, transaction); + containerImage: image.containerImage, + }, transaction) } } -}; +} -const _updateCatalogItemIOTypes = async function (data, where, transaction) { +const _updateCatalogItemIOTypes = async function(data, where, transaction) { if (data.inputType && data.inputType.length !== 0) { let inputType = { catalogItemId: data.id, infoType: data.inputType.infoType, - infoFormat: data.inputType.infoFormat - }; - inputType = AppHelper.deleteUndefinedFields(inputType); - await CatalogItemInputTypeManager.updateOrCreate({catalogItemId: data.id}, inputType, transaction); + infoFormat: data.inputType.infoFormat, + } + inputType = AppHelper.deleteUndefinedFields(inputType) + await CatalogItemInputTypeManager.updateOrCreate({catalogItemId: data.id}, inputType, transaction) } if (data.outputType && data.outputType.length !== 0) { let outputType = { catalogItemId: data.id, infoType: data.outputType.infoType, - infoFormat: data.outputType.infoFormat - }; - outputType = AppHelper.deleteUndefinedFields(outputType); - await CatalogItemOutputTypeManager.updateOrCreate({catalogItemId: data.id}, outputType, transaction); + infoFormat: data.outputType.infoFormat, + } + outputType = AppHelper.deleteUndefinedFields(outputType) + await CatalogItemOutputTypeManager.updateOrCreate({catalogItemId: data.id}, outputType, transaction) } -}; +} -//decorated functions -const createCatalogItemWithTracking = TrackingDecorator.trackEvent(createCatalogItem, TrackingEventType.CATALOG_CREATED); +// decorated functions +const createCatalogItemWithTracking = TrackingDecorator.trackEvent(createCatalogItem, TrackingEventType.CATALOG_CREATED) module.exports = { createCatalogItem: TransactionDecorator.generateTransaction(createCatalogItemWithTracking), @@ -355,5 +352,5 @@ module.exports = { updateCatalogItem: TransactionDecorator.generateTransaction(updateCatalogItem), getNetworkCatalogItem: getNetworkCatalogItem, getBluetoothCatalogItem: getBluetoothCatalogItem, - getHalCatalogItem: getHalCatalogItem -}; \ No newline at end of file + getHalCatalogItem: getHalCatalogItem, +} diff --git a/src/services/change-tracking-service.js b/src/services/change-tracking-service.js index 572043da6..337ad1353 100644 --- a/src/services/change-tracking-service.js +++ b/src/services/change-tracking-service.js @@ -11,7 +11,7 @@ * */ -const ChangeTrackingManager = require('../sequelize/managers/change-tracking-manager'); +const ChangeTrackingManager = require('../sequelize/managers/change-tracking-manager') const events = Object.freeze({ clean: { @@ -25,66 +25,66 @@ const events = Object.freeze({ registries: false, tunnel: false, diagnostics: false, - isImageSnapshot: false + isImageSnapshot: false, }, diagnostics: { - diagnostics: true + diagnostics: true, }, imageSnapshot: { - isImageSnapshot: true + isImageSnapshot: true, }, microserviceFull: { microserviceConfig: true, microserviceList: true, - routing: true + routing: true, }, microserviceCommon: { microserviceConfig: true, - microserviceList: true + microserviceList: true, }, microserviceList: { - microserviceList: true + microserviceList: true, }, microserviceConfig: { - microserviceConfig: true + microserviceConfig: true, }, microserviceRouting: { - routing: true + routing: true, }, version: { - version: true + version: true, }, reboot: { - reboot: true + reboot: true, }, deleteNode: { - deleteNode: true + deleteNode: true, }, registries: { - registries: true + registries: true, }, tunnel: { - tunnel: true + tunnel: true, }, config: { - config: true - } -}); + config: true, + }, +}) async function create(ioFogUuid, transaction) { - await ChangeTrackingManager.create({iofogUuid: ioFogUuid}, transaction); + await ChangeTrackingManager.create({iofogUuid: ioFogUuid}, transaction) } async function update(ioFogUuid, data, transaction) { - await ChangeTrackingManager.update({iofogUuid: ioFogUuid}, data, transaction); + await ChangeTrackingManager.update({iofogUuid: ioFogUuid}, data, transaction) } async function updateIfChanged(ioFogUuid, data, transaction) { - await ChangeTrackingManager.updateIfChanged({iofogUuid: ioFogUuid}, data, transaction); + await ChangeTrackingManager.updateIfChanged({iofogUuid: ioFogUuid}, data, transaction) } async function getByIoFogUuid(ioFogUuid, transaction) { - return await ChangeTrackingManager.findOne({iofogUuid: ioFogUuid}, transaction); + return await ChangeTrackingManager.findOne({iofogUuid: ioFogUuid}, transaction) } module.exports = { @@ -92,5 +92,5 @@ module.exports = { create: create, update: update, updateIfChanged: updateIfChanged, - getByIoFogUuid: getByIoFogUuid -}; \ No newline at end of file + getByIoFogUuid: getByIoFogUuid, +} diff --git a/src/services/connector-port-service.js b/src/services/connector-port-service.js index 235adf59e..29d841704 100644 --- a/src/services/connector-port-service.js +++ b/src/services/connector-port-service.js @@ -11,26 +11,26 @@ * */ -const ConnectorManager = require('../sequelize/managers/connector-manager'); -const https = require('https'); -const http = require('http'); -const constants = require('../helpers/constants'); -const logger = require('../logger'); -const qs = require('qs'); -const fs = require('fs'); +const ConnectorManager = require('../sequelize/managers/connector-manager') +const https = require('https') +const http = require('http') +const constants = require('../helpers/constants') +const logger = require('../logger') +const qs = require('qs') +const fs = require('fs') async function openPortOnRandomConnector(isPublicAccess, transaction) { - let isConnectorPortOpen = false; - let ports = null; - let connector = null; - const maxAttempts = 5; + let isConnectorPortOpen = false + let ports = null + let connector = null + const maxAttempts = 5 for (let i = 0; i < maxAttempts; i++) { try { - connector = await _getRandomConnector(transaction); - ports = await _openPortsOnConnector(connector, isPublicAccess); + connector = await _getRandomConnector(transaction) + ports = await _openPortsOnConnector(connector, isPublicAccess) if (ports) { - isConnectorPortOpen = true; - break; + isConnectorPortOpen = true + break } } catch (e) { logger.warn(`Failed to open ports on Connector. Attempts ${i + 1}/${maxAttempts}`) @@ -39,46 +39,47 @@ async function openPortOnRandomConnector(isPublicAccess, transaction) { if (!isConnectorPortOpen) { throw new Error('Not able to open port on remote Connector. Gave up after 5 attempts.') } - ports.connectorId = connector.id; + ports.connectorId = connector.id return {ports: ports, connector: connector} } async function _openPortsOnConnector(connector, isPublicAccess) { - let data = isPublicAccess + const data = isPublicAccess ? await qs.stringify({ - mapping: '{"type":"public","maxconnections":60,"heartbeatabsencethreshold":200000}' + mapping: '{"type":"public","maxconnections":60,"heartbeatabsencethreshold":200000}', }) : await qs.stringify({ mapping: '{"type":"private","maxconnectionsport1":1, "maxconnectionsport2":1, ' + - '"heartbeatabsencethresholdport1":200000, "heartbeatabsencethresholdport2":200000}' - }); + '"heartbeatabsencethresholdport1":200000, "heartbeatabsencethresholdport2":200000}', + }) - let port = connector.devMode ? constants.CONNECTOR_HTTP_PORT : constants.CONNECTOR_HTTPS_PORT; + const port = connector.devMode ? constants.CONNECTOR_HTTP_PORT : constants.CONNECTOR_HTTPS_PORT - let options = { + const options = { host: connector.domain, port: port, path: '/api/v2/mapping/add', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', - 'Content-Length': Buffer.byteLength(data) - } - }; + 'Content-Length': Buffer.byteLength(data), + }, + } if (!connector.devMode && connector.cert && connector.isSelfSignedCert === true) { - const ca = fs.readFileSync(connector.cert); - options.ca = new Buffer.from(ca); + const ca = fs.readFileSync(connector.cert) + /* eslint-disable new-cap */ + options.ca = new Buffer.from(ca) } - const ports = await _makeRequest(connector, options, data); + const ports = await _makeRequest(connector, options, data) return ports } async function _getRandomConnector(transaction) { - const connectors = await ConnectorManager.findAll({}, transaction); + const connectors = await ConnectorManager.findAll({}, transaction) if (connectors && connectors.length > 0) { - const randomNumber = Math.round((Math.random() * (connectors.length - 1))); + const randomNumber = Math.round((Math.random() * (connectors.length - 1))) return connectors[randomNumber] } else { throw new Error('no connectors defined') @@ -86,25 +87,26 @@ async function _getRandomConnector(transaction) { } async function closePortOnConnector(connector, ports) { - let data = qs.stringify({ - mappingid: ports.mappingId - }); + const data = qs.stringify({ + mappingid: ports.mappingId, + }) - let port = connector.devMode ? constants.CONNECTOR_HTTP_PORT : constants.CONNECTOR_HTTPS_PORT; + const port = connector.devMode ? constants.CONNECTOR_HTTP_PORT : constants.CONNECTOR_HTTPS_PORT - let options = { + const options = { host: connector.domain, port: port, path: '/api/v2/mapping/remove', method: 'POST', headers: { 'Content-Type': 'application/x-www-form-urlencoded', - 'Content-Length': Buffer.byteLength(data) - } - }; + 'Content-Length': Buffer.byteLength(data), + }, + } if (!connector.devMode && connector.cert && connector.isSelfSignedCert === true) { - const ca = fs.readFileSync(connector.cert); - options.ca = new Buffer.from(ca); + const ca = fs.readFileSync(connector.cert) + /* eslint-disable new-cap */ + options.ca = new Buffer.from(ca) } @@ -113,37 +115,38 @@ async function closePortOnConnector(connector, ports) { async function _makeRequest(connector, options, data) { return new Promise((resolve, reject) => { - let httpreq = (connector.devMode ? http : https).request(options, function (response) { - let output = ''; - response.setEncoding('utf8'); + const httpreq = (connector.devMode ? http : https).request(options, function(response) { + let output = '' + response.setEncoding('utf8') - response.on('data', function (chunk) { - output += chunk; - }); + response.on('data', function(chunk) { + output += chunk + }) - response.on('end', function () { - let responseObj = JSON.parse(output); + response.on('end', function() { + const responseObj = JSON.parse(output) if (responseObj.errormessage) { - return reject(new Error(responseObj.errormessage)); + return reject(new Error(responseObj.errormessage)) } else { - return resolve(responseObj); + return resolve(responseObj) } - }); - }); - - httpreq.on('error', function (err) { - if (err instanceof Error) - return reject(new Error(err.message)); - else - return reject(new Error(JSON.stringify(err))); - }); - - httpreq.write(data); - httpreq.end(); + }) + }) + + httpreq.on('error', function(err) { + if (err instanceof Error) { + return reject(new Error(err.message)) + } else { + return reject(new Error(JSON.stringify(err))) + } + }) + + httpreq.write(data) + httpreq.end() }) } module.exports = { openPortOnRandomConnector: openPortOnRandomConnector, - closePortOnConnector: closePortOnConnector -}; + closePortOnConnector: closePortOnConnector, +} diff --git a/src/services/connector-service.js b/src/services/connector-service.js index 1cb79b252..13defb83b 100644 --- a/src/services/connector-service.js +++ b/src/services/connector-service.js @@ -11,33 +11,33 @@ * */ -const TransactionDecorator = require('../decorators/transaction-decorator'); -const Validator = require('../schemas'); -const ConnectorManager = require('../sequelize/managers/connector-manager'); -const Errors = require('../helpers/errors'); -const ErrorMessages = require('../helpers/error-messages'); -const AppHelper = require('../helpers/app-helper'); -const Op = require('sequelize').Op; +const TransactionDecorator = require('../decorators/transaction-decorator') +const Validator = require('../schemas') +const ConnectorManager = require('../sequelize/managers/connector-manager') +const Errors = require('../helpers/errors') +const ErrorMessages = require('../helpers/error-messages') +const AppHelper = require('../helpers/app-helper') +const Op = require('sequelize').Op -const ConnectorPortManager = require('../sequelize/managers/connector-port-manager'); -const MicroserviceService = require('../services/microservices-service'); +const ConnectorPortManager = require('../sequelize/managers/connector-port-manager') +const MicroserviceService = require('../services/microservices-service') async function createConnector(connectorData, transaction) { - await Validator.validate(connectorData, Validator.schemas.connectorCreate); - _validateConnectorData(connectorData); + await Validator.validate(connectorData, Validator.schemas.connectorCreate) + _validateConnectorData(connectorData) const connector = await ConnectorManager.findOne({ [Op.or]: [ { - name: connectorData.name + name: connectorData.name, }, { - publicIp: connectorData.publicIp + publicIp: connectorData.publicIp, }, { - domain: connectorData.domain - } - ] - }, transaction); + domain: connectorData.domain, + }, + ], + }, transaction) if (connector) { throw new Errors.ValidationError(ErrorMessages.ALREADY_EXISTS) } @@ -45,39 +45,39 @@ async function createConnector(connectorData, transaction) { } async function updateConnector(connectorData, transaction) { - await Validator.validate(connectorData, Validator.schemas.connectorUpdate); - _validateConnectorData(connectorData); + await Validator.validate(connectorData, Validator.schemas.connectorUpdate) + _validateConnectorData(connectorData) const queryConnectorData = { - publicIp: connectorData.publicIp - }; + publicIp: connectorData.publicIp, + } const connector = await ConnectorManager.findOne({ - publicIp: connectorData.publicIp - }, transaction); + publicIp: connectorData.publicIp, + }, transaction) if (!connector) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_CONNECTOR_IP, connectorData.publicIp)) } - await ConnectorManager.update(queryConnectorData, connectorData, transaction); - const updatedConnector = await ConnectorManager.findOne({publicIp: connectorData.publicIp}, transaction); - await MicroserviceService.updateRouteOverConnector(updatedConnector, transaction); - await MicroserviceService.updatePortMappingOverConnector(updatedConnector, transaction); + await ConnectorManager.update(queryConnectorData, connectorData, transaction) + const updatedConnector = await ConnectorManager.findOne({publicIp: connectorData.publicIp}, transaction) + await MicroserviceService.updateRouteOverConnector(updatedConnector, transaction) + await MicroserviceService.updatePortMappingOverConnector(updatedConnector, transaction) } async function deleteConnector(connectorData, transaction) { - await Validator.validate(connectorData, Validator.schemas.connectorDelete); + await Validator.validate(connectorData, Validator.schemas.connectorDelete) const queryConnectorData = { - publicIp: connectorData.publicIp - }; - const connector = await ConnectorManager.findOne(queryConnectorData, transaction); + publicIp: connectorData.publicIp, + } + const connector = await ConnectorManager.findOne(queryConnectorData, transaction) if (!connector) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_CONNECTOR_IP, connectorData.publicIp)) } - const ports = await ConnectorPortManager.findAll({connectorId: connector.id}, transaction); + const ports = await ConnectorPortManager.findAll({connectorId: connector.id}, transaction) if (ports && ports.length > 0) { throw new Errors.ValidationError(ErrorMessages.CONNECTOR_IS_IN_USE) } - await ConnectorManager.delete(queryConnectorData, transaction); + await ConnectorManager.delete(queryConnectorData, transaction) } async function getConnectorList(transaction) { @@ -86,14 +86,14 @@ async function getConnectorList(transaction) { function _validateConnectorData(connectorData) { if (connectorData.domain) { - const validDomain = AppHelper.isValidDomain(connectorData.domain) || AppHelper.isValidPublicIP(connectorData.domain); + const validDomain = AppHelper.isValidDomain(connectorData.domain) || AppHelper.isValidPublicIP(connectorData.domain) if (!validDomain) { - throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_CONNECTOR_DOMAIN, connectorData.domain)); + throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_CONNECTOR_DOMAIN, connectorData.domain)) } } if (!AppHelper.isValidPublicIP(connectorData.publicIp)) { - throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_CONNECTOR_IP, connectorData.publicIp)); + throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_CONNECTOR_IP, connectorData.publicIp)) } } @@ -101,5 +101,5 @@ module.exports = { createConnector: TransactionDecorator.generateTransaction(createConnector), updateConnector: TransactionDecorator.generateTransaction(updateConnector), deleteConnector: TransactionDecorator.generateTransaction(deleteConnector), - getConnectorList: TransactionDecorator.generateTransaction(getConnectorList) -}; \ No newline at end of file + getConnectorList: TransactionDecorator.generateTransaction(getConnectorList), +} diff --git a/src/services/controller-service.js b/src/services/controller-service.js index 984f7eda3..f90ed0bac 100644 --- a/src/services/controller-service.js +++ b/src/services/controller-service.js @@ -11,40 +11,39 @@ * */ -const ioFogTypesManager = require('../sequelize/managers/iofog-type-manager'); -const Config = require('../config'); -const TransactionDecorator = require('../decorators/transaction-decorator'); -const packageJson = require('../../package'); -const AppHelper = require('../helpers/app-helper'); +const ioFogTypesManager = require('../sequelize/managers/iofog-type-manager') +const Config = require('../config') +const TransactionDecorator = require('../decorators/transaction-decorator') +const packageJson = require('../../package') +const AppHelper = require('../helpers/app-helper') -const getFogTypes = async function (isCLI, transaction) { - const ioFogTypes = await ioFogTypesManager.findAll({}, transaction); - let response = []; +const getFogTypes = async function(isCLI, transaction) { + const ioFogTypes = await ioFogTypesManager.findAll({}, transaction) + const response = [] for (ioFogType of ioFogTypes) { response.push({ id: ioFogType.id, name: ioFogType.name, image: ioFogType.image, - description: ioFogType.description + description: ioFogType.description, }) } return { - fogTypes: response + fogTypes: response, } +} -}; - -const emailActivation = async function (isCLI) { - const emailActivation = await Config.get('Email:ActivationEnabled'); +const emailActivation = async function(isCLI) { + const emailActivation = await Config.get('Email:ActivationEnabled') return { - isEmailActivationEnabled: emailActivation + isEmailActivationEnabled: emailActivation, } -}; +} -const statusController = async function (isCLI) { - let status; +const statusController = async function(isCLI) { + let status if (AppHelper.isOnline()) { status = 'online' @@ -53,18 +52,18 @@ const statusController = async function (isCLI) { } return { - "status": status, - "timestamp": Date.now(), + 'status': status, + 'timestamp': Date.now(), } -}; +} -const getVersion = async function (isCLI) { - return `ioFog-Controller version: ${packageJson.version}`; -}; +const getVersion = async function(isCLI) { + return `ioFog-Controller version: ${packageJson.version}` +} module.exports = { getFogTypes: TransactionDecorator.generateTransaction(getFogTypes), emailActivation: emailActivation, statusController: statusController, - getVersion: getVersion -}; \ No newline at end of file + getVersion: getVersion, +} diff --git a/src/services/diagnostic-service.js b/src/services/diagnostic-service.js index 368125344..bd560c0bc 100644 --- a/src/services/diagnostic-service.js +++ b/src/services/diagnostic-service.js @@ -11,242 +11,240 @@ * */ -const TransactionDecorator = require('../decorators/transaction-decorator'); -const AppHelper = require('../helpers/app-helper'); -const Errors = require('../helpers/errors'); -const ErrorMessages = require('../helpers/error-messages'); -const Validator = require('../schemas/index'); -const MicroserviceService = require('../services/microservices-service'); -const StraceDiagnosticManager = require('../sequelize/managers/strace-diagnostics-manager'); -const ChangeTrackingService = require('./change-tracking-service'); -const MicroserviceManager = require('../sequelize/managers/microservice-manager'); -const Config = require('../config'); -const fs = require('fs'); -const logger = require('../logger'); -const FtpClient = require('ftp'); -const mime = require('mime'); - - -const changeMicroserviceStraceState = async function (uuid, data, user, isCLI, transaction) { - await Validator.validate(data, Validator.schemas.straceStateUpdate); - const microservice = await MicroserviceService.getMicroservice(uuid, user, isCLI, transaction); +const TransactionDecorator = require('../decorators/transaction-decorator') +const AppHelper = require('../helpers/app-helper') +const Errors = require('../helpers/errors') +const ErrorMessages = require('../helpers/error-messages') +const Validator = require('../schemas/index') +const MicroserviceService = require('../services/microservices-service') +const StraceDiagnosticManager = require('../sequelize/managers/strace-diagnostics-manager') +const ChangeTrackingService = require('./change-tracking-service') +const MicroserviceManager = require('../sequelize/managers/microservice-manager') +const Config = require('../config') +const fs = require('fs') +const logger = require('../logger') +const FtpClient = require('ftp') +const mime = require('mime') + + +const changeMicroserviceStraceState = async function(uuid, data, user, isCLI, transaction) { + await Validator.validate(data, Validator.schemas.straceStateUpdate) + const microservice = await MicroserviceService.getMicroservice(uuid, user, isCLI, transaction) if (microservice.iofogUuid === null) { - throw new Errors.ValidationError(ErrorMessages.STRACE_WITHOUT_FOG); + throw new Errors.ValidationError(ErrorMessages.STRACE_WITHOUT_FOG) } const straceObj = { straceRun: data.enable, - microserviceUuid: uuid - }; + microserviceUuid: uuid, + } - await StraceDiagnosticManager.updateOrCreate({microserviceUuid: uuid}, straceObj, transaction); + await StraceDiagnosticManager.updateOrCreate({microserviceUuid: uuid}, straceObj, transaction) await ChangeTrackingService.update(microservice.iofogUuid, ChangeTrackingService.events.diagnostics, transaction) -}; +} -const getMicroserviceStraceData = async function (uuid, data, user, isCLI, transaction) { - await Validator.validate(data, Validator.schemas.straceGetData); +const getMicroserviceStraceData = async function(uuid, data, user, isCLI, transaction) { + await Validator.validate(data, Validator.schemas.straceGetData) const microserviceWhere = isCLI ? {uuid: uuid} - : {uuid: uuid, userId: user.id}; - const microservice = await MicroserviceManager.findOne(microserviceWhere, transaction); + : {uuid: uuid, userId: user.id} + const microservice = await MicroserviceManager.findOne(microserviceWhere, transaction) if (!microservice) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, uuid)) } - const straceData = await StraceDiagnosticManager.findOne({microserviceUuid: uuid}, transaction); + const straceData = await StraceDiagnosticManager.findOne({microserviceUuid: uuid}, transaction) if (!straceData) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_STRACE, uuid)) } - const dir = Config.get('Diagnostics:DiagnosticDir') || 'diagnostics'; - const filePath = dir + '/' + uuid; + const dir = Config.get('Diagnostics:DiagnosticDir') || 'diagnostics' + const filePath = dir + '/' + uuid - let result = straceData.buffer; + let result = straceData.buffer if (data.format === 'file') { - _createDirectoryIfNotExists(dir); - _writeBufferToFile(filePath, straceData.buffer); - result = _convertFileToBase64(filePath); - _deleteFile(filePath); + _createDirectoryIfNotExists(dir) + _writeBufferToFile(filePath, straceData.buffer) + result = _convertFileToBase64(filePath) + _deleteFile(filePath) } return { - data: result - }; -}; + data: result, + } +} -const postMicroserviceStraceDatatoFtp = async function (uuid, data, user, isCLI, transaction) { - await Validator.validate(data, Validator.schemas.stracePostToFtp); +const postMicroserviceStraceDatatoFtp = async function(uuid, data, user, isCLI, transaction) { + await Validator.validate(data, Validator.schemas.stracePostToFtp) const microserviceWhere = isCLI ? {uuid: uuid} - : {uuid: uuid, userId: user.id}; - const microservice = await MicroserviceManager.findOne(microserviceWhere, transaction); + : {uuid: uuid, userId: user.id} + const microservice = await MicroserviceManager.findOne(microserviceWhere, transaction) if (!microservice) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, uuid)) } - const straceData = await StraceDiagnosticManager.findOne({microserviceUuid: uuid}, transaction); + const straceData = await StraceDiagnosticManager.findOne({microserviceUuid: uuid}, transaction) if (!straceData) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_STRACE, uuid)) } - const dir = Config.get('Diagnostics:DiagnosticDir'); - const filePath = dir + '/' + uuid; + const dir = Config.get('Diagnostics:DiagnosticDir') + const filePath = dir + '/' + uuid - _createDirectoryIfNotExists(dir); - _writeBufferToFile(filePath, straceData.buffer); - await _sendFileToFtp(data, filePath); - _deleteFile(filePath); -}; + _createDirectoryIfNotExists(dir) + _writeBufferToFile(filePath, straceData.buffer) + await _sendFileToFtp(data, filePath) + _deleteFile(filePath) +} -const postMicroserviceImageSnapshotCreate = async function (microserviceUuid, user, isCLI, transaction) { +const postMicroserviceImageSnapshotCreate = async function(microserviceUuid, user, isCLI, transaction) { const where = isCLI ? { - uuid: microserviceUuid + uuid: microserviceUuid, } : { uuid: microserviceUuid, - userId: user.id - }; + userId: user.id, + } - const microservice = await MicroserviceManager.findOneWithDependencies(where, {}, transaction); + const microservice = await MicroserviceManager.findOneWithDependencies(where, {}, transaction) if (!microservice) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)) } if (microservice.iofogUuid === null) { - throw new Errors.ValidationError(ErrorMessages.IMAGE_SNAPSHOT_WITHOUT_FOG); + throw new Errors.ValidationError(ErrorMessages.IMAGE_SNAPSHOT_WITHOUT_FOG) } const microserviceToUpdate = { - imageSnapshot: 'get_image' - }; + imageSnapshot: 'get_image', + } - await MicroserviceManager.update({uuid: microservice.uuid}, microserviceToUpdate, transaction); - await ChangeTrackingService.update(microservice.iofogUuid, ChangeTrackingService.events.imageSnapshot, transaction); -}; + await MicroserviceManager.update({uuid: microservice.uuid}, microserviceToUpdate, transaction) + await ChangeTrackingService.update(microservice.iofogUuid, ChangeTrackingService.events.imageSnapshot, transaction) +} -const getMicroserviceImageSnapshot = async function (microserviceUuid, user, isCLI, transaction) { +const getMicroserviceImageSnapshot = async function(microserviceUuid, user, isCLI, transaction) { const where = isCLI ? { - uuid: microserviceUuid + uuid: microserviceUuid, } : { uuid: microserviceUuid, - userId: user.id - }; - const microservice = await MicroserviceManager.findOneWithDependencies(where, {}, transaction); + userId: user.id, + } + const microservice = await MicroserviceManager.findOneWithDependencies(where, {}, transaction) if (!microservice) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)) } if (microservice.iofogUuid === null) { - throw new Errors.ValidationError(ErrorMessages.IMAGE_SNAPSHOT_WITHOUT_FOG); + throw new Errors.ValidationError(ErrorMessages.IMAGE_SNAPSHOT_WITHOUT_FOG) } const microserviceToUpdate = { - imageSnapshot: '' - }; + imageSnapshot: '', + } if (!microservice.imageSnapshot || microservice.imageSnapshot === 'get_image') { throw new Errors.ValidationError(ErrorMessages.IMAGE_SNAPSHOT_NOT_AVAILABLE) } - let _path = microservice.imageSnapshot; - await MicroserviceManager.update({uuid: microservice.uuid}, microserviceToUpdate, transaction); + const _path = microservice.imageSnapshot + await MicroserviceManager.update({uuid: microservice.uuid}, microserviceToUpdate, transaction) if (isCLI) { return _path } else { - let mimetype = mime.lookup(microservice.imageSnapshot); - let stat = fs.statSync(_path); - let fileSize = stat.size; + const mimetype = mime.lookup(microservice.imageSnapshot) + const stat = fs.statSync(_path) + const fileSize = stat.size return { 'Content-Length': fileSize, 'Content-Type': mimetype, - fileName: _path.split(new RegExp('/'))[1], - filePath: _path - }; + 'fileName': _path.split(new RegExp('/'))[1], + 'filePath': _path, + } } +} -}; - -const _sendFileToFtp = async function (data, filePath) { - - const destDir = data.ftpDestDir; +const _sendFileToFtp = async function(data, filePath) { + const destDir = data.ftpDestDir const connectionData = { host: data.ftpHost, port: data.ftpPort, user: data.ftpUser, password: data.ftpPass, - protocol: 'ftp' - }; + protocol: 'ftp', + } - await writeFileToFtp(connectionData, filePath, destDir); -}; + await writeFileToFtp(connectionData, filePath, destDir) +} -const writeFileToFtp = function (connectionData, filePath, destDir) { +const writeFileToFtp = function(connectionData, filePath, destDir) { return new Promise((resolve, reject) => { - const client = new FtpClient(); + const client = new FtpClient() client.on('ready', () => { - client.put(filePath, destDir + '/' + filePath.split('/').pop(), err => { + client.put(filePath, destDir + '/' + filePath.split('/').pop(), (err) => { if (err) { - client.end(); - logger.warn(AppHelper.formatMessage(ErrorMessages.FTP_ERROR, err)); - reject(new Errors.FtpError(AppHelper.formatMessage(ErrorMessages.FTP_ERROR, err))); + client.end() + logger.warn(AppHelper.formatMessage(ErrorMessages.FTP_ERROR, err)) + reject(new Errors.FtpError(AppHelper.formatMessage(ErrorMessages.FTP_ERROR, err))) } else { - client.end(); - resolve(); + client.end() + resolve() } - }); - }); + }) + }) - client.on('error', err => { - logger.warn(AppHelper.formatMessage(ErrorMessages.FTP_ERROR, err)); - reject(new Errors.FtpError(AppHelper.formatMessage(ErrorMessages.FTP_ERROR, err))); - }); + client.on('error', (err) => { + logger.warn(AppHelper.formatMessage(ErrorMessages.FTP_ERROR, err)) + reject(new Errors.FtpError(AppHelper.formatMessage(ErrorMessages.FTP_ERROR, err))) + }) - client.connect(connectionData); + client.connect(connectionData) }) -}; +} -const _createDirectoryIfNotExists = function (dir) { +const _createDirectoryIfNotExists = function(dir) { if (!fs.existsSync(dir)) { - fs.mkdirSync(dir); + fs.mkdirSync(dir) } -}; - -const _writeBufferToFile = function (filePath, data) { +} +const _writeBufferToFile = function(filePath, data) { fs.writeFileSync(filePath, data, (err) => { if (err) { - throw new Error(AppHelper.formatMessage(ErrorMessages.UNABLE_TO_WRITE_STRACE, data, err)); + throw new Error(AppHelper.formatMessage(ErrorMessages.UNABLE_TO_WRITE_STRACE, data, err)) } - }); -}; + }) +} -const _convertFileToBase64 = function (filePath) { - const file = fs.readFileSync(filePath); - return new Buffer.from(file).toString('base64'); -}; +const _convertFileToBase64 = function(filePath) { + const file = fs.readFileSync(filePath) + /* eslint-disable new-cap */ + return new Buffer.from(file).toString('base64') +} -const _deleteFile = function (filePath) { +const _deleteFile = function(filePath) { fs.unlink(filePath, (err) => { if (err) { - logger.warn(AppHelper.formatMessage(ErrorMessages.UNABLE_TO_DELETE_STRACE, filePath, err)); + logger.warn(AppHelper.formatMessage(ErrorMessages.UNABLE_TO_DELETE_STRACE, filePath, err)) } - }); -}; + }) +} module.exports = { changeMicroserviceStraceState: TransactionDecorator.generateTransaction(changeMicroserviceStraceState), getMicroserviceStraceData: TransactionDecorator.generateTransaction(getMicroserviceStraceData), postMicroserviceStraceDatatoFtp: TransactionDecorator.generateTransaction(postMicroserviceStraceDatatoFtp), postMicroserviceImageSnapshotCreate: TransactionDecorator.generateTransaction(postMicroserviceImageSnapshotCreate), - getMicroserviceImageSnapshot: TransactionDecorator.generateTransaction(getMicroserviceImageSnapshot) + getMicroserviceImageSnapshot: TransactionDecorator.generateTransaction(getMicroserviceImageSnapshot), -}; \ No newline at end of file +} diff --git a/src/services/email-activation-code-service.js b/src/services/email-activation-code-service.js index a79709c91..680cb7a1f 100644 --- a/src/services/email-activation-code-service.js +++ b/src/services/email-activation-code-service.js @@ -11,52 +11,52 @@ * */ -const EmailActivationCodeManager = require('../sequelize/managers/email-activation-code-manager'); -const AppHelper = require('../helpers/app-helper'); -const ErrorMessages = require('../helpers/error-messages'); +const EmailActivationCodeManager = require('../sequelize/managers/email-activation-code-manager') +const AppHelper = require('../helpers/app-helper') +const ErrorMessages = require('../helpers/error-messages') -const generateActivationCode = async function (transaction) { +const generateActivationCode = async function(transaction) { while (true) { - const newActivationCode = AppHelper.generateRandomString(16); - const exists = await EmailActivationCodeManager.getByActivationCode(newActivationCode, transaction); + const newActivationCode = AppHelper.generateRandomString(16) + const exists = await EmailActivationCodeManager.getByActivationCode(newActivationCode, transaction) if (!exists) { - const activationCodeExpiryTime = new Date().getTime() + ((60 * 60 * 24 * 3) * 1000); + const activationCodeExpiryTime = new Date().getTime() + ((60 * 60 * 24 * 3) * 1000) return { activationCode: newActivationCode, - expirationTime: activationCodeExpiryTime + expirationTime: activationCodeExpiryTime, } } } -}; +} -const saveActivationCode = async function (userId, activationCodeData, transaction) { - const activationCode = activationCodeData.activationCode; - const expirationTime = activationCodeData.expirationTime; +const saveActivationCode = async function(userId, activationCodeData, transaction) { + const activationCode = activationCodeData.activationCode + const expirationTime = activationCodeData.expirationTime try { - return await EmailActivationCodeManager.createActivationCode(userId, activationCode, expirationTime, transaction); + return await EmailActivationCodeManager.createActivationCode(userId, activationCode, expirationTime, transaction) } catch (errMsg) { - throw new Error(ErrorMessages.UNABLE_TO_CREATE_ACTIVATION_CODE); + throw new Error(ErrorMessages.UNABLE_TO_CREATE_ACTIVATION_CODE) } -}; +} -const verifyActivationCode = async function (activationCode, transaction) { +const verifyActivationCode = async function(activationCode, transaction) { try { return await EmailActivationCodeManager.verifyActivationCode(activationCode, transaction) } catch (errMsg) { - throw new Error(ErrorMessages.UNABLE_TO_GET_ACTIVATION_CODE); + throw new Error(ErrorMessages.UNABLE_TO_GET_ACTIVATION_CODE) } -}; +} -const deleteActivationCode = async function (activationCode, transaction) { +const deleteActivationCode = async function(activationCode, transaction) { return await EmailActivationCodeManager.delete({ - activationCode: activationCode - }, transaction); -}; + activationCode: activationCode, + }, transaction) +} module.exports = { generateActivationCode: generateActivationCode, saveActivationCode: saveActivationCode, verifyActivationCode: verifyActivationCode, - deleteActivationCode: deleteActivationCode -}; \ No newline at end of file + deleteActivationCode: deleteActivationCode, +} diff --git a/src/services/flow-service.js b/src/services/flow-service.js index d5dae88cf..f4bbee326 100644 --- a/src/services/flow-service.js +++ b/src/services/flow-service.js @@ -11,140 +11,140 @@ * */ -const TransactionDecorator = require('../decorators/transaction-decorator'); -const FlowManager = require('../sequelize/managers/flow-manager'); -const AppHelper = require('../helpers/app-helper'); -const Errors = require('../helpers/errors'); -const ErrorMessages = require('../helpers/error-messages'); -const Validator = require('../schemas'); -const ChangeTrackingService = require('./change-tracking-service'); -const Sequelize = require('sequelize'); -const Op = Sequelize.Op; +const TransactionDecorator = require('../decorators/transaction-decorator') +const FlowManager = require('../sequelize/managers/flow-manager') +const AppHelper = require('../helpers/app-helper') +const Errors = require('../helpers/errors') +const ErrorMessages = require('../helpers/error-messages') +const Validator = require('../schemas') +const ChangeTrackingService = require('./change-tracking-service') +const Sequelize = require('sequelize') +const Op = Sequelize.Op -const createFlow = async function (flowData, user, isCLI, transaction) { - await Validator.validate(flowData, Validator.schemas.flowCreate); +const createFlow = async function(flowData, user, isCLI, transaction) { + await Validator.validate(flowData, Validator.schemas.flowCreate) - await _checkForDuplicateName(flowData.name, null, user.id, transaction); + await _checkForDuplicateName(flowData.name, null, user.id, transaction) const flowToCreate = { name: flowData.name, description: flowData.description, isActivated: flowData.isActivated, - userId: user.id - }; + userId: user.id, + } - const flowDataCreate = AppHelper.deleteUndefinedFields(flowToCreate); + const flowDataCreate = AppHelper.deleteUndefinedFields(flowToCreate) - const flow = await FlowManager.create(flowDataCreate, transaction); + const flow = await FlowManager.create(flowDataCreate, transaction) return { - id: flow.id + id: flow.id, } -}; +} -const deleteFlow = async function (flowId, user, isCLI, transaction) { +const deleteFlow = async function(flowId, user, isCLI, transaction) { const whereObj = { id: flowId, - userId: user.id - }; - const where = AppHelper.deleteUndefinedFields(whereObj); + userId: user.id, + } + const where = AppHelper.deleteUndefinedFields(whereObj) await _updateChangeTrackingsByFlowId(flowId, transaction) - await FlowManager.delete(where, transaction); -}; + await FlowManager.delete(where, transaction) +} -const updateFlow = async function (flowData, flowId, user, isCLI, transaction) { - await Validator.validate(flowData, Validator.schemas.flowUpdate); +const updateFlow = async function(flowData, flowId, user, isCLI, transaction) { + await Validator.validate(flowData, Validator.schemas.flowUpdate) - const oldFlow = await getFlow(flowId, user, isCLI, transaction); + const oldFlow = await getFlow(flowId, user, isCLI, transaction) if (!oldFlow) { throw new Errors.NotFoundError(ErrorMessages.INVALID_FLOW_ID) } if (flowData.name) { - await _checkForDuplicateName(flowData.name, flowId, user.id, transaction); + await _checkForDuplicateName(flowData.name, flowId, user.id, transaction) } const flow = { name: flowData.name, description: flowData.description, isActivated: flowData.isActivated, - }; + } - const updateFlowData = AppHelper.deleteUndefinedFields(flow); + const updateFlowData = AppHelper.deleteUndefinedFields(flow) const where = isCLI ? {id: flowId} - : {id: flowId, userId: user.id}; + : {id: flowId, userId: user.id} - await FlowManager.update(where, updateFlowData, transaction); + await FlowManager.update(where, updateFlowData, transaction) if (oldFlow.isActivated !== flowData.isActivated) { - await _updateChangeTrackingsByFlowId(flowId, transaction); + await _updateChangeTrackingsByFlowId(flowId, transaction) } -}; +} -const getUserFlows = async function (user, isCLI, transaction) { +const getUserFlows = async function(user, isCLI, transaction) { const flow = { - userId: user.id - }; + userId: user.id, + } - const attributes = {exclude: ["created_at", "updated_at"]}; - const flows = await FlowManager.findAllWithAttributes(flow, attributes, transaction); + const attributes = {exclude: ['created_at', 'updated_at']} + const flows = await FlowManager.findAllWithAttributes(flow, attributes, transaction) return { - flows: flows + flows: flows, } -}; +} -const getAllFlows = async function (isCLI, transaction) { - const attributes = {exclude: ['created_at', 'updated_at']}; - const flows = await FlowManager.findAllWithAttributes({}, attributes, transaction); +const getAllFlows = async function(isCLI, transaction) { + const attributes = {exclude: ['created_at', 'updated_at']} + const flows = await FlowManager.findAllWithAttributes({}, attributes, transaction) return { - flows: flows + flows: flows, } -}; +} -const getFlow = async function (flowId, user, isCLI, transaction) { +const getFlow = async function(flowId, user, isCLI, transaction) { const where = isCLI ? {id: flowId} - : {id: flowId, userId: user.id}; + : {id: flowId, userId: user.id} - const attributes = {exclude: ["created_at", "updated_at"]}; + const attributes = {exclude: ['created_at', 'updated_at']} - const flow = await FlowManager.findOneWithAttributes(where, attributes, transaction); + const flow = await FlowManager.findOneWithAttributes(where, attributes, transaction) if (!flow) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_FLOW_ID, flowId)) } return flow -}; +} -const _checkForDuplicateName = async function (name, flowId, userId, transaction) { +const _checkForDuplicateName = async function(name, flowId, userId, transaction) { if (name) { const where = flowId ? {name: name, userId: userId, id: {[Op.ne]: flowId}} - : {name: name, userId: userId}; + : {name: name, userId: userId} - const result = await FlowManager.findOne(where, transaction); + const result = await FlowManager.findOne(where, transaction) if (result) { - throw new Errors.DuplicatePropertyError(AppHelper.formatMessage(ErrorMessages.DUPLICATE_NAME, name)); + throw new Errors.DuplicatePropertyError(AppHelper.formatMessage(ErrorMessages.DUPLICATE_NAME, name)) } } -}; +} async function _updateChangeTrackingsByFlowId(flowId, transaction) { - const flowWithMicroservices = await FlowManager.findFlowMicroservices({id: flowId}, transaction); + const flowWithMicroservices = await FlowManager.findFlowMicroservices({id: flowId}, transaction) if (!flowWithMicroservices) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_FLOW_ID, flowId)); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_FLOW_ID, flowId)) } - const onlyUnique = (value, index, self) => self.indexOf(value) === index; + const onlyUnique = (value, index, self) => self.indexOf(value) === index const iofogUuids = flowWithMicroservices.microservices - .map(obj => obj.iofogUuid) - .filter(onlyUnique) - .filter(val => val !== null); + .map((obj) => obj.iofogUuid) + .filter(onlyUnique) + .filter((val) => val !== null) for (const iofogUuid of iofogUuids) { - await ChangeTrackingService.update(iofogUuid, ChangeTrackingService.events.microserviceFull, transaction); + await ChangeTrackingService.update(iofogUuid, ChangeTrackingService.events.microserviceFull, transaction) } } @@ -155,5 +155,5 @@ module.exports = { getUserFlows: TransactionDecorator.generateTransaction(getUserFlows), getAllFlows: TransactionDecorator.generateTransaction(getAllFlows), getFlowWithTransaction: TransactionDecorator.generateTransaction(getFlow), - getFlow: getFlow -}; + getFlow: getFlow, +} diff --git a/src/services/iofog-access-token-service.js b/src/services/iofog-access-token-service.js index 75031e466..f7237c80b 100644 --- a/src/services/iofog-access-token-service.js +++ b/src/services/iofog-access-token-service.js @@ -11,43 +11,43 @@ * */ -const AppHelper = require('../helpers/app-helper'); -const FogAccessTokenManager = require('../sequelize/managers/iofog-access-token-manager'); +const AppHelper = require('../helpers/app-helper') +const FogAccessTokenManager = require('../sequelize/managers/iofog-access-token-manager') -const Config = require('../config'); +const Config = require('../config') -const generateAccessToken = async function (transaction) { +const generateAccessToken = async function(transaction) { while (true) { - const newAccessToken = AppHelper.generateRandomString(16); + const newAccessToken = AppHelper.generateRandomString(16) const exists = await FogAccessTokenManager.findOne({ - token: newAccessToken - }, transaction); + token: newAccessToken, + }, transaction) if (!exists) { - const accessTokenExpiryTime = Date.now() + Config.get('Settings:FogTokenExpirationIntervalSeconds') * 1000; + const accessTokenExpiryTime = Date.now() + Config.get('Settings:FogTokenExpirationIntervalSeconds') * 1000 return { token: newAccessToken, - expirationTime: accessTokenExpiryTime + expirationTime: accessTokenExpiryTime, } } } -}; +} async function updateAccessToken(fogUuid, newAccessToken, transaction) { return FogAccessTokenManager.updateOrCreate({ - iofogUuid: fogUuid + iofogUuid: fogUuid, }, { iofogUuid: fogUuid, token: newAccessToken.token, - expirationTime: newAccessToken.expirationTime - }, transaction); + expirationTime: newAccessToken.expirationTime, + }, transaction) } async function all(transaction) { - return FogAccessTokenManager.findAll(null, transaction); + return FogAccessTokenManager.findAll(null, transaction) } module.exports = { generateAccessToken, updateAccessToken, all, -}; \ No newline at end of file +} diff --git a/src/services/iofog-service.js b/src/services/iofog-service.js index 58adf14a7..3bb9983e9 100644 --- a/src/services/iofog-service.js +++ b/src/services/iofog-service.js @@ -11,25 +11,25 @@ * */ -const TransactionDecorator = require('../decorators/transaction-decorator'); -const AppHelper = require('../helpers/app-helper'); -const FogManager = require('../sequelize/managers/iofog-manager'); -const FogProvisionKeyManager = require('../sequelize/managers/iofog-provision-key-manager'); -const FogVersionCommandManager = require('../sequelize/managers/iofog-version-command-manager'); -const ChangeTrackingService = require('./change-tracking-service'); -const Errors = require('../helpers/errors'); -const ErrorMessages = require('../helpers/error-messages'); -const Validator = require('../schemas'); -const HWInfoManager = require('../sequelize/managers/hw-info-manager'); -const USBInfoManager = require('../sequelize/managers/usb-info-manager'); -const CatalogService = require('../services/catalog-service'); -const MicroserviceManager = require('../sequelize/managers/microservice-manager'); -const FogStates = require('../enums/fog-state'); -const TrackingDecorator = require('../decorators/tracking-decorator'); -const TrackingEventType = require('../enums/tracking-event-type'); +const TransactionDecorator = require('../decorators/transaction-decorator') +const AppHelper = require('../helpers/app-helper') +const FogManager = require('../sequelize/managers/iofog-manager') +const FogProvisionKeyManager = require('../sequelize/managers/iofog-provision-key-manager') +const FogVersionCommandManager = require('../sequelize/managers/iofog-version-command-manager') +const ChangeTrackingService = require('./change-tracking-service') +const Errors = require('../helpers/errors') +const ErrorMessages = require('../helpers/error-messages') +const Validator = require('../schemas') +const HWInfoManager = require('../sequelize/managers/hw-info-manager') +const USBInfoManager = require('../sequelize/managers/usb-info-manager') +const CatalogService = require('../services/catalog-service') +const MicroserviceManager = require('../sequelize/managers/microservice-manager') +const FogStates = require('../enums/fog-state') +const TrackingDecorator = require('../decorators/tracking-decorator') +const TrackingEventType = require('../enums/tracking-event-type') async function createFog(fogData, user, isCLI, transaction) { - await Validator.validate(fogData, Validator.schemas.iofogCreate); + await Validator.validate(fogData, Validator.schemas.iofogCreate) let createFogData = { uuid: AppHelper.generateRandomString(32), @@ -54,37 +54,37 @@ async function createFog(fogData, user, isCLI, transaction) { watchdogEnabled: fogData.watchdogEnabled, abstractedHardwareEnabled: fogData.abstractedHardwareEnabled, fogTypeId: fogData.fogType, - userId: user.id - }; - createFogData = AppHelper.deleteUndefinedFields(createFogData); + userId: user.id, + } + createFogData = AppHelper.deleteUndefinedFields(createFogData) - const fog = await FogManager.create(createFogData, transaction); + const fog = await FogManager.create(createFogData, transaction) const res = { - uuid: fog.uuid - }; + uuid: fog.uuid, + } - await ChangeTrackingService.create(fog.uuid, transaction); + await ChangeTrackingService.create(fog.uuid, transaction) if (fogData.abstractedHardwareEnabled) { - await _createHalMicroserviceForFog(fog, null, user, transaction); + await _createHalMicroserviceForFog(fog, null, user, transaction) } if (fogData.bluetoothEnabled) { - await _createBluetoothMicroserviceForFog(fog, null, user, transaction); + await _createBluetoothMicroserviceForFog(fog, null, user, transaction) } - await ChangeTrackingService.update(createFogData.uuid, ChangeTrackingService.events.microserviceCommon, transaction); + await ChangeTrackingService.update(createFogData.uuid, ChangeTrackingService.events.microserviceCommon, transaction) return res } async function updateFog(fogData, user, isCLI, transaction) { - await Validator.validate(fogData, Validator.schemas.iofogUpdate); + await Validator.validate(fogData, Validator.schemas.iofogUpdate) const queryFogData = isCLI ? {uuid: fogData.uuid} - : {uuid: fogData.uuid, userId: user.id}; + : {uuid: fogData.uuid, userId: user.id} let updateFogData = { name: fogData.name, @@ -108,50 +108,50 @@ async function updateFog(fogData, user, isCLI, transaction) { watchdogEnabled: fogData.watchdogEnabled, abstractedHardwareEnabled: fogData.abstractedHardwareEnabled, fogTypeId: fogData.fogType, - }; - updateFogData = AppHelper.deleteUndefinedFields(updateFogData); + } + updateFogData = AppHelper.deleteUndefinedFields(updateFogData) - const oldFog = await FogManager.findOne(queryFogData, transaction); + const oldFog = await FogManager.findOne(queryFogData, transaction) if (!oldFog) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_IOFOG_UUID, fogData.uuid)) } - await FogManager.update(queryFogData, updateFogData, transaction); - await ChangeTrackingService.update(fogData.uuid, ChangeTrackingService.events.config, transaction); + await FogManager.update(queryFogData, updateFogData, transaction) + await ChangeTrackingService.update(fogData.uuid, ChangeTrackingService.events.config, transaction) - let msChanged = false; + let msChanged = false if (oldFog.abstractedHardwareEnabled === true && fogData.abstractedHardwareEnabled === false) { - await _deleteHalMicroserviceByFog(fogData, transaction); - msChanged = true; + await _deleteHalMicroserviceByFog(fogData, transaction) + msChanged = true } if (oldFog.abstractedHardwareEnabled === false && fogData.abstractedHardwareEnabled === true) { - await _createHalMicroserviceForFog(fogData, oldFog, user, transaction); - msChanged = true; + await _createHalMicroserviceForFog(fogData, oldFog, user, transaction) + msChanged = true } if (oldFog.bluetoothEnabled === true && fogData.bluetoothEnabled === false) { - await _deleteBluetoothMicroserviceByFog(fogData, transaction); - msChanged = true; + await _deleteBluetoothMicroserviceByFog(fogData, transaction) + msChanged = true } if (oldFog.bluetoothEnabled === false && fogData.bluetoothEnabled === true) { - await _createBluetoothMicroserviceForFog(fogData, oldFog, user, transaction); - msChanged = true; + await _createBluetoothMicroserviceForFog(fogData, oldFog, user, transaction) + msChanged = true } if (msChanged) { - await ChangeTrackingService.update(fogData.uuid, ChangeTrackingService.events.microserviceCommon, transaction); + await ChangeTrackingService.update(fogData.uuid, ChangeTrackingService.events.microserviceCommon, transaction) } } async function deleteFog(fogData, user, isCLI, transaction) { - await Validator.validate(fogData, Validator.schemas.iofogDelete); + await Validator.validate(fogData, Validator.schemas.iofogDelete) const queryFogData = isCLI ? {uuid: fogData.uuid} - : {uuid: fogData.uuid, userId: user.id}; + : {uuid: fogData.uuid, userId: user.id} - const fog = await FogManager.findOne(queryFogData, transaction); + const fog = await FogManager.findOne(queryFogData, transaction) if (!fog) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_IOFOG_UUID, fogData.uuid)) } @@ -159,13 +159,13 @@ async function deleteFog(fogData, user, isCLI, transaction) { } async function getFog(fogData, user, isCLI, transaction) { - await Validator.validate(fogData, Validator.schemas.iofogGet); + await Validator.validate(fogData, Validator.schemas.iofogGet) const queryFogData = isCLI ? {uuid: fogData.uuid} - : {uuid: fogData.uuid, userId: user.id}; + : {uuid: fogData.uuid, userId: user.id} - const fog = await FogManager.findOne(queryFogData, transaction); + const fog = await FogManager.findOne(queryFogData, transaction) if (!fog) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_IOFOG_UUID, fogData.uuid)) } @@ -218,63 +218,63 @@ async function getFog(fogData, user, isCLI, transaction) { tunnel: fog.tunnel, watchdogEnabled: fog.watchdogEnabled, fogTypeId: fog.fogTypeId, - userId: fog.userId - }; + userId: fog.userId, + } } async function getFogList(filters, user, isCLI, transaction) { - await Validator.validate(filters, Validator.schemas.iofogFilters); + await Validator.validate(filters, Validator.schemas.iofogFilters) const queryFogData = isCLI ? {} - : {userId: user.id}; + : {userId: user.id} - let fogs = await FogManager.findAll(queryFogData, transaction); - fogs = _filterFogs(fogs, filters); + let fogs = await FogManager.findAll(queryFogData, transaction) + fogs = _filterFogs(fogs, filters) return { - fogs: fogs + fogs: fogs, } } async function generateProvisioningKey(fogData, user, isCLI, transaction) { - await Validator.validate(fogData, Validator.schemas.iofogGenerateProvision); + await Validator.validate(fogData, Validator.schemas.iofogGenerateProvision) const queryFogData = isCLI ? {uuid: fogData.uuid} - : {uuid: fogData.uuid, userId: user.id}; + : {uuid: fogData.uuid, userId: user.id} const newProvision = { iofogUuid: fogData.uuid, provisionKey: AppHelper.generateRandomString(8), - expirationTime: new Date().getTime() + (20 * 60 * 1000) - }; + expirationTime: new Date().getTime() + (20 * 60 * 1000), + } - const fog = await FogManager.findOne(queryFogData, transaction); + const fog = await FogManager.findOne(queryFogData, transaction) if (!fog) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_IOFOG_UUID, fogData.uuid)) } - const provisioningKeyData = await FogProvisionKeyManager.updateOrCreate({iofogUuid: fogData.uuid}, newProvision, transaction); + const provisioningKeyData = await FogProvisionKeyManager.updateOrCreate({iofogUuid: fogData.uuid}, newProvision, transaction) return { key: provisioningKeyData.provisionKey, - expirationTime: provisioningKeyData.expirationTime + expirationTime: provisioningKeyData.expirationTime, } } async function setFogVersionCommand(fogVersionData, user, isCLI, transaction) { - await Validator.validate(fogVersionData, Validator.schemas.iofogSetVersionCommand); + await Validator.validate(fogVersionData, Validator.schemas.iofogSetVersionCommand) const queryFogData = isCLI ? {uuid: fogVersionData.uuid} - : {uuid: fogVersionData.uuid, userId: user.id}; + : {uuid: fogVersionData.uuid, userId: user.id} const newVersionCommand = { iofogUuid: fogVersionData.uuid, - versionCommand: fogVersionData.versionCommand - }; + versionCommand: fogVersionData.versionCommand, + } - const fog = await FogManager.findOne(queryFogData, transaction); + const fog = await FogManager.findOne(queryFogData, transaction) if (!fog) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_IOFOG_UUID, fogData.uuid)) } @@ -286,19 +286,19 @@ async function setFogVersionCommand(fogVersionData, user, isCLI, transaction) { throw new Errors.ValidationError(ErrorMessages.INVALID_VERSION_COMMAND_UPGRADE) } - await generateProvisioningKey({uuid: fogVersionData.uuid}, user, isCLI, transaction); - await FogVersionCommandManager.updateOrCreate({iofogUuid: fogVersionData.uuid}, newVersionCommand, transaction); + await generateProvisioningKey({uuid: fogVersionData.uuid}, user, isCLI, transaction) + await FogVersionCommandManager.updateOrCreate({iofogUuid: fogVersionData.uuid}, newVersionCommand, transaction) await ChangeTrackingService.update(fogVersionData.uuid, ChangeTrackingService.events.version, transaction) } async function setFogRebootCommand(fogData, user, isCLI, transaction) { - await Validator.validate(fogData, Validator.schemas.iofogReboot); + await Validator.validate(fogData, Validator.schemas.iofogReboot) const queryFogData = isCLI ? {uuid: fogData.uuid} - : {uuid: fogData.uuid, userId: user.id}; + : {uuid: fogData.uuid, userId: user.id} - const fog = await FogManager.findOne(queryFogData, transaction); + const fog = await FogManager.findOne(queryFogData, transaction) if (!fog) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_IOFOG_UUID, fogData.uuid)) } @@ -307,33 +307,33 @@ async function setFogRebootCommand(fogData, user, isCLI, transaction) { } async function getHalHardwareInfo(uuidObj, user, isCLI, transaction) { - await Validator.validate(uuidObj, Validator.schemas.halGet); + await Validator.validate(uuidObj, Validator.schemas.halGet) const fog = await FogManager.findOne({ - uuid: uuidObj.uuid - }, transaction); + uuid: uuidObj.uuid, + }, transaction) if (!fog) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_IOFOG_UUID, uuidObj.uuid)); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_IOFOG_UUID, uuidObj.uuid)) } return await HWInfoManager.findOne({ - iofogUuid: uuidObj.uuid - }, transaction); + iofogUuid: uuidObj.uuid, + }, transaction) } async function getHalUsbInfo(uuidObj, user, isCLI, transaction) { - await Validator.validate(uuidObj, Validator.schemas.halGet); + await Validator.validate(uuidObj, Validator.schemas.halGet) const fog = await FogManager.findOne({ - uuid: uuidObj.uuid - }, transaction); + uuid: uuidObj.uuid, + }, transaction) if (!fog) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_IOFOG_UUID, uuidObj.uuid)); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_IOFOG_UUID, uuidObj.uuid)) } return await USBInfoManager.findOne({ - iofogUuid: uuidObj.uuid - }, transaction); + iofogUuid: uuidObj.uuid, + }, transaction) } function _filterFogs(fogs, filters) { @@ -341,24 +341,24 @@ function _filterFogs(fogs, filters) { return fogs } - const filtered = []; + const filtered = [] fogs.forEach((fog) => { - let isMatchFog = true; + let isMatchFog = true filters.some((filter) => { - let fld = filter.key, - val = filter.value, - condition = filter.condition; - let isMatchField = (condition === 'equals' && fog[fld] && fog[fld] === val) - || (condition === 'has' && fog[fld] && fog[fld].includes(val)); + const fld = filter.key + const val = filter.value + const condition = filter.condition + const isMatchField = (condition === 'equals' && fog[fld] && fog[fld] === val) + || (condition === 'has' && fog[fld] && fog[fld].includes(val)) if (!isMatchField) { - isMatchFog = false; + isMatchFog = false return false } - }); + }) if (isMatchFog) { filtered.push(fog) } - }); + }) return filtered } @@ -371,7 +371,7 @@ async function _processDeleteCommand(fog, transaction) { } async function _createHalMicroserviceForFog(fogData, oldFog, user, transaction) { - const halItem = await CatalogService.getHalCatalogItem(transaction); + const halItem = await CatalogService.getHalCatalogItem(transaction) const halMicroserviceData = { uuid: AppHelper.generateRandomString(32), @@ -382,24 +382,24 @@ async function _createHalMicroserviceForFog(fogData, oldFog, user, transaction) rootHostAccess: true, logSize: 50, userId: oldFog ? oldFog.userId : user.id, - configLastUpdated: Date.now() - }; + configLastUpdated: Date.now(), + } - await MicroserviceManager.create(halMicroserviceData, transaction); + await MicroserviceManager.create(halMicroserviceData, transaction) } async function _deleteHalMicroserviceByFog(fogData, transaction) { - const halItem = await CatalogService.getHalCatalogItem(transaction); + const halItem = await CatalogService.getHalCatalogItem(transaction) const deleteHalMicroserviceData = { iofogUuid: fogData.uuid, - catalogItemId: halItem.id - }; + catalogItemId: halItem.id, + } await MicroserviceManager.delete(deleteHalMicroserviceData, transaction) } async function _createBluetoothMicroserviceForFog(fogData, oldFog, user, transaction) { - const bluetoothItem = await CatalogService.getBluetoothCatalogItem(transaction); + const bluetoothItem = await CatalogService.getBluetoothCatalogItem(transaction) const bluetoothMicroserviceData = { uuid: AppHelper.generateRandomString(32), @@ -410,24 +410,24 @@ async function _createBluetoothMicroserviceForFog(fogData, oldFog, user, transac rootHostAccess: true, logSize: 50, userId: oldFog ? oldFog.userId : user.id, - configLastUpdated: Date.now() - }; + configLastUpdated: Date.now(), + } - await MicroserviceManager.create(bluetoothMicroserviceData, transaction); + await MicroserviceManager.create(bluetoothMicroserviceData, transaction) } async function _deleteBluetoothMicroserviceByFog(fogData, transaction) { - const bluetoothItem = await CatalogService.getBluetoothCatalogItem(transaction); + const bluetoothItem = await CatalogService.getBluetoothCatalogItem(transaction) const deleteBluetoothMicroserviceData = { iofogUuid: fogData.uuid, - catalogItemId: bluetoothItem.id - }; + catalogItemId: bluetoothItem.id, + } await MicroserviceManager.delete(deleteBluetoothMicroserviceData, transaction) } -//decorated functions -const createFogWithTracking = TrackingDecorator.trackEvent(createFog, TrackingEventType.IOFOG_CREATED); +// decorated functions +const createFogWithTracking = TrackingDecorator.trackEvent(createFog, TrackingEventType.IOFOG_CREATED) module.exports = { createFog: TransactionDecorator.generateTransaction(createFogWithTracking), @@ -440,5 +440,5 @@ module.exports = { setFogRebootCommand: TransactionDecorator.generateTransaction(setFogRebootCommand), getHalHardwareInfo: TransactionDecorator.generateTransaction(getHalHardwareInfo), getHalUsbInfo: TransactionDecorator.generateTransaction(getHalUsbInfo), - getFog: getFog -}; \ No newline at end of file + getFog: getFog, +} diff --git a/src/services/microservices-service.js b/src/services/microservices-service.js index 15f1e5bdf..47235934a 100644 --- a/src/services/microservices-service.js +++ b/src/services/microservices-service.js @@ -11,126 +11,130 @@ * */ -const logger = require('../logger'); -const TransactionDecorator = require('../decorators/transaction-decorator'); -const MicroserviceManager = require('../sequelize/managers/microservice-manager'); -const MicroserviceStatusManager = require('../sequelize/managers/microservice-status-manager'); -const MicroservicePortManager = require('../sequelize/managers/microservice-port-manager'); -const MicroserviceStates = require('../enums/microservice-state'); -const VolumeMappingManager = require('../sequelize/managers/volume-mapping-manager'); -const ConnectorManager = require('../sequelize/managers/connector-manager'); -const ConnectorPortManager = require('../sequelize/managers/connector-port-manager'); -const MicroservicePublicModeManager = require('../sequelize/managers/microservice-public-mode-manager'); -const ChangeTrackingService = require('./change-tracking-service'); -const ConnectorPortService = require('./connector-port-service'); -const IoFogService = require('../services/iofog-service'); -const AppHelper = require('../helpers/app-helper'); -const Errors = require('../helpers/errors'); -const ErrorMessages = require('../helpers/error-messages'); -const Validator = require('../schemas/index'); -const FlowService = require('../services/flow-service'); -const CatalogService = require('../services/catalog-service'); -const RoutingManager = require('../sequelize/managers/routing-manager'); -const Op = require('sequelize').Op; -const fs = require('fs'); -const _ = require('underscore'); -const TrackingDecorator = require('../decorators/tracking-decorator'); -const TrackingEventType = require('../enums/tracking-event-type'); +const logger = require('../logger') +const TransactionDecorator = require('../decorators/transaction-decorator') +const MicroserviceManager = require('../sequelize/managers/microservice-manager') +const MicroserviceStatusManager = require('../sequelize/managers/microservice-status-manager') +const MicroservicePortManager = require('../sequelize/managers/microservice-port-manager') +const MicroserviceStates = require('../enums/microservice-state') +const VolumeMappingManager = require('../sequelize/managers/volume-mapping-manager') +const ConnectorManager = require('../sequelize/managers/connector-manager') +const ConnectorPortManager = require('../sequelize/managers/connector-port-manager') +const MicroservicePublicModeManager = require('../sequelize/managers/microservice-public-mode-manager') +const ChangeTrackingService = require('./change-tracking-service') +const ConnectorPortService = require('./connector-port-service') +const IoFogService = require('../services/iofog-service') +const AppHelper = require('../helpers/app-helper') +const Errors = require('../helpers/errors') +const ErrorMessages = require('../helpers/error-messages') +const Validator = require('../schemas/index') +const FlowService = require('../services/flow-service') +const CatalogService = require('../services/catalog-service') +const RoutingManager = require('../sequelize/managers/routing-manager') +const Op = require('sequelize').Op +const fs = require('fs') +const _ = require('underscore') +const TrackingDecorator = require('../decorators/tracking-decorator') +const TrackingEventType = require('../enums/tracking-event-type') async function listMicroservices(flowId, user, isCLI, transaction) { if (!isCLI) { - await FlowService.getFlow(flowId, user, isCLI, transaction); + await FlowService.getFlow(flowId, user, isCLI, transaction) } - const where = isCLI ? {delete: false} : {flowId: flowId, delete: false}; + const where = isCLI ? {delete: false} : {flowId: flowId, delete: false} - const microservices = await MicroserviceManager.findAllExcludeFields(where, transaction); + const microservices = await MicroserviceManager.findAllExcludeFields(where, transaction) const res = await Promise.all(microservices.map(async (microservice) => { - const microserviceUuid = microservice.uuid; - const portMappings = await MicroservicePortManager.findAll({microserviceUuid: microserviceUuid}, transaction); - const volumeMappings = await VolumeMappingManager.findAll({microserviceUuid: microserviceUuid}, transaction); - const routes = await RoutingManager.findAll({sourceMicroserviceUuid: microserviceUuid}, transaction); - - const fullMs = Object.assign({}, microservice.dataValues); - fullMs.ports = portMappings.map((pm) => {return {internal: pm.portInternal, external: pm.portExternal, publicMode: pm.isPublic}}); - fullMs.volumeMappings = volumeMappings.map(vm => vm.dataValues); - fullMs.routes = routes.map(r => r.destMicroserviceUuid); - - return fullMs; - })); + const microserviceUuid = microservice.uuid + const portMappings = await MicroservicePortManager.findAll({microserviceUuid: microserviceUuid}, transaction) + const volumeMappings = await VolumeMappingManager.findAll({microserviceUuid: microserviceUuid}, transaction) + const routes = await RoutingManager.findAll({sourceMicroserviceUuid: microserviceUuid}, transaction) + + const fullMs = Object.assign({}, microservice.dataValues) + fullMs.ports = portMappings.map((pm) => { + return {internal: pm.portInternal, external: pm.portExternal, publicMode: pm.isPublic} + }) + fullMs.volumeMappings = volumeMappings.map((vm) => vm.dataValues) + fullMs.routes = routes.map((r) => r.destMicroserviceUuid) + + return fullMs + })) return { - microservices: res + microservices: res, } } async function getMicroservice(microserviceUuid, user, isCLI, transaction) { if (!isCLI) { - await _validateMicroserviceOnGet(user.id, microserviceUuid, transaction); + await _validateMicroserviceOnGet(user.id, microserviceUuid, transaction) } const microservice = await MicroserviceManager.findOneExcludeFields({ - uuid: microserviceUuid, delete: false - }, transaction); + uuid: microserviceUuid, delete: false, + }, transaction) if (!microservice) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)) } - const portMappings = await MicroservicePortManager.findAll({microserviceUuid: microserviceUuid}, transaction); - const volumeMappings = await VolumeMappingManager.findAll({microserviceUuid: microserviceUuid}, transaction); - const routes = await RoutingManager.findAll({sourceMicroserviceUuid: microserviceUuid}, transaction); + const portMappings = await MicroservicePortManager.findAll({microserviceUuid: microserviceUuid}, transaction) + const volumeMappings = await VolumeMappingManager.findAll({microserviceUuid: microserviceUuid}, transaction) + const routes = await RoutingManager.findAll({sourceMicroserviceUuid: microserviceUuid}, transaction) - const res = Object.assign({}, microservice.dataValues); - res.ports = portMappings.map((pm) => {return {internal: pm.portInternal, external: pm.portExternal, publicMode: pm.isPublic}}); - res.volumeMappings = volumeMappings.map(vm => vm.dataValues); - res.routes = routes.map(r => r.destMicroserviceUuid); - return res; + const res = Object.assign({}, microservice.dataValues) + res.ports = portMappings.map((pm) => { + return {internal: pm.portInternal, external: pm.portExternal, publicMode: pm.isPublic} + }) + res.volumeMappings = volumeMappings.map((vm) => vm.dataValues) + res.routes = routes.map((r) => r.destMicroserviceUuid) + return res } async function createMicroservice(microserviceData, user, isCLI, transaction) { - await Validator.validate(microserviceData, Validator.schemas.microserviceCreate); + await Validator.validate(microserviceData, Validator.schemas.microserviceCreate) - const microservice = await _createMicroservice(microserviceData, user, isCLI, transaction); + const microservice = await _createMicroservice(microserviceData, user, isCLI, transaction) if (microserviceData.ports) { for (const port of microserviceData.ports) { - await createPortMapping(microservice.uuid, port, user, isCLI, transaction); + await createPortMapping(microservice.uuid, port, user, isCLI, transaction) } } if (microserviceData.volumeMappings) { - await _createVolumeMappings(microserviceData.volumeMappings, microservice.uuid, transaction); + await _createVolumeMappings(microserviceData.volumeMappings, microservice.uuid, transaction) } if (microserviceData.routes) { - await _createRoutes(microserviceData.routes, microservice.uuid, user, transaction); + await _createRoutes(microserviceData.routes, microservice.uuid, user, transaction) } if (microserviceData.iofogUuid) { - await _updateChangeTracking(false, microserviceData.iofogUuid, transaction); + await _updateChangeTracking(false, microserviceData.iofogUuid, transaction) } - await _createMicroserviceStatus(microservice.uuid, transaction); + await _createMicroserviceStatus(microservice.uuid, transaction) return { - uuid: microservice.uuid + uuid: microservice.uuid, } } async function updateMicroservice(microserviceUuid, microserviceData, user, isCLI, transaction) { - await Validator.validate(microserviceData, Validator.schemas.microserviceUpdate); + await Validator.validate(microserviceData, Validator.schemas.microserviceUpdate) const query = isCLI ? { - uuid: microserviceUuid + uuid: microserviceUuid, } : { uuid: microserviceUuid, - userId: user.id - }; + userId: user.id, + } - const config = _validateMicroserviceConfig(microserviceData.config); + const config = _validateMicroserviceConfig(microserviceData.config) const microserviceToUpdate = { name: microserviceData.name, @@ -139,54 +143,54 @@ async function updateMicroservice(microserviceUuid, microserviceData, user, isCL iofogUuid: microserviceData.iofogUuid, rootHostAccess: microserviceData.rootHostAccess, logSize: microserviceData.logLimit, - volumeMappings: microserviceData.volumeMappings - }; + volumeMappings: microserviceData.volumeMappings, + } - const microserviceDataUpdate = AppHelper.deleteUndefinedFields(microserviceToUpdate); + const microserviceDataUpdate = AppHelper.deleteUndefinedFields(microserviceToUpdate) - const microservice = await MicroserviceManager.findOneWithCategory(query, transaction); + const microservice = await MicroserviceManager.findOneWithCategory(query, transaction) if (!microservice) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)) } - if (microservice.catalogItem.category === "SYSTEM") { + if (microservice.catalogItem.category === 'SYSTEM') { throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.SYSTEM_MICROSERVICE_UPDATE, microserviceUuid)) } if (microserviceDataUpdate.name) { - const userId = isCLI ? microservice.userId : user.id; - await _checkForDuplicateName(microserviceDataUpdate.name, {id: microserviceUuid}, userId, transaction); + const userId = isCLI ? microservice.userId : user.id + await _checkForDuplicateName(microserviceDataUpdate.name, {id: microserviceUuid}, userId, transaction) } - //validate fog node + // validate fog node if (microserviceDataUpdate.iofogUuid) { - await IoFogService.getFog({uuid: microserviceDataUpdate.iofogUuid}, user, isCLI, transaction); + await IoFogService.getFog({uuid: microserviceDataUpdate.iofogUuid}, user, isCLI, transaction) } - await MicroserviceManager.update(query, microserviceDataUpdate, transaction); + await MicroserviceManager.update(query, microserviceDataUpdate, transaction) if (microserviceDataUpdate.volumeMappings) { - await _updateVolumeMappings(microserviceDataUpdate.volumeMappings, microserviceUuid, transaction); + await _updateVolumeMappings(microserviceDataUpdate.volumeMappings, microserviceUuid, transaction) } if (microserviceDataUpdate.iofogUuid && microserviceDataUpdate.iofogUuid !== microservice.iofogUuid) { - const routes = await _getLogicalNetworkRoutesByFog(microservice.iofogUuid, transaction); - for (let route of routes) { - await deleteRoute(route.sourceMicroserviceUuid, route.destMicroserviceUuid, user, isCLI, transaction); - await createRoute(route.sourceMicroserviceUuid, route.destMicroserviceUuid, user, isCLI, transaction); - //update change tracking for another fog in route + const routes = await _getLogicalNetworkRoutesByFog(microservice.iofogUuid, transaction) + for (const route of routes) { + await deleteRoute(route.sourceMicroserviceUuid, route.destMicroserviceUuid, user, isCLI, transaction) + await createRoute(route.sourceMicroserviceUuid, route.destMicroserviceUuid, user, isCLI, transaction) + // update change tracking for another fog in route if (microservice.iofogUuid === route.sourceIofogUuid) { - await _updateChangeTracking(false, route.destIofogUuid, transaction); + await _updateChangeTracking(false, route.destIofogUuid, transaction) } else if (microservice.iofogUuid === route.destIofogUuid) { - await _updateChangeTracking(false, route.sourceIofogUuid, transaction); + await _updateChangeTracking(false, route.sourceIofogUuid, transaction) } } - //update change tracking for old fog - await _updateChangeTracking(false, microservice.iofogUuid, transaction); + // update change tracking for old fog + await _updateChangeTracking(false, microservice.iofogUuid, transaction) } - //update change tracking for new fog - await _updateChangeTracking(!!microserviceData.config, microserviceDataUpdate.iofogUuid, transaction); + // update change tracking for new fog + await _updateChangeTracking(!!microserviceData.config, microserviceDataUpdate.iofogUuid, transaction) } async function deleteMicroservice(microserviceUuid, microserviceData, user, isCLI, transaction) { @@ -198,55 +202,55 @@ async function deleteMicroservice(microserviceUuid, microserviceData, user, isCL : { uuid: microserviceUuid, - userId: user.id - }; + userId: user.id, + } - const microservice = await MicroserviceManager.findOneWithStatusAndCategory(where, transaction); + const microservice = await MicroserviceManager.findOneWithStatusAndCategory(where, transaction) if (!microservice) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)) } - if (!isCLI && microservice.catalogItem.category === "SYSTEM") { + if (!isCLI && microservice.catalogItem.category === 'SYSTEM') { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.SYSTEM_MICROSERVICE_DELETE, microserviceUuid)) } if (!microservice.microserviceStatus || microservice.microserviceStatus.status === MicroserviceStates.NOT_RUNNING) { - await deleteMicroserviceWithRoutesAndPortMappings(microserviceUuid, transaction); + await deleteMicroserviceWithRoutesAndPortMappings(microserviceUuid, transaction) } else { await MicroserviceManager.update({ - uuid: microserviceUuid - }, - { - delete: true, - deleteWithCleanUp: !!microserviceData.withCleanup - }, transaction); + uuid: microserviceUuid, + }, + { + delete: true, + deleteWithCleanUp: !!microserviceData.withCleanup, + }, transaction) } await _updateChangeTracking(false, microservice.iofogUuid, transaction) } async function deleteNotRunningMicroservices(fog, transaction) { - const microservices = await MicroserviceManager.findAllWithStatuses({iofogUuid: fog.uuid}, transaction); + const microservices = await MicroserviceManager.findAllWithStatuses({iofogUuid: fog.uuid}, transaction) microservices - .filter(microservice => microservice.delete) - .filter(microservice => microservice.microserviceStatus.status === MicroserviceStates.NOT_RUNNING) - .forEach(async microservice => await deleteMicroserviceWithRoutesAndPortMappings(microservice.uuid, transaction)); + .filter((microservice) => microservice.delete) + .filter((microservice) => microservice.microserviceStatus.status === MicroserviceStates.NOT_RUNNING) + .forEach(async (microservice) => await deleteMicroserviceWithRoutesAndPortMappings(microservice.uuid, transaction)) } async function createRoute(sourceMicroserviceUuid, destMicroserviceUuid, user, isCLI, transaction) { const sourceWhere = isCLI ? {uuid: sourceMicroserviceUuid} - : {uuid: sourceMicroserviceUuid, userId: user.id}; + : {uuid: sourceMicroserviceUuid, userId: user.id} - const sourceMicroservice = await MicroserviceManager.findOne(sourceWhere, transaction); + const sourceMicroservice = await MicroserviceManager.findOne(sourceWhere, transaction) if (!sourceMicroservice) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_SOURCE_MICROSERVICE_UUID, sourceMicroserviceUuid)) } const destWhere = isCLI ? {uuid: destMicroserviceUuid} - : {uuid: destMicroserviceUuid, userId: user.id}; + : {uuid: destMicroserviceUuid, userId: user.id} - const destMicroservice = await MicroserviceManager.findOne(destWhere, transaction); + const destMicroservice = await MicroserviceManager.findOne(destWhere, transaction) if (!destMicroservice) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_DEST_MICROSERVICE_UUID, destMicroserviceUuid)) } @@ -260,8 +264,8 @@ async function createRoute(sourceMicroserviceUuid, destMicroserviceUuid, user, i const route = await RoutingManager.findOne({ sourceMicroserviceUuid: sourceMicroserviceUuid, - destMicroserviceUuid: destMicroserviceUuid - }, transaction); + destMicroserviceUuid: destMicroserviceUuid, + }, transaction) if (route) { throw new Errors.ValidationError('route already exists') } @@ -274,36 +278,36 @@ async function createRoute(sourceMicroserviceUuid, destMicroserviceUuid, user, i } async function updateRouteOverConnector(connector, transaction) { - const routes = await RoutingManager.findAllRoutesByConnectorId(connector.id, transaction); + const routes = await RoutingManager.findAllRoutesByConnectorId(connector.id, transaction) const networkMicroserviceUuids = _.flatten(_.map( - routes, route => [route.sourceNetworkMicroserviceUuid, route.destNetworkMicroserviceUuid] - )); - await _updateNetworkMicroserviceConfigs(networkMicroserviceUuids, connector, transaction); + routes, (route) => [route.sourceNetworkMicroserviceUuid, route.destNetworkMicroserviceUuid] + )) + await _updateNetworkMicroserviceConfigs(networkMicroserviceUuids, connector, transaction) } async function deleteRoute(sourceMicroserviceUuid, destMicroserviceUuid, user, isCLI, transaction) { const sourceWhere = isCLI ? {uuid: sourceMicroserviceUuid} - : {uuid: sourceMicroserviceUuid, userId: user.id}; + : {uuid: sourceMicroserviceUuid, userId: user.id} - const sourceMicroservice = await MicroserviceManager.findOne(sourceWhere, transaction); + const sourceMicroservice = await MicroserviceManager.findOne(sourceWhere, transaction) if (!sourceMicroservice) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_SOURCE_MICROSERVICE_UUID, sourceMicroserviceUuid)) } const destWhere = isCLI ? {uuid: destMicroserviceUuid} - : {uuid: destMicroserviceUuid, userId: user.id}; + : {uuid: destMicroserviceUuid, userId: user.id} - const destMicroservice = await MicroserviceManager.findOne(destWhere, transaction); + const destMicroservice = await MicroserviceManager.findOne(destWhere, transaction) if (!destMicroservice) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_DEST_MICROSERVICE_UUID, destMicroserviceUuid)) } const route = await RoutingManager.findOne({ sourceMicroserviceUuid: sourceMicroserviceUuid, - destMicroserviceUuid: destMicroserviceUuid - }, transaction); + destMicroserviceUuid: destMicroserviceUuid, + }, transaction) if (!route) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.ROUTE_NOT_FOUND)) } @@ -316,20 +320,20 @@ async function deleteRoute(sourceMicroserviceUuid, destMicroserviceUuid, user, i } async function createPortMapping(microserviceUuid, portMappingData, user, isCLI, transaction) { - await Validator.validate(portMappingData, Validator.schemas.portsCreate); - await _validatePorts(portMappingData.internal, portMappingData.external); + await Validator.validate(portMappingData, Validator.schemas.portsCreate) + await _validatePorts(portMappingData.internal, portMappingData.external) const where = isCLI ? {uuid: microserviceUuid} - : {uuid: microserviceUuid, userId: user.id}; + : {uuid: microserviceUuid, userId: user.id} - const microservice = await MicroserviceManager.findOne(where, transaction); + const microservice = await MicroserviceManager.findOne(where, transaction) if (!microservice) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)) } if (!microservice.iofogUuid) { - throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.REQUIRED_FOG_NODE)); + throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.REQUIRED_FOG_NODE)) } const msPorts = await MicroservicePortManager.findOne({ @@ -337,15 +341,15 @@ async function createPortMapping(microserviceUuid, portMappingData, user, isCLI, [Op.or]: [ { - portInternal: portMappingData.internal + portInternal: portMappingData.internal, }, { - portExternal: portMappingData.external - } - ] - }, transaction); + portExternal: portMappingData.external, + }, + ], + }, transaction) if (msPorts) { - throw new Errors.ValidationError(ErrorMessages.PORT_MAPPING_ALREADY_EXISTS); + throw new Errors.ValidationError(ErrorMessages.PORT_MAPPING_ALREADY_EXISTS) } if (portMappingData.publicMode) { @@ -356,27 +360,28 @@ async function createPortMapping(microserviceUuid, portMappingData, user, isCLI, } async function updatePortMappingOverConnector(connector, transaction) { - const microservicePublicModes = await MicroservicePublicModeManager.findAllMicroservicePublicModesByConnectorId(connector.id, transaction); - const networkMicroserviceUuids = microservicePublicModes.map(obj => obj.networkMicroserviceUuid); - await _updateNetworkMicroserviceConfigs(networkMicroserviceUuids, connector, transaction); + const microservicePublicModes = await MicroservicePublicModeManager.findAllMicroservicePublicModesByConnectorId(connector.id, + transaction) + const networkMicroserviceUuids = microservicePublicModes.map((obj) => obj.networkMicroserviceUuid) + await _updateNetworkMicroserviceConfigs(networkMicroserviceUuids, connector, transaction) } async function deletePortMapping(microserviceUuid, internalPort, user, isCLI, transaction) { const where = isCLI ? {uuid: microserviceUuid} - : {uuid: microserviceUuid, userId: user.id}; + : {uuid: microserviceUuid, userId: user.id} if (!internalPort) { - throw new Errors.ValidationError(ErrorMessages.PORT_MAPPING_INTERNAL_PORT_NOT_PROVIDED); + throw new Errors.ValidationError(ErrorMessages.PORT_MAPPING_INTERNAL_PORT_NOT_PROVIDED) } - const microservice = await MicroserviceManager.findOne(where, transaction); + const microservice = await MicroserviceManager.findOne(where, transaction) if (!microservice) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)) } const msPorts = await MicroservicePortManager.findOne({ microserviceUuid: microserviceUuid, - portInternal: internalPort + portInternal: internalPort, }, transaction) if (!msPorts) { throw new Errors.NotFoundError('port mapping not exists') @@ -392,7 +397,7 @@ async function deletePortMapping(microserviceUuid, internalPort, user, isCLI, tr async function listPortMappings(microserviceUuid, user, isCLI, transaction) { const where = isCLI ? {uuid: microserviceUuid} - : {uuid: microserviceUuid, userId: user.id}; + : {uuid: microserviceUuid, userId: user.id} const microservice = await MicroserviceManager.findOne(where, transaction) if (!microservice) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)) @@ -403,7 +408,7 @@ async function listPortMappings(microserviceUuid, user, isCLI, transaction) { } async function getPhysicalConnections(microservice, transaction) { - let res = []; + const res = [] const pubModes = await MicroservicePublicModeManager.findAll({microserviceUuid: microservice.uuid}, transaction) for (const pm of pubModes) { res.push(pm.networkMicroserviceUuid) @@ -412,7 +417,7 @@ async function getPhysicalConnections(microservice, transaction) { const sourceRoutes = await RoutingManager.findAll({sourceMicroserviceUuid: microservice.uuid}, transaction) for (const sr of sourceRoutes) { if (!sr.sourceIofogUuid || !sr.destIofogUuid) { - continue; + continue } else if (sr.sourceIofogUuid === sr.destIofogUuid) { res.push(sr.destMicroserviceUuid) } else if (sr.sourceIofogUuid !== sr.destIofogUuid) { @@ -429,13 +434,13 @@ async function getPhysicalConnections(microservice, transaction) { } async function createVolumeMapping(microserviceUuid, volumeMappingData, user, isCLI, transaction) { - await Validator.validate(volumeMappingData, Validator.schemas.volumeMappings); + await Validator.validate(volumeMappingData, Validator.schemas.volumeMappings) const where = isCLI ? {uuid: microserviceUuid} - : {uuid: microserviceUuid, userId: user.id}; + : {uuid: microserviceUuid, userId: user.id} - const microservice = await MicroserviceManager.findOne(where, transaction); + const microservice = await MicroserviceManager.findOne(where, transaction) if (!microservice) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)) } @@ -443,71 +448,70 @@ async function createVolumeMapping(microserviceUuid, volumeMappingData, user, is const volumeMapping = await VolumeMappingManager.findOne({ microserviceUuid: microserviceUuid, hostDestination: volumeMappingData.hostDestination, - containerDestination: volumeMappingData.containerDestination - }, transaction); + containerDestination: volumeMappingData.containerDestination, + }, transaction) if (volumeMapping) { - throw new Errors.ValidationError(ErrorMessages.VOLUME_MAPPING_ALREADY_EXISTS); + throw new Errors.ValidationError(ErrorMessages.VOLUME_MAPPING_ALREADY_EXISTS) } const volumeMappingObj = { microserviceUuid: microserviceUuid, hostDestination: volumeMappingData.hostDestination, containerDestination: volumeMappingData.containerDestination, - accessMode: volumeMappingData.accessMode - }; + accessMode: volumeMappingData.accessMode, + } - return await VolumeMappingManager.create(volumeMappingObj, transaction); + return await VolumeMappingManager.create(volumeMappingObj, transaction) } async function deleteVolumeMapping(microserviceUuid, volumeMappingUuid, user, isCLI, transaction) { const where = isCLI ? {uuid: microserviceUuid} - : {uuid: microserviceUuid, userId: user.id}; + : {uuid: microserviceUuid, userId: user.id} - const microservice = await MicroserviceManager.findOne(where, transaction); + const microservice = await MicroserviceManager.findOne(where, transaction) if (!microservice) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)) } const volumeMappingWhere = { uuid: volumeMappingUuid, - microserviceUuid: microserviceUuid - }; + microserviceUuid: microserviceUuid, + } - const affectedRows = await VolumeMappingManager.delete(volumeMappingWhere, transaction); + const affectedRows = await VolumeMappingManager.delete(volumeMappingWhere, transaction) if (affectedRows === 0) { - throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_VOLUME_MAPPING_UUID, volumeMappingUuid)); + throw new Errors.ValidationError(AppHelper.formatMessage(ErrorMessages.INVALID_VOLUME_MAPPING_UUID, volumeMappingUuid)) } } async function listVolumeMappings(microserviceUuid, user, isCLI, transaction) { const where = isCLI ? {uuid: microserviceUuid} - : {uuid: microserviceUuid, userId: user.id}; - const microservice = await MicroserviceManager.findOne(where, transaction); + : {uuid: microserviceUuid, userId: user.id} + const microservice = await MicroserviceManager.findOne(where, transaction) if (!microservice) { throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_MICROSERVICE_UUID, microserviceUuid)) } const volumeMappingWhere = { - microserviceUuid: microserviceUuid - }; - return await VolumeMappingManager.findAll(volumeMappingWhere, transaction); + microserviceUuid: microserviceUuid, + } + return await VolumeMappingManager.findAll(volumeMappingWhere, transaction) } // this function works with escape and unescape config, in case of unescaped config, the first split will not work, // but the second will work function _validateMicroserviceConfig(config) { if (config === undefined || config === '{}') { - return '{}'; + return '{}' } - return config.split('\\"').join('"').split('"').join('\"'); + return config.split('\\"').join('"').split('"').join('\"') } async function _createMicroservice(microserviceData, user, isCLI, transaction) { - - const config = _validateMicroserviceConfig(microserviceData.config); + const config = _validateMicroserviceConfig(microserviceData.config) let newMicroservice = { uuid: AppHelper.generateRandomString(32), @@ -518,38 +522,37 @@ async function _createMicroservice(microserviceData, user, isCLI, transaction) { iofogUuid: microserviceData.iofogUuid, rootHostAccess: microserviceData.rootHostAccess, logSize: microserviceData.logLimit, - userId: user.id - }; + userId: user.id, + } - newMicroservice = AppHelper.deleteUndefinedFields(newMicroservice); + newMicroservice = AppHelper.deleteUndefinedFields(newMicroservice) - await _checkForDuplicateName(newMicroservice.name, {}, user.id, transaction); + await _checkForDuplicateName(newMicroservice.name, {}, user.id, transaction) - //validate catalog item - await CatalogService.getCatalogItem(newMicroservice.catalogItemId, user, isCLI, transaction); - //validate flow - await FlowService.getFlow(newMicroservice.flowId, user, isCLI, transaction); - //validate fog node + // validate catalog item + await CatalogService.getCatalogItem(newMicroservice.catalogItemId, user, isCLI, transaction) + // validate flow + await FlowService.getFlow(newMicroservice.flowId, user, isCLI, transaction) + // validate fog node if (newMicroservice.iofogUuid) { - await IoFogService.getFog({uuid: newMicroservice.iofogUuid}, user, isCLI, transaction); + await IoFogService.getFog({uuid: newMicroservice.iofogUuid}, user, isCLI, transaction) } - return await MicroserviceManager.create(newMicroservice, transaction); + return await MicroserviceManager.create(newMicroservice, transaction) } async function _createMicroserviceStatus(uuid, transaction) { return await MicroserviceStatusManager.create({ - microserviceUuid: uuid - }, transaction); + microserviceUuid: uuid, + }, transaction) } async function _createVolumeMappings(volumeMappings, microserviceUuid, transaction) { - - const mappings = []; + const mappings = [] for (const volumeMapping of volumeMappings) { - const mapping = Object.assign({}, volumeMapping); - mapping.microserviceUuid = microserviceUuid; - mappings.push(mapping); + const mapping = Object.assign({}, volumeMapping) + mapping.microserviceUuid = microserviceUuid + mappings.push(mapping) } await VolumeMappingManager.bulkCreate(mappings, transaction) @@ -562,26 +565,26 @@ async function _createRoutes(routes, microserviceUuid, user, transaction) { } async function _updateVolumeMappings(volumeMappings, microserviceUuid, transaction) { - for (let volumeMapping of volumeMappings) { + for (const volumeMapping of volumeMappings) { await VolumeMappingManager.update({ - microserviceUuid: microserviceUuid - }, volumeMapping, transaction); + microserviceUuid: microserviceUuid, + }, volumeMapping, transaction) } } async function _updateChangeTracking(configUpdated, fogNodeUuid, transaction) { if (configUpdated) { - await ChangeTrackingService.update(fogNodeUuid, ChangeTrackingService.events.microserviceCommon, transaction); + await ChangeTrackingService.update(fogNodeUuid, ChangeTrackingService.events.microserviceCommon, transaction) } else { - await ChangeTrackingService.update(fogNodeUuid, ChangeTrackingService.events.microserviceList, transaction); + await ChangeTrackingService.update(fogNodeUuid, ChangeTrackingService.events.microserviceList, transaction) } } -//TODO use in _deleteMicroserviceWithRoutesAndPortMappings +/* TODO use in _deleteMicroserviceWithRoutesAndPortMappings async function _deletePortMappings(microservice, user, transaction) { const msPortMappings = await MicroservicePortManager.findAll({ - microserviceUuid: microservice.uuid - }, transaction); + microserviceUuid: microservice.uuid, + }, transaction) for (const msPorts of msPortMappings) { if (msPorts.isPublic) { @@ -590,7 +593,7 @@ async function _deletePortMappings(microservice, user, transaction) { await _deleteSimplePortMapping(microservice, msPorts, user, transaction) } } -} +}*/ async function _checkForDuplicateName(name, item, userId, transaction) { if (name) { @@ -599,17 +602,17 @@ async function _checkForDuplicateName(name, item, userId, transaction) { { name: name, uuid: {[Op.ne]: item.id}, - userId: userId + userId: userId, } : { name: name, - userId: userId - }; + userId: userId, + } - const result = await MicroserviceManager.findOne(where, transaction); + const result = await MicroserviceManager.findOne(where, transaction) if (result) { - throw new Errors.DuplicatePropertyError(AppHelper.formatMessage(ErrorMessages.DUPLICATE_NAME, name)); + throw new Errors.DuplicatePropertyError(AppHelper.formatMessage(ErrorMessages.DUPLICATE_NAME, name)) } } } @@ -617,77 +620,68 @@ async function _checkForDuplicateName(name, item, userId, transaction) { async function _validateMicroserviceOnGet(userId, microserviceUuid, transaction) { const where = { '$flow.user.id$': userId, - uuid: microserviceUuid - }; - const microservice = await MicroserviceManager.findMicroserviceOnGet(where, transaction); + 'uuid': microserviceUuid, + } + const microservice = await MicroserviceManager.findMicroserviceOnGet(where, transaction) if (!microservice) { - throw new Errors.NotFoundError(ErrorMessages.INVALID_MICROSERVICE_USER); + throw new Errors.NotFoundError(ErrorMessages.INVALID_MICROSERVICE_USER) } } -/** - * use to create route between microservices on same fog - * - * @param sourceMicroservice - * @param destMicroservice - * @param transaction - * @returns {Promise} - * @private - */ async function _createSimpleRoute(sourceMicroservice, destMicroservice, transaction) { - //create new route + // create new route const routeData = { isNetworkConnection: false, sourceMicroserviceUuid: sourceMicroservice.uuid, destMicroserviceUuid: destMicroservice.uuid, sourceIofogUuid: sourceMicroservice.iofogUuid, - destIofogUuid: destMicroservice.iofogUuid //same as sourceIofogUuid - }; + destIofogUuid: destMicroservice.iofogUuid, // same as sourceIofogUuid + } - await RoutingManager.create(routeData, transaction); + await RoutingManager.create(routeData, transaction) await _switchOnUpdateFlagsForMicroservicesInRoute(sourceMicroservice, destMicroservice, transaction) } async function _updateNetworkMicroserviceConfigs(networkMicroserviceUuids, connector, transaction) { - const microservices = await MicroserviceManager.findAll({uuid: networkMicroserviceUuids}, transaction); + const microservices = await MicroserviceManager.findAll({uuid: networkMicroserviceUuids}, transaction) - let cert; + let cert if (!connector.devMode && connector.cert) { - cert = AppHelper.trimCertificate(fs.readFileSync(connector.cert, "utf-8")) + cert = AppHelper.trimCertificate(fs.readFileSync(connector.cert, 'utf-8')) } for (const microservice of microservices) { - const msConfig = JSON.parse(microservice.config); - msConfig.host = connector.domain; - msConfig.cert = cert; - msConfig.devmode = connector.devMode; + const msConfig = JSON.parse(microservice.config) + msConfig.host = connector.domain + msConfig.cert = cert + msConfig.devmode = connector.devMode const newConfig = { config: JSON.stringify(msConfig), - rebuild: true - }; + rebuild: true, + } await MicroserviceManager.update({ - uuid: microservice.uuid - }, newConfig, transaction); + uuid: microservice.uuid, + }, newConfig, transaction) } - const onlyUnique = (value, index, self) => self.indexOf(value) === index; + const onlyUnique = (value, index, self) => self.indexOf(value) === index const iofogUuids = microservices - .map(obj => obj.iofogUuid) - .filter(onlyUnique) - .filter(val => val !== null); + .map((obj) => obj.iofogUuid) + .filter(onlyUnique) + .filter((val) => val !== null) for (const iofogUuid of iofogUuids) { - await ChangeTrackingService.update(iofogUuid, ChangeTrackingService.events.microserviceCommon, transaction); + await ChangeTrackingService.update(iofogUuid, ChangeTrackingService.events.microserviceCommon, transaction) } } async function _createRouteOverConnector(sourceMicroservice, destMicroservice, user, transaction) { - //open connector - const justOpenedConnectorsPorts = await ConnectorPortService.openPortOnRandomConnector(false, transaction); + // open connector + const justOpenedConnectorsPorts = await ConnectorPortService.openPortOnRandomConnector(false, transaction) - const ports = justOpenedConnectorsPorts.ports; - const connector = justOpenedConnectorsPorts.connector; + const ports = justOpenedConnectorsPorts.ports + const connector = justOpenedConnectorsPorts.connector const createConnectorPortData = { port1: ports.port1, @@ -699,18 +693,18 @@ async function _createRouteOverConnector(sourceMicroservice, destMicroservice, u heartBeatAbsenceThresholdPort1: 60000, heartBeatAbsenceThresholdPort2: 60000, connectorId: ports.connectorId, - mappingId: ports.id - }; - const connectorPort = await ConnectorPortManager.create(createConnectorPortData, transaction); + mappingId: ports.id, + } + const connectorPort = await ConnectorPortManager.create(createConnectorPortData, transaction) - const networkCatalogItem = await CatalogService.getNetworkCatalogItem(transaction); + const networkCatalogItem = await CatalogService.getNetworkCatalogItem(transaction) - let cert; + let cert if (!connector.devMode && connector.cert) { - cert = AppHelper.trimCertificate(fs.readFileSync(connector.cert, "utf-8")) + cert = AppHelper.trimCertificate(fs.readFileSync(connector.cert, 'utf-8')) } - //create netw ms1 + // create netw ms1 const sourceNetwMsConfig = { 'mode': 'private', 'host': connector.domain, @@ -722,17 +716,17 @@ async function _createRouteOverConnector(sourceMicroservice, destMicroservice, u 'localport': 0, 'heartbeatfrequency': 20000, 'heartbeatabsencethreshold': 60000, - 'devmode': connector.devMode - }; + 'devmode': connector.devMode, + } const sourceNetworkMicroservice = await _createNetworkMicroserviceForMaster( - sourceMicroservice, - sourceNetwMsConfig, - networkCatalogItem, - user, - transaction - ); - - //create netw ms2 + sourceMicroservice, + sourceNetwMsConfig, + networkCatalogItem, + user, + transaction + ) + + // create netw ms2 const destNetwMsConfig = { 'mode': 'private', 'host': connector.domain, @@ -744,17 +738,17 @@ async function _createRouteOverConnector(sourceMicroservice, destMicroservice, u 'localport': 0, 'heartbeatfrequency': 20000, 'heartbeatabsencethreshold': 60000, - 'devmode': connector.devMode - }; + 'devmode': connector.devMode, + } const destNetworkMicroservice = await _createNetworkMicroserviceForMaster( - destMicroservice, - destNetwMsConfig, - networkCatalogItem, - user, - transaction - ); - - //create new route + destMicroservice, + destNetwMsConfig, + networkCatalogItem, + user, + transaction + ) + + // create new route const routeData = { isNetworkConnection: true, sourceMicroserviceUuid: sourceMicroservice.uuid, @@ -763,9 +757,9 @@ async function _createRouteOverConnector(sourceMicroservice, destMicroservice, u destIofogUuid: destMicroservice.iofogUuid, sourceNetworkMicroserviceUuid: sourceNetworkMicroservice.uuid, destNetworkMicroserviceUuid: destNetworkMicroservice.uuid, - connectorPortId: connectorPort.id - }; - await RoutingManager.create(routeData, transaction); + connectorPortId: connectorPort.id, + } + await RoutingManager.create(routeData, transaction) await _switchOnUpdateFlagsForMicroservicesInRoute(sourceMicroservice, destMicroservice, transaction) } @@ -782,70 +776,70 @@ async function _createNetworkMicroserviceForMaster(masterMicroservice, sourceNet rootHostAccess: false, logSize: 50, userId: masterMicroservice.userId, - configLastUpdated: Date.now() - }; + configLastUpdated: Date.now(), + } - return await MicroserviceManager.create(sourceNetworkMicroserviceData, transaction); + return await MicroserviceManager.create(sourceNetworkMicroserviceData, transaction) } async function _switchOnUpdateFlagsForMicroservicesInRoute(sourceMicroservice, destMicroservice, transaction) { const updateRebuildMs = { - rebuild: true - }; - await MicroserviceManager.update({uuid: sourceMicroservice.uuid}, updateRebuildMs, transaction); - await MicroserviceManager.update({uuid: destMicroservice.uuid}, updateRebuildMs, transaction); + rebuild: true, + } + await MicroserviceManager.update({uuid: sourceMicroservice.uuid}, updateRebuildMs, transaction) + await MicroserviceManager.update({uuid: destMicroservice.uuid}, updateRebuildMs, transaction) - await ChangeTrackingService.update(sourceMicroservice.iofogUuid, ChangeTrackingService.events.microserviceFull, transaction); - await ChangeTrackingService.update(destMicroservice.iofogUuid, ChangeTrackingService.events.microserviceFull, transaction); + await ChangeTrackingService.update(sourceMicroservice.iofogUuid, ChangeTrackingService.events.microserviceFull, transaction) + await ChangeTrackingService.update(destMicroservice.iofogUuid, ChangeTrackingService.events.microserviceFull, transaction) } async function _deleteSimpleRoute(route, transaction) { - await RoutingManager.delete({id: route.id}, transaction); + await RoutingManager.delete({id: route.id}, transaction) - await ChangeTrackingService.update(route.sourceIofogUuid, ChangeTrackingService.events.microserviceRouting, transaction); - await ChangeTrackingService.update(route.destIofogUuid, ChangeTrackingService.events.microserviceRouting, transaction); + await ChangeTrackingService.update(route.sourceIofogUuid, ChangeTrackingService.events.microserviceRouting, transaction) + await ChangeTrackingService.update(route.destIofogUuid, ChangeTrackingService.events.microserviceRouting, transaction) } async function _deleteRouteOverConnector(route, transaction) { - const ports = await ConnectorPortManager.findOne({id: route.connectorPortId}, transaction); - const connector = await ConnectorManager.findOne({id: ports.connectorId}, transaction); + const ports = await ConnectorPortManager.findOne({id: route.connectorPortId}, transaction) + const connector = await ConnectorManager.findOne({id: ports.connectorId}, transaction) try { - await ConnectorPortService.closePortOnConnector(connector, ports); + await ConnectorPortService.closePortOnConnector(connector, ports) } catch (e) { - logger.warn(`Can't close ports pair ${ports.mappingId} on connector ${connector.publicIp}. Delete manually if necessary`); + logger.warn(`Can't close ports pair ${ports.mappingId} on connector ${connector.publicIp}. Delete manually if necessary`) } - await RoutingManager.delete({id: route.id}, transaction); - await ConnectorPortManager.delete({id: ports.id}, transaction); - await MicroserviceManager.delete({uuid: route.sourceNetworkMicroserviceUuid}, transaction); - await MicroserviceManager.delete({uuid: route.destNetworkMicroserviceUuid}, transaction); + await RoutingManager.delete({id: route.id}, transaction) + await ConnectorPortManager.delete({id: ports.id}, transaction) + await MicroserviceManager.delete({uuid: route.sourceNetworkMicroserviceUuid}, transaction) + await MicroserviceManager.delete({uuid: route.destNetworkMicroserviceUuid}, transaction) - await ChangeTrackingService.update(route.sourceIofogUuid, ChangeTrackingService.events.microserviceFull, transaction); - await ChangeTrackingService.update(route.destIofogUuid, ChangeTrackingService.events.microserviceFull, transaction); + await ChangeTrackingService.update(route.sourceIofogUuid, ChangeTrackingService.events.microserviceFull, transaction) + await ChangeTrackingService.update(route.destIofogUuid, ChangeTrackingService.events.microserviceFull, transaction) } async function _createSimplePortMapping(microservice, portMappingData, user, transaction) { - //create port mapping + // create port mapping const mappingData = { isPublic: false, portInternal: portMappingData.internal, portExternal: portMappingData.external, userId: microservice.userId, - microserviceUuid: microservice.uuid - }; + microserviceUuid: microservice.uuid, + } - await MicroservicePortManager.create(mappingData, transaction); + await MicroservicePortManager.create(mappingData, transaction) await _switchOnUpdateFlagsForMicroservicesForPortMapping(microservice, false, transaction) } async function _createPortMappingOverConnector(microservice, portMappingData, user, transaction) { - //open connector - const justOpenedConnectorsPorts = await ConnectorPortService.openPortOnRandomConnector(true, transaction); + // open connector + const justOpenedConnectorsPorts = await ConnectorPortService.openPortOnRandomConnector(true, transaction) - const ports = justOpenedConnectorsPorts.ports; - const connector = justOpenedConnectorsPorts.connector; + const ports = justOpenedConnectorsPorts.ports + const connector = justOpenedConnectorsPorts.connector const createConnectorPortData = { port1: ports.port1, @@ -857,17 +851,17 @@ async function _createPortMappingOverConnector(microservice, portMappingData, us heartBeatAbsenceThresholdPort1: 60000, heartBeatAbsenceThresholdPort2: 0, connectorId: ports.connectorId, - mappingId: ports.id - }; - const connectorPort = await ConnectorPortManager.create(createConnectorPortData, transaction); + mappingId: ports.id, + } + const connectorPort = await ConnectorPortManager.create(createConnectorPortData, transaction) - const networkCatalogItem = await CatalogService.getNetworkCatalogItem(transaction); + const networkCatalogItem = await CatalogService.getNetworkCatalogItem(transaction) - let cert; + let cert if (!connector.devMode && connector.cert) { - cert = AppHelper.trimCertificate(fs.readFileSync(connector.cert, "utf-8")); + cert = AppHelper.trimCertificate(fs.readFileSync(connector.cert, 'utf-8')) } - //create netw ms1 + // create netw ms1 const netwMsConfig = { 'mode': 'public', 'host': connector.domain, @@ -879,47 +873,47 @@ async function _createPortMappingOverConnector(microservice, portMappingData, us 'localport': portMappingData.external, 'heartbeatfrequency': 20000, 'heartbeatabsencethreshold': 60000, - 'devmode': connector.devMode - }; + 'devmode': connector.devMode, + } const networkMicroservice = await _createNetworkMicroserviceForMaster( - microservice, - netwMsConfig, - networkCatalogItem, - user, - transaction - ); - - //create public port mapping + microservice, + netwMsConfig, + networkCatalogItem, + user, + transaction + ) + + // create public port mapping const mappingData = { isPublic: true, portInternal: portMappingData.internal, portExternal: portMappingData.external, userId: microservice.userId, - microserviceUuid: microservice.uuid - }; + microserviceUuid: microservice.uuid, + } - const msPortMapping = await MicroservicePortManager.create(mappingData, transaction); + const msPortMapping = await MicroservicePortManager.create(mappingData, transaction) const msPubModeData = { microserviceUuid: microservice.uuid, networkMicroserviceUuid: networkMicroservice.uuid, iofogUuid: microservice.iofogUuid, microservicePortId: msPortMapping.id, - connectorPortId: connectorPort.id - }; - await MicroservicePublicModeManager.create(msPubModeData, transaction); + connectorPortId: connectorPort.id, + } + await MicroservicePublicModeManager.create(msPubModeData, transaction) - await _switchOnUpdateFlagsForMicroservicesForPortMapping(microservice, true, transaction); + await _switchOnUpdateFlagsForMicroservicesForPortMapping(microservice, true, transaction) const publicLink = await _buildLink(connector.devMode ? 'http' : 'https', connector.publicIp, connectorPort.port2) return {publicLink: publicLink} } async function _switchOnUpdateFlagsForMicroservicesForPortMapping(microservice, isPublic, transaction) { const updateRebuildMs = { - rebuild: true - }; - await MicroserviceManager.update({uuid: microservice.uuid}, updateRebuildMs, transaction); + rebuild: true, + } + await MicroserviceManager.update({uuid: microservice.uuid}, updateRebuildMs, transaction) if (isPublic) { await ChangeTrackingService.update(microservice.iofogUuid, ChangeTrackingService.events.microserviceFull, transaction) @@ -930,63 +924,63 @@ async function _switchOnUpdateFlagsForMicroservicesForPortMapping(microservice, async function _deleteSimplePortMapping(microservice, msPorts, user, transaction) { - await MicroservicePortManager.delete({id: msPorts.id}, transaction); + await MicroservicePortManager.delete({id: msPorts.id}, transaction) const updateRebuildMs = { - rebuild: true - }; - await MicroserviceManager.update({uuid: microservice.uuid}, updateRebuildMs, transaction); - await ChangeTrackingService.update(microservice.iofogUuid, ChangeTrackingService.events.microserviceCommon, transaction); + rebuild: true, + } + await MicroserviceManager.update({uuid: microservice.uuid}, updateRebuildMs, transaction) + await ChangeTrackingService.update(microservice.iofogUuid, ChangeTrackingService.events.microserviceCommon, transaction) } async function _deletePortMappingOverConnector(microservice, msPorts, user, transaction) { - const pubModeData = await MicroservicePublicModeManager.findOne({microservicePortId: msPorts.id}, transaction); + const pubModeData = await MicroservicePublicModeManager.findOne({microservicePortId: msPorts.id}, transaction) - const ports = await ConnectorPortManager.findOne({id: pubModeData.connectorPortId}, transaction); - const connector = await ConnectorManager.findOne({id: ports.connectorId}, transaction); + const ports = await ConnectorPortManager.findOne({id: pubModeData.connectorPortId}, transaction) + const connector = await ConnectorManager.findOne({id: ports.connectorId}, transaction) try { - await ConnectorPortService.closePortOnConnector(connector, ports); + await ConnectorPortService.closePortOnConnector(connector, ports) } catch (e) { - logger.warn(`Can't close ports pair ${ports.mappingId} on connector ${connector.publicIp}. Delete manually if necessary`); + logger.warn(`Can't close ports pair ${ports.mappingId} on connector ${connector.publicIp}. Delete manually if necessary`) } - await MicroservicePublicModeManager.delete({id: pubModeData.id}, transaction); - await MicroservicePortManager.delete({id: msPorts.id}, transaction); - await ConnectorPortManager.delete({id: ports.id}, transaction); - await MicroserviceManager.delete({uuid: pubModeData.networkMicroserviceUuid}, transaction); + await MicroservicePublicModeManager.delete({id: pubModeData.id}, transaction) + await MicroservicePortManager.delete({id: msPorts.id}, transaction) + await ConnectorPortManager.delete({id: ports.id}, transaction) + await MicroserviceManager.delete({uuid: pubModeData.networkMicroserviceUuid}, transaction) const updateRebuildMs = { - rebuild: true - }; - await MicroserviceManager.update({uuid: microservice.uuid}, updateRebuildMs, transaction); + rebuild: true, + } + await MicroserviceManager.update({uuid: microservice.uuid}, updateRebuildMs, transaction) - await ChangeTrackingService.update(pubModeData.iofogUuid, ChangeTrackingService.events.microserviceFull, transaction); + await ChangeTrackingService.update(pubModeData.iofogUuid, ChangeTrackingService.events.microserviceFull, transaction) } async function _validatePorts(internal, external) { if (internal <= 0 || internal > 65535 || external <= 0 || external > 65535 - //TODO find this ports in project. check is possible to delete some of them + // TODO find this ports in project. check is possible to delete some of them || external === 60400 || external === 60401 || external === 10500 || external === 54321 || external === 55555) { - throw new Errors.ValidationError('Incorrect port') } } async function _buildPortsList(portsPairs, transaction) { - const res = []; + const res = [] for (const ports of portsPairs) { - let portMappingResposeData = { + const portMappingResposeData = { internal: ports.portInternal, external: ports.portExternal, - publicMode: ports.isPublic - }; + publicMode: ports.isPublic, + } if (ports.isPublic) { - const pubMode = await MicroservicePublicModeManager.findOne({microservicePortId: ports.id}, transaction); - const connectorPorts = await ConnectorPortManager.findOne({id: pubMode.connectorPortId}, transaction); - const connector = await ConnectorManager.findOne({id: connectorPorts.connectorId}, transaction); + const pubMode = await MicroservicePublicModeManager.findOne({microservicePortId: ports.id}, transaction) + const connectorPorts = await ConnectorPortManager.findOne({id: pubMode.connectorPortId}, transaction) + const connector = await ConnectorManager.findOne({id: connectorPorts.connectorId}, transaction) - portMappingResposeData.publicLink = await _buildLink(connector.devMode ? 'http' : 'https', connector.publicIp, connectorPorts.port2) + portMappingResposeData.publicLink = await _buildLink(connector.devMode ? 'http' : 'https', + connector.publicIp, connectorPorts.port2) } res.push(portMappingResposeData) } @@ -994,83 +988,83 @@ async function _buildPortsList(portsPairs, transaction) { } async function _getLogicalNetworkRoutesByFog(iofogUuid, transaction) { - let res = []; + const res = [] const query = { [Op.or]: [ { - sourceIofogUuid: iofogUuid + sourceIofogUuid: iofogUuid, }, { - destIofogUuid: iofogUuid - } - ] - }; + destIofogUuid: iofogUuid, + }, + ], + } const routes = await RoutingManager.findAll(query, transaction) - for (let route of routes) { + for (const route of routes) { if (route.sourceIofogUuid && route.destIofogUuid && route.isNetworkConnection) { - res.push(route); + res.push(route) } } - return res; + return res } async function _getLogicalRoutesByMicroservice(microserviceUuid, transaction) { - let res = []; + const res = [] const query = { [Op.or]: [ { - sourceMicroserviceUuid: microserviceUuid + sourceMicroserviceUuid: microserviceUuid, }, { - destMicroserviceUuid: microserviceUuid - } - ] - }; - const routes = await RoutingManager.findAll(query, transaction); - for (let route of routes) { + destMicroserviceUuid: microserviceUuid, + }, + ], + } + const routes = await RoutingManager.findAll(query, transaction) + for (const route of routes) { if (route.sourceMicroserviceUuid && route.destMicroserviceUuid) { - res.push(route); + res.push(route) } } - return res; + return res } async function deleteMicroserviceWithRoutesAndPortMappings(microserviceUuid, transaction) { - const routes = await _getLogicalRoutesByMicroservice(microserviceUuid, transaction); - for (let route of routes) { - //TODO: simplify after splitting all endpoints service functions to validation and request processing part + const routes = await _getLogicalRoutesByMicroservice(microserviceUuid, transaction) + for (const route of routes) { + // TODO: simplify after splitting all endpoints service functions to validation and request processing part const userId = (await MicroserviceManager - .findOne({uuid: route.sourceMicroserviceUuid}, transaction)) - .userId; + .findOne({uuid: route.sourceMicroserviceUuid}, transaction)) + .userId const user = { - id: userId - }; - await deleteRoute(route.sourceMicroserviceUuid, route.destMicroserviceUuid, user, false, transaction); + id: userId, + } + await deleteRoute(route.sourceMicroserviceUuid, route.destMicroserviceUuid, user, false, transaction) } - const portMappings = await MicroservicePortManager.findAll({microserviceUuid: microserviceUuid}, transaction); + const portMappings = await MicroservicePortManager.findAll({microserviceUuid: microserviceUuid}, transaction) for (const ports of portMappings) { const userId = (await MicroserviceManager - .findOne({uuid: ports.microserviceUuid}, transaction)) - .userId; + .findOne({uuid: ports.microserviceUuid}, transaction)) + .userId const user = { - id: userId - }; - await deletePortMapping(ports.microserviceUuid, ports.portInternal, user, false, transaction); + id: userId, + } + await deletePortMapping(ports.microserviceUuid, ports.portInternal, user, false, transaction) } await MicroserviceManager.delete({ - uuid: microserviceUuid - }, transaction); + uuid: microserviceUuid, + }, transaction) } async function _buildLink(protocol, ip, port) { return `${protocol}://${ip}:${port}` } -//decorated functions -const createMicroserviceWithTracking = TrackingDecorator.trackEvent(createMicroservice, TrackingEventType.MICROSERVICE_CREATED); +// decorated functions +const createMicroserviceWithTracking = TrackingDecorator.trackEvent(createMicroservice, TrackingEventType.MICROSERVICE_CREATED) module.exports = { createMicroservice: TransactionDecorator.generateTransaction(createMicroserviceWithTracking), @@ -1090,5 +1084,5 @@ module.exports = { deleteNotRunningMicroservices: deleteNotRunningMicroservices, updateRouteOverConnector: updateRouteOverConnector, updatePortMappingOverConnector: updatePortMappingOverConnector, - deleteMicroserviceWithRoutesAndPortMappings: deleteMicroserviceWithRoutesAndPortMappings -}; + deleteMicroserviceWithRoutesAndPortMappings: deleteMicroserviceWithRoutesAndPortMappings, +} diff --git a/src/services/registry-service.js b/src/services/registry-service.js index 730cba299..1384750d4 100644 --- a/src/services/registry-service.js +++ b/src/services/registry-service.js @@ -11,22 +11,22 @@ * */ -const RegistryManager = require('../sequelize/managers/registry-manager'); -const Validator = require('../schemas'); -const Errors = require('../helpers/errors'); -const ErrorMessages = require('../helpers/error-messages'); -const ChangeTrackingService = require('./change-tracking-service'); -const TransactionDecorator = require('../decorators/transaction-decorator'); -const FogManager = require('../sequelize/managers/iofog-manager'); -const Sequelize = require('sequelize'); -const Op = Sequelize.Op; -const AppHelper = require('../helpers/app-helper'); - - -const createRegistry = async function (registry, user, transaction) { - await Validator.validate(registry, Validator.schemas.registryCreate); +const RegistryManager = require('../sequelize/managers/registry-manager') +const Validator = require('../schemas') +const Errors = require('../helpers/errors') +const ErrorMessages = require('../helpers/error-messages') +const ChangeTrackingService = require('./change-tracking-service') +const TransactionDecorator = require('../decorators/transaction-decorator') +const FogManager = require('../sequelize/managers/iofog-manager') +const Sequelize = require('sequelize') +const Op = Sequelize.Op +const AppHelper = require('../helpers/app-helper') + + +const createRegistry = async function(registry, user, transaction) { + await Validator.validate(registry, Validator.schemas.registryCreate) if (registry.requiresCert && registry.certificate === undefined) { - throw new Errors.ValidationError(ErrorMessages.CERT_PROPERTY_REQUIRED); + throw new Errors.ValidationError(ErrorMessages.CERT_PROPERTY_REQUIRED) } let registryCreate = { @@ -37,67 +37,67 @@ const createRegistry = async function (registry, user, transaction) { userEmail: registry.email, requiresCert: registry.requiresCert, certificate: registry.certificate, - userId: user.id - }; + userId: user.id, + } - registryCreate = AppHelper.deleteUndefinedFields(registryCreate); + registryCreate = AppHelper.deleteUndefinedFields(registryCreate) - const createdRegistry = await RegistryManager.create(registryCreate, transaction); + const createdRegistry = await RegistryManager.create(registryCreate, transaction) - await _updateChangeTracking(user, transaction); + await _updateChangeTracking(user, transaction) return { - id: createdRegistry.id + id: createdRegistry.id, } -}; +} -const findRegistries = async function (user, isCLI, transaction) { +const findRegistries = async function(user, isCLI, transaction) { const queryRegistry = isCLI ? {} : { [Op.or]: [ { - userId: user.id + userId: user.id, }, { - isPublic: true - } - ] - }; + isPublic: true, + }, + ], + } - const registries = await RegistryManager.findAll(queryRegistry, transaction); + const registries = await RegistryManager.findAll(queryRegistry, transaction) return { - registries: registries + registries: registries, } -}; +} -const deleteRegistry = async function (registryData, user, isCLI, transaction) { - await Validator.validate(registryData, Validator.schemas.registryDelete); +const deleteRegistry = async function(registryData, user, isCLI, transaction) { + await Validator.validate(registryData, Validator.schemas.registryDelete) const queryData = isCLI ? {id: registryData.id} - : {id: registryData.id, userId: user.id}; - const registry = await RegistryManager.findOne(queryData, transaction); + : {id: registryData.id, userId: user.id} + const registry = await RegistryManager.findOne(queryData, transaction) if (!registry) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_REGISTRY_ID, registryData.id)); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_REGISTRY_ID, registryData.id)) } if (isCLI) { - user = {id: registry.userId}; + user = {id: registry.userId} } - await RegistryManager.delete(queryData, transaction); - await _updateChangeTracking(user, transaction); -}; + await RegistryManager.delete(queryData, transaction) + await _updateChangeTracking(user, transaction) +} -const updateRegistry = async function (registry, registryId, user, isCLI, transaction) { - await Validator.validate(registry, Validator.schemas.registryUpdate); +const updateRegistry = async function(registry, registryId, user, isCLI, transaction) { + await Validator.validate(registry, Validator.schemas.registryUpdate) if (registry.requiresCert && registry.certificate === undefined) { - throw new Errors.ValidationError(ErrorMessages.CERT_PROPERTY_REQUIRED); + throw new Errors.ValidationError(ErrorMessages.CERT_PROPERTY_REQUIRED) } const existingRegistry = await RegistryManager.findOne({ - id: registryId - }, transaction); + id: registryId, + }, transaction) if (!existingRegistry) { throw new Errors.NotFoundError(ErrorMessages.REGISTRY_NOT_FOUND) } @@ -109,37 +109,37 @@ const updateRegistry = async function (registry, registryId, user, isCLI, transa isPublic: registry.isPublic, userEmail: registry.email, requiresCert: registry.requiresCert, - certificate: registry.certificate - }; + certificate: registry.certificate, + } - registryUpdate = AppHelper.deleteUndefinedFields(registryUpdate); + registryUpdate = AppHelper.deleteUndefinedFields(registryUpdate) const where = isCLI ? { - id: registryId + id: registryId, } : { id: registryId, - userId: user.id - }; + userId: user.id, + } - await RegistryManager.update(where, registryUpdate, transaction); + await RegistryManager.update(where, registryUpdate, transaction) - await _updateChangeTracking(user, transaction); -}; + await _updateChangeTracking(user, transaction) +} -const _updateChangeTracking = async function (user, transaction) { - let fogs = await FogManager.findAll({userId: user.id}, transaction); +const _updateChangeTracking = async function(user, transaction) { + const fogs = await FogManager.findAll({userId: user.id}, transaction) for (fog of fogs) { - await ChangeTrackingService.update(fog.uuid, ChangeTrackingService.events.registries, transaction); + await ChangeTrackingService.update(fog.uuid, ChangeTrackingService.events.registries, transaction) } -}; +} module.exports = { createRegistry: TransactionDecorator.generateTransaction(createRegistry), findRegistries: TransactionDecorator.generateTransaction(findRegistries), deleteRegistry: TransactionDecorator.generateTransaction(deleteRegistry), - updateRegistry: TransactionDecorator.generateTransaction(updateRegistry) -}; \ No newline at end of file + updateRegistry: TransactionDecorator.generateTransaction(updateRegistry), +} diff --git a/src/services/tunnel-service.js b/src/services/tunnel-service.js index b24c51f3c..6c994a7f1 100644 --- a/src/services/tunnel-service.js +++ b/src/services/tunnel-service.js @@ -11,72 +11,72 @@ * */ -const TunnelManager = require('../sequelize/managers/tunnel-manager'); -const FogManager = require('../sequelize/managers/iofog-manager'); -const Config = require('../config'); -const AppHelper = require('../helpers/app-helper'); -const Validator = require('../schemas'); -const Errors = require('../helpers/errors'); -const ErrorMessages = require('../helpers/error-messages'); -const TransactionDecorator = require('../decorators/transaction-decorator'); -const ChangeTrackingService = require('./change-tracking-service'); +const TunnelManager = require('../sequelize/managers/tunnel-manager') +const FogManager = require('../sequelize/managers/iofog-manager') +const Config = require('../config') +const AppHelper = require('../helpers/app-helper') +const Validator = require('../schemas') +const Errors = require('../helpers/errors') +const ErrorMessages = require('../helpers/error-messages') +const TransactionDecorator = require('../decorators/transaction-decorator') +const ChangeTrackingService = require('./change-tracking-service') -const openTunnel = async function (tunnelData, user, isCli, transaction) { - const iofog = await FogManager.findOne({ uuid: tunnelData.iofogUuid }, transaction); +const openTunnel = async function(tunnelData, user, isCli, transaction) { + const iofog = await FogManager.findOne({uuid: tunnelData.iofogUuid}, transaction) if (!iofog) { - throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_IOFOG_UUID, tunnelData.iofogUuid)); + throw new Errors.NotFoundError(AppHelper.formatMessage(ErrorMessages.INVALID_IOFOG_UUID, tunnelData.iofogUuid)) } - let tunnel = tunnelData; + let tunnel = tunnelData if (isCli) { - tunnel.rport = await AppHelper.findAvailablePort(tunnelData.host); + tunnel.rport = await AppHelper.findAvailablePort(tunnelData.host) } else { - const host = Config.get("Tunnel:Host"); + const host = Config.get('Tunnel:Host') tunnel = { - username: Config.get("Tunnel:Username"), - password: Config.get("Tunnel:Password"), + username: Config.get('Tunnel:Username'), + password: Config.get('Tunnel:Password'), host: host, - rsakey: Config.get("Tunnel:RsaKey"), - lport: Config.get("Tunnel:Lport"), + rsakey: Config.get('Tunnel:RsaKey'), + lport: Config.get('Tunnel:Lport'), iofogUuid: iofog.uuid, closed: false, - rport: await AppHelper.findAvailablePort(host) - }; + rport: await AppHelper.findAvailablePort(host), + } } - await Validator.validate(tunnel, Validator.schemas.tunnelCreate); - await TunnelManager.updateOrCreate(tunnelData, tunnel, transaction); - await ChangeTrackingService.update(tunnelData.iofogUuid, ChangeTrackingService.events.tunnel, transaction); -}; + await Validator.validate(tunnel, Validator.schemas.tunnelCreate) + await TunnelManager.updateOrCreate(tunnelData, tunnel, transaction) + await ChangeTrackingService.update(tunnelData.iofogUuid, ChangeTrackingService.events.tunnel, transaction) +} -const findTunnel = async function (tunnelData, user, transaction) { - const tunnel = await TunnelManager.findOne(tunnelData, transaction); +const findTunnel = async function(tunnelData, user, transaction) { + const tunnel = await TunnelManager.findOne(tunnelData, transaction) if (!tunnel) { - throw new Errors.NotFoundError('Invalid Tunnel Id'); + throw new Errors.NotFoundError('Invalid Tunnel Id') } return { username: tunnel.username, host: tunnel.host, remotePort: tunnel.rport, localPort: tunnel.lport, - status: tunnel.closed ? "closed" : "open" - }; -}; + status: tunnel.closed ? 'closed' : 'open', + } +} -const findAll = async function (transaction) { - const tunnels = await TunnelManager.findAll({}, transaction); +const findAll = async function(transaction) { + const tunnels = await TunnelManager.findAll({}, transaction) return { - tunnels: tunnels - }; -}; + tunnels: tunnels, + } +} -const closeTunnel = async function (tunnelData, user, transaction) { - await module.exports.findTunnel(tunnelData, user, transaction); - await TunnelManager.update(tunnelData, { closed: true }, transaction); - await ChangeTrackingService.update(tunnelData.iofogUuid, ChangeTrackingService.events.tunnel, transaction); -}; +const closeTunnel = async function(tunnelData, user, transaction) { + await module.exports.findTunnel(tunnelData, user, transaction) + await TunnelManager.update(tunnelData, {closed: true}, transaction) + await ChangeTrackingService.update(tunnelData.iofogUuid, ChangeTrackingService.events.tunnel, transaction) +} module.exports = { findTunnel: TransactionDecorator.generateTransaction(findTunnel), openTunnel: TransactionDecorator.generateTransaction(openTunnel), closeTunnel: TransactionDecorator.generateTransaction(closeTunnel), findAll: TransactionDecorator.generateTransaction(findAll), -}; \ No newline at end of file +} diff --git a/src/services/user-service.js b/src/services/user-service.js index cc895c026..74e5bba85 100644 --- a/src/services/user-service.js +++ b/src/services/user-service.js @@ -11,235 +11,234 @@ * */ -const nodemailer = require('nodemailer'); -const smtpTransport = require('nodemailer-smtp-transport'); -const UserManager = require('../sequelize/managers/user-manager'); -const AppHelper = require('../helpers/app-helper'); -const Errors = require('../helpers/errors'); -const ErrorMessages = require('../helpers/error-messages'); -const Config = require('../config'); -const ioFogManager = require('../sequelize/managers/iofog-manager'); -const FogStates = require('../enums/fog-state'); -const emailActivationTemplate = require('../views/email-activation-temp'); -const emailRecoveryTemplate = require('../views/email-temp'); -const emailResetTemplate = require('../views/reset-password-temp'); -const EmailActivationCodeService = require('./email-activation-code-service'); -const AccessTokenService = require('./access-token-service'); -const TrackingDecorator = require('../decorators/tracking-decorator'); -const TrackingEventType = require('../enums/tracking-event-type'); - -const TransactionDecorator = require('../decorators/transaction-decorator'); -const Validator = require('../schemas'); - -const signUp = async function (user, isCLI, transaction) { - let isEmailActivationEnabled = Config.get("Email:ActivationEnabled"); +const nodemailer = require('nodemailer') +const smtpTransport = require('nodemailer-smtp-transport') +const UserManager = require('../sequelize/managers/user-manager') +const AppHelper = require('../helpers/app-helper') +const Errors = require('../helpers/errors') +const ErrorMessages = require('../helpers/error-messages') +const Config = require('../config') +const ioFogManager = require('../sequelize/managers/iofog-manager') +const FogStates = require('../enums/fog-state') +const emailActivationTemplate = require('../views/email-activation-temp') +const emailRecoveryTemplate = require('../views/email-temp') +const emailResetTemplate = require('../views/reset-password-temp') +const EmailActivationCodeService = require('./email-activation-code-service') +const AccessTokenService = require('./access-token-service') +const TrackingDecorator = require('../decorators/tracking-decorator') +const TrackingEventType = require('../enums/tracking-event-type') + +const TransactionDecorator = require('../decorators/transaction-decorator') +const Validator = require('../schemas') + +const signUp = async function(user, isCLI, transaction) { + const isEmailActivationEnabled = Config.get('Email:ActivationEnabled') if (isEmailActivationEnabled) { - const newUser = await _handleCreateUser(user, isEmailActivationEnabled, transaction); + const newUser = await _handleCreateUser(user, isEmailActivationEnabled, transaction) - const activationCodeData = await EmailActivationCodeService.generateActivationCode(transaction); - await EmailActivationCodeService.saveActivationCode(newUser.id, activationCodeData, transaction); + const activationCodeData = await EmailActivationCodeService.generateActivationCode(transaction) + await EmailActivationCodeService.saveActivationCode(newUser.id, activationCodeData, transaction) - const emailData = await _getEmailData(); - const transporter = await _userEmailSender(emailData); - await _notifyUserAboutActivationCode(user.email, Config.get('Email:HomeUrl'), emailData, activationCodeData, transporter); - return newUser; + const emailData = await _getEmailData() + const transporter = await _userEmailSender(emailData) + await _notifyUserAboutActivationCode(user.email, Config.get('Email:HomeUrl'), emailData, activationCodeData, transporter) + return newUser } else { - return await _handleCreateUser(user, isEmailActivationEnabled, transaction); + return await _handleCreateUser(user, isEmailActivationEnabled, transaction) } -}; +} -const login = async function (credentials, isCLI, transaction) { +const login = async function(credentials, isCLI, transaction) { const user = await UserManager.findOne({ - email: credentials.email - }, transaction); + email: credentials.email, + }, transaction) if (!user) { - throw new Errors.InvalidCredentialsError(); + throw new Errors.InvalidCredentialsError() } - const pass = AppHelper.decryptText(user.password, user.email); + const pass = AppHelper.decryptText(user.password, user.email) if (isCLI) { - credentials.password = AppHelper.decryptText(credentials.password, credentials.email); + credentials.password = AppHelper.decryptText(credentials.password, credentials.email) } - const validPassword = credentials.password === pass || credentials.password === user.tempPassword; + const validPassword = credentials.password === pass || credentials.password === user.tempPassword if (!validPassword) { - throw new Errors.InvalidCredentialsError(); + throw new Errors.InvalidCredentialsError() } - _verifyEmailActivation(user.emailActivated); + _verifyEmailActivation(user.emailActivated) - const accessToken = await _generateAccessToken(transaction); - accessToken.userId = user.id; + const accessToken = await _generateAccessToken(transaction) + accessToken.userId = user.id - await AccessTokenService.createAccessToken(accessToken, transaction); + await AccessTokenService.createAccessToken(accessToken, transaction) return { - accessToken: accessToken.token + accessToken: accessToken.token, } -}; +} -const resendActivation = async function (emailObj, isCLI, transaction) { - await Validator.validate(emailObj, Validator.schemas.resendActivation); +const resendActivation = async function(emailObj, isCLI, transaction) { + await Validator.validate(emailObj, Validator.schemas.resendActivation) const user = await UserManager.findOne({ - email: emailObj.email - }, transaction); + email: emailObj.email, + }, transaction) if (!user) { - throw new Errors.ValidationError(ErrorMessages.INVALID_USER_EMAIL); + throw new Errors.ValidationError(ErrorMessages.INVALID_USER_EMAIL) } - const activationCodeData = await EmailActivationCodeService.generateActivationCode(transaction); - await EmailActivationCodeService.saveActivationCode(user.id, activationCodeData, transaction); + const activationCodeData = await EmailActivationCodeService.generateActivationCode(transaction) + await EmailActivationCodeService.saveActivationCode(user.id, activationCodeData, transaction) - const emailData = await _getEmailData(); - const transporter = await _userEmailSender(emailData); - await _notifyUserAboutActivationCode(user.email, Config.get('Email:HomeUrl'), emailData, activationCodeData, transporter); -}; + const emailData = await _getEmailData() + const transporter = await _userEmailSender(emailData) + await _notifyUserAboutActivationCode(user.email, Config.get('Email:HomeUrl'), emailData, activationCodeData, transporter) +} -const activateUser = async function (codeData, isCLI, transaction) { +const activateUser = async function(codeData, isCLI, transaction) { const updatedObj = { - emailActivated: true - }; + emailActivated: true, + } if (isCLI) { const user = await UserManager.findOne({ - id: codeData.userId - }, transaction); + id: codeData.userId, + }, transaction) if (user.emailActivated === true) { throw new Error(ErrorMessages.USER_ALREADY_ACTIVATED) } - await _updateUser(codeData.userId, updatedObj, transaction); + await _updateUser(codeData.userId, updatedObj, transaction) } else { - await Validator.validate(codeData, Validator.schemas.activateUser); + await Validator.validate(codeData, Validator.schemas.activateUser) - const activationCode = await EmailActivationCodeService.verifyActivationCode(codeData.activationCode, transaction); + const activationCode = await EmailActivationCodeService.verifyActivationCode(codeData.activationCode, transaction) if (!activationCode) { - throw new Errors.NotFoundError(ErrorMessages.ACTIVATION_CODE_NOT_FOUND); + throw new Errors.NotFoundError(ErrorMessages.ACTIVATION_CODE_NOT_FOUND) } - await _updateUser(activationCode.userId, updatedObj, transaction); + await _updateUser(activationCode.userId, updatedObj, transaction) - await EmailActivationCodeService.deleteActivationCode(codeData.activationCode, transaction); + await EmailActivationCodeService.deleteActivationCode(codeData.activationCode, transaction) } +} -}; - -const logout = async function (user, isCLI, transaction) { +const logout = async function(user, isCLI, transaction) { return await AccessTokenService.removeAccessTokenByUserId(user.id, transaction) -}; +} -const updateUserDetails = async function (user, profileData, isCLI, transaction) { +const updateUserDetails = async function(user, profileData, isCLI, transaction) { if (isCLI) { - await Validator.validate(profileData, Validator.schemas.updateUserProfileCLI); + await Validator.validate(profileData, Validator.schemas.updateUserProfileCLI) } else { - await Validator.validate(profileData, Validator.schemas.updateUserProfile); + await Validator.validate(profileData, Validator.schemas.updateUserProfile) } - const password = (profileData.password) ? AppHelper.encryptText(profileData.password, user.email) : undefined; + const password = (profileData.password) ? AppHelper.encryptText(profileData.password, user.email) : undefined let updateObject = isCLI ? { firstName: profileData.firstName, lastName: profileData.lastName, - password: password + password: password, } : { firstName: profileData.firstName, - lastName: profileData.lastName - }; + lastName: profileData.lastName, + } - updateObject = AppHelper.deleteUndefinedFields(updateObject); + updateObject = AppHelper.deleteUndefinedFields(updateObject) - await UserManager.updateDetails(user, updateObject, transaction); + await UserManager.updateDetails(user, updateObject, transaction) return { firstName: updateObject.firstName, lastName: updateObject.lastName, - email: user.email + email: user.email, } -}; +} -const deleteUser = async function (force, user, isCLI, transaction) { +const deleteUser = async function(force, user, isCLI, transaction) { if (!force) { const ioFogArray = await ioFogManager.findAll({ - userId: user.id - }, transaction); + userId: user.id, + }, transaction) if (!!ioFogArray) { for (const ioFog of ioFogArray) { if (ioFog.daemonStatus === FogStates.RUNNING) { - throw new Errors.ValidationError(ErrorMessages.NEEDED_FORCE_DELETE_USER); + throw new Errors.ValidationError(ErrorMessages.NEEDED_FORCE_DELETE_USER) } } } } await UserManager.delete({ - id: user.id - }, transaction); -}; + id: user.id, + }, transaction) +} -const updateUserPassword = async function (passwordUpdates, user, isCLI, transaction) { - const pass = AppHelper.decryptText(user.password, user.email); +const updateUserPassword = async function(passwordUpdates, user, isCLI, transaction) { + const pass = AppHelper.decryptText(user.password, user.email) if (pass !== passwordUpdates.oldPassword && user.tempPassword !== passwordUpdates.oldPassword) { - throw new Errors.ValidationError(ErrorMessages.INVALID_OLD_PASSWORD); + throw new Errors.ValidationError(ErrorMessages.INVALID_OLD_PASSWORD) } - const emailData = await _getEmailData(); - const transporter = await _userEmailSender(emailData); + const emailData = await _getEmailData() + const transporter = await _userEmailSender(emailData) - const newPass = AppHelper.encryptText(passwordUpdates.newPassword, user.email); + const newPass = AppHelper.encryptText(passwordUpdates.newPassword, user.email) - await UserManager.updatePassword(user.id, newPass, transaction); - await _notifyUserAboutPasswordChange(user, emailData, transporter); -}; + await UserManager.updatePassword(user.id, newPass, transaction) + await _notifyUserAboutPasswordChange(user, emailData, transporter) +} -const resetUserPassword = async function (emailObj, isCLI, transaction) { - await Validator.validate(emailObj, Validator.schemas.resetUserPassword); +const resetUserPassword = async function(emailObj, isCLI, transaction) { + await Validator.validate(emailObj, Validator.schemas.resetUserPassword) const user = await UserManager.findOne({ - email: emailObj.email - }, transaction); + email: emailObj.email, + }, transaction) if (!user) { - throw new Errors.NotFoundError(ErrorMessages.ACCOUNT_NOT_FOUND); + throw new Errors.NotFoundError(ErrorMessages.ACCOUNT_NOT_FOUND) } - let tempPass = AppHelper.generateRandomString(2) + 'uL7'; - let tempDbPass = AppHelper.encryptText(tempPass, user.email); - await UserManager.updateTempPassword(user.id, tempDbPass, transaction); + const tempPass = AppHelper.generateRandomString(2) + 'uL7' + const tempDbPass = AppHelper.encryptText(tempPass, user.email) + await UserManager.updateTempPassword(user.id, tempDbPass, transaction) - const emailData = await _getEmailData(); - const transporter = await _userEmailSender(emailData); - await _notifyUserAboutPasswordReset(user, Config.get('Email:HomeUrl'), emailData, tempPass, transporter); -}; + const emailData = await _getEmailData() + const transporter = await _userEmailSender(emailData) + await _notifyUserAboutPasswordReset(user, Config.get('Email:HomeUrl'), emailData, tempPass, transporter) +} -const list = async function (isCLI, transaction) { - return await UserManager.findAll({}, transaction); -}; +const list = async function(isCLI, transaction) { + return await UserManager.findAll({}, transaction) +} -const suspendUser = async function (user, isCLI, transaction) { +const suspendUser = async function(user, isCLI, transaction) { if (user.emailActivated === false) { throw new Error(ErrorMessages.USER_NOT_ACTIVATED_YET) } const updatedObj = { - emailActivated: false - }; + emailActivated: false, + } - await AccessTokenService.removeAccessTokenByUserId(user.id, transaction); + await AccessTokenService.removeAccessTokenByUserId(user.id, transaction) - return await _updateUser(user.id, updatedObj, transaction); -}; + return await _updateUser(user.id, updatedObj, transaction) +} async function _updateUser(userId, updatedUser, transaction) { try { return await UserManager.update({ - id: userId + id: userId, }, updatedUser, transaction) } catch (errMsg) { throw new Error(ErrorMessages.USER_NOT_UPDATED) @@ -248,44 +247,45 @@ async function _updateUser(userId, updatedUser, transaction) { async function _generateAccessToken(transaction) { while (true) { - let newAccessToken = AppHelper.generateAccessToken(); - const exists = await UserManager.findByAccessToken(newAccessToken, transaction); + const newAccessToken = AppHelper.generateAccessToken() + const exists = await UserManager.findByAccessToken(newAccessToken, transaction) if (!exists) { - let tokenExpiryTime = new Date().getTime() + (Config.get('Settings:UserTokenExpirationIntervalSeconds') * 1000); + const tokenExpiryTime = new Date().getTime() + (Config.get('Settings:UserTokenExpirationIntervalSeconds') * 1000) return { token: newAccessToken, - expirationTime: tokenExpiryTime - }; + expirationTime: tokenExpiryTime, + } } } } function _verifyEmailActivation(emailActivated) { - const isEmailActivationEnabled = Config.get("Email:ActivationEnabled"); - if (isEmailActivationEnabled && !emailActivated) - throw new Error(ErrorMessages.EMAIL_NOT_ACTIVATED); + const isEmailActivationEnabled = Config.get('Email:ActivationEnabled') + if (isEmailActivationEnabled && !emailActivated) { + throw new Error(ErrorMessages.EMAIL_NOT_ACTIVATED) + } } async function _userEmailSender(emailData) { - let transporter; + let transporter if (emailData.service) { transporter = nodemailer.createTransport(smtpTransport({ service: emailData.service, auth: { user: emailData.email, - pass: emailData.password - } - })); + pass: emailData.password, + }, + })) } else { transporter = nodemailer.createTransport(smtpTransport({ host: emailData.host, port: emailData.port, auth: { user: emailData.email, - pass: emailData.password - } + pass: emailData.password, + }, })) } @@ -294,90 +294,92 @@ async function _userEmailSender(emailData) { async function _handleCreateUser(user, isEmailActivationEnabled, transaction) { const existingUser = await UserManager.findOne({ - email: user.email - }, transaction); + email: user.email, + }, transaction) if (existingUser) { - throw new Errors.ValidationError('Registration failed: There is already an account associated with your email address. Please try logging in instead.'); + throw new Errors.ValidationError('Registration failed: There is already an account associated with your email address. ' + + 'Please try logging in instead.') } - const newUser = await _createNewUser(user, isEmailActivationEnabled, transaction); + const newUser = await _createNewUser(user, isEmailActivationEnabled, transaction) return { userId: newUser.id, firstName: newUser.firstName, lastName: newUser.lastName, email: newUser.email, - emailActivated: user.emailActivated + emailActivated: user.emailActivated, } } async function _createNewUser(user, isEmailActivationEnabled, transaction) { - user.emailActivated = !isEmailActivationEnabled; - return await UserManager.create(user, transaction); + user.emailActivated = !isEmailActivationEnabled + return await UserManager.create(user, transaction) } async function _notifyUserAboutActivationCode(email, url, emailSenderData, activationCodeData, transporter) { - let mailOptions = { + const mailOptions = { from: '"IOFOG" <' + emailSenderData.email + '>', to: email, subject: 'Activate Your Account', - html: emailActivationTemplate.p1 + url + emailActivationTemplate.p2 + activationCodeData.activationCode + emailActivationTemplate.p3 + url + emailActivationTemplate.p4 + activationCodeData.activationCode + emailActivationTemplate.p5 + url + emailActivationTemplate.p6 + activationCodeData.activationCode + emailActivationTemplate.p7 - }; + html: emailActivationTemplate.p1 + url + emailActivationTemplate.p2 + activationCodeData.activationCode + + emailActivationTemplate.p3 + url + emailActivationTemplate.p4 + activationCodeData.activationCode + + emailActivationTemplate.p5 + url + emailActivationTemplate.p6 + activationCodeData.activationCode + emailActivationTemplate.p7, + } - await _sendEmail(transporter, mailOptions); + await _sendEmail(transporter, mailOptions) } async function _notifyUserAboutPasswordChange(user, emailSenderData, transporter) { - let mailOptions = { + const mailOptions = { from: '"IOFOG" <' + emailSenderData.email + '>', to: user.email, subject: 'Password Change Notification', - html: emailRecoveryTemplate.p1 + user.firstName + ' ' + user.lastName + emailRecoveryTemplate.p2 - }; + html: emailRecoveryTemplate.p1 + user.firstName + ' ' + user.lastName + emailRecoveryTemplate.p2, + } - await _sendEmail(transporter, mailOptions); + await _sendEmail(transporter, mailOptions) } async function _notifyUserAboutPasswordReset(user, url, emailSenderData, tempPass, transporter) { - let mailOptions = { + const mailOptions = { from: '"IOFOG" <' + emailSenderData.email + '>', to: user.email, subject: 'Password Reset Request', - html: emailResetTemplate.p1 + user.firstName + ' ' + user.lastName + emailResetTemplate.p2 + tempPass + emailResetTemplate.p3 + url + emailResetTemplate.p4 - }; + html: emailResetTemplate.p1 + user.firstName + ' ' + user.lastName + emailResetTemplate.p2 + tempPass + emailResetTemplate.p3 + + url + emailResetTemplate.p4, + } - await _sendEmail(transporter, mailOptions); + await _sendEmail(transporter, mailOptions) } async function _sendEmail(transporter, mailOptions) { try { - await transporter.sendMail(mailOptions); + await transporter.sendMail(mailOptions) } catch (errMsg) { - throw new Error(ErrorMessages.EMAIL_SENDER_NOT_CONFIGURED); + throw new Error(ErrorMessages.EMAIL_SENDER_NOT_CONFIGURED) } } async function _getEmailData() { try { - const email = Config.get("Email:Address"); - const password = AppHelper.decryptText(Config.get("Email:Password"), Config.get("Email:Address")); - const service = Config.get("Email:Service"); + const email = Config.get('Email:Address') + const password = AppHelper.decryptText(Config.get('Email:Password'), Config.get('Email:Address')) + const service = Config.get('Email:Service') return { email: email, password: password, - service: service + service: service, } - } catch (errMsg) { - throw new Errors.EmailActivationSetupError(); + throw new Errors.EmailActivationSetupError() } - } -//decorated functions -const signUpWithTracking = TrackingDecorator.trackEvent(signUp, TrackingEventType.USER_CREATED); +// decorated functions +const signUpWithTracking = TrackingDecorator.trackEvent(signUp, TrackingEventType.USER_CREATED) module.exports = { signUp: TransactionDecorator.generateTransaction(signUpWithTracking), @@ -390,5 +392,5 @@ module.exports = { updateUserPassword: TransactionDecorator.generateTransaction(updateUserPassword), resetUserPassword: TransactionDecorator.generateTransaction(resetUserPassword), list: TransactionDecorator.generateTransaction(list), - suspendUser: TransactionDecorator.generateTransaction(suspendUser) -}; \ No newline at end of file + suspendUser: TransactionDecorator.generateTransaction(suspendUser), +} diff --git a/src/tracking/index.js b/src/tracking/index.js index 63404c3a8..43c7ff647 100644 --- a/src/tracking/index.js +++ b/src/tracking/index.js @@ -11,72 +11,63 @@ * */ -const {isOnline} = require('../helpers/app-helper'); -const https = require('https'); -const EventTypes = require('../enums/tracking-event-type'); -const os = require('os'); -const AppHelper = require('../helpers/app-helper'); -const crypto = require('crypto'); +const {isOnline} = require('../helpers/app-helper') +const https = require('https') +const EventTypes = require('../enums/tracking-event-type') +const os = require('os') +const AppHelper = require('../helpers/app-helper') +const crypto = require('crypto') -const TrackingEventManager = require('../sequelize/managers/tracking-event-manager'); -const Transaction = require('sequelize/lib/transaction'); +const TrackingEventManager = require('../sequelize/managers/tracking-event-manager') +const Transaction = require('sequelize/lib/transaction') -const fakeTransactionObject = {fakeTransaction: true}; +const fakeTransactionObject = {fakeTransaction: true} -const trackingUuid = getUniqueTrackingUuid(); +const trackingUuid = getUniqueTrackingUuid() -/** - * generate tracking event after service function was executed - * - * @param eventType - @see src/enum/tracking-event-type.js - * @param res - response of service function - * @param args - arguments of service function - * @param functionName - name of service function - * @returns {{sourceType: string, type: string, uuid: string, timestamp: number}} - */ function buildEvent(eventType, res, args, functionName) { - let eventInfo = { + const eventInfo = { uuid: trackingUuid, sourceType: 'controller', timestamp: Date.now(), - type: eventType - }; + type: eventType, + } switch (eventType) { case EventTypes.INIT: - eventInfo.data = {event: 'controller inited'}; - break; + eventInfo.data = {event: 'controller inited'} + break case EventTypes.START: - eventInfo.data = {event: `controller started: ${res}`}; - break; + eventInfo.data = {event: `controller started: ${res}`} + break case EventTypes.USER_CREATED: - eventInfo.data = {event: 'user created'}; - break; + eventInfo.data = {event: 'user created'} + break case EventTypes.RUNNING_TIME: eventInfo.data = { event: `${res.runningTime} min`, agentsCount: res.agentsCount, - }; - break; + } + break case EventTypes.IOFOG_CREATED: - eventInfo.data = {event: 'iofog agent created'}; - break; + eventInfo.data = {event: 'iofog agent created'} + break case EventTypes.IOFOG_PROVISION: - eventInfo.data = {event: 'iofog agent provisioned'}; - break; + eventInfo.data = {event: 'iofog agent provisioned'} + break case EventTypes.CATALOG_CREATED: - eventInfo.data = {event: 'catalog item was created'}; - break; + eventInfo.data = {event: 'catalog item was created'} + break case EventTypes.MICROSERVICE_CREATED: - eventInfo.data = {event: 'microservice created'}; - break; + eventInfo.data = {event: 'microservice created'} + break case EventTypes.CONFIG_CHANGED: - eventInfo.data = {event: `new config property '${res}'`}; - break; + eventInfo.data = {event: `new config property '${res}'`} + break case EventTypes.OTHER: - eventInfo.data = {event: `function ${functionName} was executed`}; - break; + eventInfo.data = {event: `function ${functionName} was executed`} + break } - return eventInfo; + return eventInfo } function sendEvents(events) { @@ -84,64 +75,66 @@ function sendEvents(events) { event.data = JSON.parse(event.data) } const body = { - events: events + events: events, } - const data = JSON.stringify(body); - let options = { + const data = JSON.stringify(body) + const options = { host: 'analytics.iofog.org', path: '/post', method: 'POST', headers: { 'Content-Type': 'application/json', - 'Content-Length': Buffer.byteLength(data) - } - }; + 'Content-Length': Buffer.byteLength(data), + }, + } - const request = https.request(options); - request.write(data); - request.end(); + const request = https.request(options) + request.write(data) + request.end() } function getUniqueTrackingUuid() { - let uuid; + let uuid try { - let allMacs = ''; - const interfaces = os.networkInterfaces(); + let allMacs = '' + const interfaces = os.networkInterfaces() for (const i in interfaces) { - let networkInterface = interfaces[i]; - if (Array.isArray(networkInterface)) { - networkInterface = networkInterface.length > 0 ? networkInterface[0] : null; - } + if (interfaces.hasOwnProperty(i)) { + let networkInterface = interfaces[i] + if (Array.isArray(networkInterface)) { + networkInterface = networkInterface.length > 0 ? networkInterface[0] : null + } - if (!networkInterface || networkInterface.internal) { - continue; - } + if (!networkInterface || networkInterface.internal) { + continue + } - allMacs += networkInterface.mac + '-'; + allMacs += networkInterface.mac + '-' + } } - uuid = crypto.createHash('md5').update(allMacs).digest("hex"); + uuid = crypto.createHash('md5').update(allMacs).digest('hex') } catch (e) { uuid = 'random_' + AppHelper.generateRandomString(32) } - return uuid; + return uuid } async function processEvent(event, fArgs) { - event.data = JSON.stringify(event.data); + event.data = JSON.stringify(event.data) if (isOnline()) { - //save in db, and send later by job + // save in db, and send later by job if (fArgs && fArgs.length > 0 && fArgs[fArgs.length - 1] instanceof Transaction) { - await TrackingEventManager.create(event, fArgs[fArgs.length - 1]); + await TrackingEventManager.create(event, fArgs[fArgs.length - 1]) } else { - await TrackingEventManager.create(event, fakeTransactionObject); + await TrackingEventManager.create(event, fakeTransactionObject) } } else { - //just send + // just send try { - sendEvents([event]); + sendEvents([event]) } catch (e) { - logger.silly(`tracking sending failed with error ${e.message}`); + logger.silly(`tracking sending failed with error ${e.message}`) } } } @@ -150,5 +143,5 @@ module.exports = { trackingUuid: trackingUuid, buildEvent: buildEvent, sendEvents: sendEvents, - processEvent: processEvent -}; \ No newline at end of file + processEvent: processEvent, +} diff --git a/src/views/email-activation-temp.js b/src/views/email-activation-temp.js index d7a292673..359e80bbc 100644 --- a/src/views/email-activation-temp.js +++ b/src/views/email-activation-temp.js @@ -11,128 +11,130 @@ * */ -let emailActivationTemplate = { - p1: "\ +const emailActivationTemplate = { + p1: '\
\ - \ - \ - \ - \ - \ - \ - \ - \ -
\ -
\ - \ - \ - \ - \ - \ - \ - \ - \ - \ -
\ - Welcome to Eclipse ioFog!\ -
\ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ -
\ - Before we can get started, you need to click this button to activate your account. If clicking the button doesn't work, copy and paste copy and paste this link into your web browser address bar.
\ -
\ - ", + p3: '>', - p4: "/account/activate/code/", + p4: '/account/activate/code/', - p5: " \ -
\ - \ - Confirm Email Address\ - \ -
\ - — the IOFOG team\ -
\ -
\ -
\ - \ - \ - \ - \ - \ - \ -
\ - Follow \ - \ - @EclipseioFog\ - \ - on Twitter.\ -
\ -
\ -
\ -
\ -
\ -
" + p7: ' class = \'btn\' style=\'\ + font-size: 14px;\ + color: #fff;\ + background: #348eda;\ + border: none;\ + padding: 10px 20px;\ + border-radius: 6px;\ + text-decoration: none; margin-left: 20px;\'>\ + Confirm Email Address\ + \ + \ + \ + \ + \ + — the IOFOG team\ + \ + \ + \ + \ + \ + \ + \ + \ + \ +
\ + \ + \ + \ + \ + \ + \ +
\ + Follow \ + \ + @EclipseioFog\ + \ + on Twitter.\ +
\ +
\ + \ + \ + \ + \ + \ + \ + \ +', } -module.exports = emailActivationTemplate; \ No newline at end of file +module.exports = emailActivationTemplate diff --git a/src/views/email-temp.js b/src/views/email-temp.js index 06e4593b9..331bacb99 100644 --- a/src/views/email-temp.js +++ b/src/views/email-temp.js @@ -11,64 +11,66 @@ * */ -let emailRecoveryTemplate = { - p1: "
\ - \ - \ - \ - \ + \ + \ +
\ -
\ - \ - \ - \ - \ + \ + \ + \ + \ + \ +
\ - Hi, ", +const emailRecoveryTemplate = { + p1: '
\ + \ + \ + \ + \ - \ - \ -
\ +
\ + \ + \ + \ + \ - \ - \ - \ - \ - \ -
\ + Hi, ', - p2: "
\ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ - \ -
\ - We sent you this email just to tell you that your password was changed.\ - Did you do that? If so, then we are all good. If not, then please contact us\ - so we can help you avoid any potential problems.\ -
\ - You can just reply directly to this email if you need to contact us.\ -
\ - — the IOFOG team\ -
\ -
\ -
\ - \ - \ - \ - \ - \ - \ -
\ - Follow @EclipseioFog on Twitter.\ -
\ -
\ -
\ -
" + p2: '
\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ +
\ + We sent you this email just to tell you that your password was changed.\ + Did you do that? If so, then we are all good. If not, then please contact us\ + so we can help you avoid any potential problems.\ +
\ + You can just reply directly to this email if you need to contact us.\ +
\ + — the IOFOG team\ +
\ +
\ +
\ + \ + \ + \ + \ + \ + \ +
\ + Follow @EclipseioFog on Twitter.\ +
\ +
\ +
\ +
', } -module.exports = emailRecoveryTemplate; \ No newline at end of file +module.exports = emailRecoveryTemplate diff --git a/src/views/reset-password-temp.js b/src/views/reset-password-temp.js index 4f5c98c56..441ff793f 100644 --- a/src/views/reset-password-temp.js +++ b/src/views/reset-password-temp.js @@ -11,116 +11,116 @@ * */ -let emailResetTemplate = { - p1: "
\ - \ - \ - \ - \ + \ + \ + \ +
\ -
\ - \ - \ - \ - \ + \ + \ +
\ - Hi ", +const emailResetTemplate = { + p1: '
\ + \ + \ + \ + \ + \ + \ + \ + \ + \ + \ +
\ +
\ + \ + \ + \ + \ - \ - \ - \ - \ - \ - \ -
\ + Hi ', - p2: "
\ - \ - \ - \ - \ - \ - \ - \ + \ + \ + \ - \ - \ -
\ - It took like you were having some trouble with your password?\ -
\ - You can use the temporary password ", + p2: '
\ + \ + \ + \ + \ + \ + \ + \ - \ - \ - \ + \ + \ - \ - \ - \ - \ - \ - \ -
\ + It took like you were having some trouble with your password?\ +
\ + You can use the temporary password ', - p3: " to log in.\ -
\ - \ +
\ + \ - Go To Login\ - \ -
\ - — the IOFOG team\ -
\ -
\ -
\ - \ - \ - \ - \ - \ - \ -
\ - Follow \ - \ - @EclipseioFog\ - \ - on Twitter.\ -
\ -
\ - \ -
\ -
\ -
" + p4: '/login\' class = \'btn\' style=\'\ + font-size: 16px;\ + color: #fff;\ + background: #348eda;\ + border: none;\ + padding: 10px 20px;\ + border-radius: 6px;\ + text-decoration: none; margin-left: 20px;\'>\ + Go To Login\ + \ +
\ + — the IOFOG team\ +
\ +
\ +
\ + \ + \ + \ + \ + \ + \ +
\ + Follow \ + \ + @EclipseioFog\ + \ + on Twitter.\ +
\ +
\ +
\ +
\ +
\ +
', } -module.exports = emailResetTemplate; \ No newline at end of file +module.exports = emailResetTemplate diff --git a/test/src/controllers/agent-controller.test.js b/test/src/controllers/agent-controller.test.js index 55d7b2ec8..e8ff593a4 100644 --- a/test/src/controllers/agent-controller.test.js +++ b/test/src/controllers/agent-controller.test.js @@ -1,150 +1,149 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); +const {expect} = require('chai') +const sinon = require('sinon') -const AgentController = require('../../../src/controllers/agent-controller'); -const AgentService = require('../../../src/services/agent-service'); +const AgentController = require('../../../src/controllers/agent-controller') +const AgentService = require('../../../src/services/agent-service') describe('Agent Controller', () => { - def('subject', () => AgentController); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => AgentController) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.agentProvisionEndPoint()', () => { - def('type', () => 1); - def('key', () => 'testKey'); + def('type', () => 1) + def('key', () => 'testKey') def('req', () => ({ body: { type: $type, - key: $key - } - })); + key: $key, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.agentProvisionEndPoint($req)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.agentProvisionEndPoint($req)) beforeEach(() => { - $sandbox.stub(AgentService, 'agentProvision').returns($response); - }); + $sandbox.stub(AgentService, 'agentProvision').returns($response) + }) it('calls AgentService.agentProvision with correct args', async () => { - await $subject; + await $subject expect(AgentService.agentProvision).to.have.been.calledWith({ type: $type, - key: $key - }); - }); + key: $key, + }) + }) context('when AgentService#agentProvision fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#agentProvision succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.agentDeprovisionEndPoint()', () => { - def('fog', () => 'fog!'); - const deprovisionData = {microserviceUuids:["uuid"]}; + def('fog', () => 'fog!') + const deprovisionData = {microserviceUuids: ['uuid']} def('req', () => ({ - body: deprovisionData - })); + body: deprovisionData, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.agentDeprovisionEndPoint($req, $fog)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.agentDeprovisionEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'agentDeprovision').returns($response); - }); + $sandbox.stub(AgentService, 'agentDeprovision').returns($response) + }) it('calls AgentService.agentDeprovision with correct args', async () => { - await $subject; - expect(AgentService.agentDeprovision).to.have.been.calledWith(deprovisionData, $fog); - }); + await $subject + expect(AgentService.agentDeprovision).to.have.been.calledWith(deprovisionData, $fog) + }) context('when AgentService#agentDeprovision fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#agentDeprovision succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.getAgentConfigEndPoint()', () => { - def('fog', () => 'fog!'); + def('fog', () => 'fog!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getAgentConfigEndPoint($req, $fog)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getAgentConfigEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'getAgentConfig').returns($response); - }); + $sandbox.stub(AgentService, 'getAgentConfig').returns($response) + }) it('calls AgentService.getAgentConfig with correct args', async () => { - await $subject; + await $subject expect(AgentService.getAgentConfig).to.have.been.calledWith($fog) - }); + }) context('when AgentService#getAgentConfig fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#getAgentConfig succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - - }); + }) describe('.updateAgentConfigEndPoint()', () => { - def('fog', () => 'fog!'); - - def('networkInterface', () => 'testNetworkInterface'); - def('dockerUrl', () => 'testDockerUrl'); - def('diskLimit', 15); - def('diskDirectory', () => 'testDiskDirectory'); - def('memoryLimit', () => 25); - def('cpuLimit', () => 35); - def('logLimit', () => 45); - def('logDirectory', () => 'testLogDirectory'); - def('logFileCount', () => 5); - def('statusFrequency', () => 60); - def('changeFrequency', () => 30); - def('deviceScanFrequency', () => 40); - def('watchdogEnabled', () => true); - def('latitude', () => 30); - def('longitude', () => 40); - def('gpsMode', () => 'testGpsMode'); + def('fog', () => 'fog!') + + def('networkInterface', () => 'testNetworkInterface') + def('dockerUrl', () => 'testDockerUrl') + def('diskLimit', 15) + def('diskDirectory', () => 'testDiskDirectory') + def('memoryLimit', () => 25) + def('cpuLimit', () => 35) + def('logLimit', () => 45) + def('logDirectory', () => 'testLogDirectory') + def('logFileCount', () => 5) + def('statusFrequency', () => 60) + def('changeFrequency', () => 30) + def('deviceScanFrequency', () => 40) + def('watchdogEnabled', () => true) + def('latitude', () => 30) + def('longitude', () => 40) + def('gpsMode', () => 'testGpsMode') def('req', () => ({ body: { @@ -163,19 +162,19 @@ describe('Agent Controller', () => { watchdogEnabled: $watchdogEnabled, latitude: $latitude, longitude: $longitude, - gpsMode: $gpsMode - } - })); + gpsMode: $gpsMode, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.updateAgentConfigEndPoint($req, $fog)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.updateAgentConfigEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'updateAgentConfig').returns($response); - }); + $sandbox.stub(AgentService, 'updateAgentConfig').returns($response) + }) it('calls AgentService.updateAgentConfig with correct args', async () => { - await $subject; + await $subject expect(AgentService.updateAgentConfig).to.have.been.calledWith({ networkInterface: $networkInterface, dockerUrl: $dockerUrl, @@ -192,88 +191,88 @@ describe('Agent Controller', () => { watchdogEnabled: $watchdogEnabled, latitude: $latitude, longitude: $longitude, - gpsMode: $gpsMode - }, $fog); - }); + gpsMode: $gpsMode, + }, $fog) + }) context('when AgentService#updateAgentConfig fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#updateAgentConfig succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.getAgentConfigChangesEndPoint()', () => { - def('fog', () => 'fog!'); + def('fog', () => 'fog!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getAgentConfigChangesEndPoint($req, $fog)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getAgentConfigChangesEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'getAgentConfigChanges').returns($response); - }); + $sandbox.stub(AgentService, 'getAgentConfigChanges').returns($response) + }) it('calls AgentService.getAgentConfigChanges with correct args', async () => { - await $subject; - expect(AgentService.getAgentConfigChanges).to.have.been.calledWith($fog); - }); + await $subject + expect(AgentService.getAgentConfigChanges).to.have.been.calledWith($fog) + }) context('when AgentService#getAgentConfigChanges fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#getAgentConfigChanges succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.updateAgentStatusEndPoint()', () => { - def('fog', () => 'fog!'); - - def('daemonStatus', () => 'testDaemonStatus'); - def('daemonOperatingDuration', () => 'testDaemonOperatingDuration'); - def('daemonLastStart', () => 5); - def('memoryUsage', () => 25); - def('diskUsage', () => 35); - def('cpuUsage', () => 45); - def('memoryViolation', () => true); - def('diskViolation', () => true); - def('cpuViolation', () => true); - def('microserviceStatus', () => 'RUNNING'); - def('repositoryCount', () => 5); - def('repositoryStatus', () => 'testRepositoryStatus'); - def('systemTime', () => 1555555); - def('lastStatusTime', () => 15555555); - def('ipAddress', () => 'testIpAddress'); - def('processedMessages', () => 155); - def('microserviceMessageCounts', () => 1555); - def('messageSpeed', () => 5); - def('lastCommandTime', () => 155555555); - def('tunnelStatus', () => 'testTunnelStatus'); - def('version', () => '1.5.6'); - def('isReadyToUpgrade', () => true); - def('isReadyToRollback', () => true); + def('fog', () => 'fog!') + + def('daemonStatus', () => 'testDaemonStatus') + def('daemonOperatingDuration', () => 'testDaemonOperatingDuration') + def('daemonLastStart', () => 5) + def('memoryUsage', () => 25) + def('diskUsage', () => 35) + def('cpuUsage', () => 45) + def('memoryViolation', () => true) + def('diskViolation', () => true) + def('cpuViolation', () => true) + def('microserviceStatus', () => 'RUNNING') + def('repositoryCount', () => 5) + def('repositoryStatus', () => 'testRepositoryStatus') + def('systemTime', () => 1555555) + def('lastStatusTime', () => 15555555) + def('ipAddress', () => 'testIpAddress') + def('processedMessages', () => 155) + def('microserviceMessageCounts', () => 1555) + def('messageSpeed', () => 5) + def('lastCommandTime', () => 155555555) + def('tunnelStatus', () => 'testTunnelStatus') + def('version', () => '1.5.6') + def('isReadyToUpgrade', () => true) + def('isReadyToRollback', () => true) def('req', () => ({ body: { @@ -299,18 +298,18 @@ describe('Agent Controller', () => { tunnelStatus: $tunnelStatus, version: $version, IsReadyToUpgrade: $isReadyToUpgrade, - isReadyToRollback: $isReadyToRollback - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.updateAgentStatusEndPoint($req, $fog)); + isReadyToRollback: $isReadyToRollback, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.updateAgentStatusEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'updateAgentStatus').returns($response); - }); + $sandbox.stub(AgentService, 'updateAgentStatus').returns($response) + }) it('calls AgentService.updateAgentStatus with correct args', async () => { - await $subject; + await $subject expect(AgentService.updateAgentStatus).to.have.been.calledWith({ daemonStatus: $daemonStatus, daemonOperatingDuration: $daemonOperatingDuration, @@ -334,507 +333,506 @@ describe('Agent Controller', () => { tunnelStatus: $tunnelStatus, version: $version, IsReadyToUpgrade: $isReadyToUpgrade, - isReadyToRollback: $isReadyToRollback - }, $fog); - }); + isReadyToRollback: $isReadyToRollback, + }, $fog) + }) context('when AgentService#updateAgentStatus fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#updateAgentStatus succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.getAgentMicroservicesEndPoint()', () => { - def('fog', () => 'fog!'); + def('fog', () => 'fog!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getAgentMicroservicesEndPoint($req, $fog)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getAgentMicroservicesEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'getAgentMicroservices').returns($response); - }); + $sandbox.stub(AgentService, 'getAgentMicroservices').returns($response) + }) it('calls AgentService.getAgentMicroservices with correct args', async () => { - await $subject; - expect(AgentService.getAgentMicroservices).to.have.been.calledWith($fog); - }); + await $subject + expect(AgentService.getAgentMicroservices).to.have.been.calledWith($fog) + }) context('when AgentService#getAgentMicroservices fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#getAgentMicroservices succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('getAgentMicroserviceEndPoint()', () => { - def('fog', () => 'fog!'); - def('microserviceUuid', () => 'testUuid'); + def('fog', () => 'fog!') + def('microserviceUuid', () => 'testUuid') def('req', () => ({ params: { microserviceUuid: $microserviceUuid, - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getAgentMicroserviceEndPoint($req, $fog)); + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getAgentMicroserviceEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'getAgentMicroservice').returns($response); - }); + $sandbox.stub(AgentService, 'getAgentMicroservice').returns($response) + }) it('calls AgentService.getAgentMicroservice with correct args', async () => { - await $subject; - expect(AgentService.getAgentMicroservice).to.have.been.calledWith($microserviceUuid, $fog); - }); + await $subject + expect(AgentService.getAgentMicroservice).to.have.been.calledWith($microserviceUuid, $fog) + }) context('when AgentService#getAgentMicroservice fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#getAgentMicroservice succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('getAgentRegistriesEndPoint()', () => { - def('fog', () => 'fog!'); + def('fog', () => 'fog!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getAgentRegistriesEndPoint($req, $fog)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getAgentRegistriesEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'getAgentRegistries').returns($response); - }); + $sandbox.stub(AgentService, 'getAgentRegistries').returns($response) + }) it('calls AgentService.getAgentRegistries with correct args', async () => { - await $subject; - expect(AgentService.getAgentRegistries).to.have.been.calledWith($fog); - }); + await $subject + expect(AgentService.getAgentRegistries).to.have.been.calledWith($fog) + }) context('when AgentService#getAgentRegistries fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#getAgentRegistries succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('getAgentTunnelEndPoint()', () => { - def('fog', () => 'fog!'); + def('fog', () => 'fog!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getAgentTunnelEndPoint($req, $fog)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getAgentTunnelEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'getAgentTunnel').returns($response); - }); + $sandbox.stub(AgentService, 'getAgentTunnel').returns($response) + }) it('calls AgentService.getAgentTunnel with correct args', async () => { - await $subject; - expect(AgentService.getAgentTunnel).to.have.been.calledWith($fog); - }); + await $subject + expect(AgentService.getAgentTunnel).to.have.been.calledWith($fog) + }) context('when AgentService#getAgentTunnel fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#getAgentTunnel succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('getAgentStraceEndPoint()', () => { - def('fog', () => 'fog!'); + def('fog', () => 'fog!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getAgentStraceEndPoint($req, $fog)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getAgentStraceEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'getAgentStrace').returns($response); - }); + $sandbox.stub(AgentService, 'getAgentStrace').returns($response) + }) it('calls AgentService.getAgentStrace with correct args', async () => { - await $subject; - expect(AgentService.getAgentStrace).to.have.been.calledWith($fog); - }); + await $subject + expect(AgentService.getAgentStrace).to.have.been.calledWith($fog) + }) context('when AgentService#getAgentStrace fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#getAgentStrace succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('updateAgentStraceEndPoint()', () => { - def('fog', () => 'fog!'); - def('microserviceUuid', () => 'microserviceUuid'); - def('buffer', () => 'testBuffer'); + def('fog', () => 'fog!') + def('microserviceUuid', () => 'microserviceUuid') + def('buffer', () => 'testBuffer') def('straceData', [{ microserviceUuid: $microserviceUuid, - buffer: $buffer - }]); + buffer: $buffer, + }]) def('req', () => ({ body: { - straceData: $straceData - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.updateAgentStraceEndPoint($req, $fog)); + straceData: $straceData, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.updateAgentStraceEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'updateAgentStrace').returns($response); - }); + $sandbox.stub(AgentService, 'updateAgentStrace').returns($response) + }) it('calls AgentService.updateAgentStrace with correct args', async () => { - await $subject; + await $subject expect(AgentService.updateAgentStrace).to.have.been.calledWith({ - straceData: $straceData - }, $fog); - }); + straceData: $straceData, + }, $fog) + }) context('when AgentService#updateAgentStrace fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#updateAgentStrace succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('getAgentChangeVersionCommandEndPoint()', () => { - def('fog', () => 'fog!'); + def('fog', () => 'fog!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getAgentChangeVersionCommandEndPoint($req, $fog)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getAgentChangeVersionCommandEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'getAgentChangeVersionCommand').returns($response); - }); + $sandbox.stub(AgentService, 'getAgentChangeVersionCommand').returns($response) + }) it('calls AgentService.getAgentChangeVersionCommand with correct args', async () => { - await $subject; - expect(AgentService.getAgentChangeVersionCommand).to.have.been.calledWith($fog); - }); + await $subject + expect(AgentService.getAgentChangeVersionCommand).to.have.been.calledWith($fog) + }) context('when AgentService#getAgentChangeVersionCommand fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#getAgentChangeVersionCommand succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('updateHalHardwareInfoEndPoint()', () => { - def('fog', () => 'fog!'); + def('fog', () => 'fog!') - def('info', () => 'testInfo'); + def('info', () => 'testInfo') def('req', () => ({ body: { - info: $info - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.updateHalHardwareInfoEndPoint($req, $fog)); + info: $info, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.updateHalHardwareInfoEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'updateHalHardwareInfo').returns($response); - }); + $sandbox.stub(AgentService, 'updateHalHardwareInfo').returns($response) + }) it('calls AgentService.updateHalHardwareInfo with correct args', async () => { - await $subject; + await $subject expect(AgentService.updateHalHardwareInfo).to.have.been.calledWith({ - info: $info - }, $fog); - }); + info: $info, + }, $fog) + }) context('when AgentService#updateHalHardwareInfo fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#updateHalHardwareInfo succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('updateHalUsbInfoEndPoint()', () => { - def('fog', () => 'fog!'); + def('fog', () => 'fog!') - def('info', () => 'testInfo'); + def('info', () => 'testInfo') def('req', () => ({ body: { - info: $info - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.updateHalUsbInfoEndPoint($req, $fog)); + info: $info, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.updateHalUsbInfoEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'updateHalUsbInfo').returns($response); - }); + $sandbox.stub(AgentService, 'updateHalUsbInfo').returns($response) + }) it('calls AgentService.updateHalUsbInfo with correct args', async () => { - await $subject; + await $subject expect(AgentService.updateHalUsbInfo).to.have.been.calledWith({ - info: $info - }, $fog); - }); + info: $info, + }, $fog) + }) context('when AgentService#updateHalUsbInfo fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#updateHalUsbInfo succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('deleteNodeEndPoint()', () => { - def('fog', () => 'fog!'); + def('fog', () => 'fog!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.deleteNodeEndPoint($req, $fog)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.deleteNodeEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'deleteNode').returns($response); - }); + $sandbox.stub(AgentService, 'deleteNode').returns($response) + }) it('calls AgentService.deleteNode with correct args', async () => { - await $subject; - expect(AgentService.deleteNode).to.have.been.calledWith($fog); - }); + await $subject + expect(AgentService.deleteNode).to.have.been.calledWith($fog) + }) context('when AgentService#deleteNode fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#deleteNode succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('getImageSnapshotEndPoint()', () => { - def('fog', () => 'fog!'); + def('fog', () => 'fog!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getImageSnapshotEndPoint($req, $fog)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getImageSnapshotEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'getImageSnapshot').returns($response); - }); + $sandbox.stub(AgentService, 'getImageSnapshot').returns($response) + }) it('calls AgentService.getImageSnapshot with correct args', async () => { - await $subject; - expect(AgentService.getImageSnapshot).to.have.been.calledWith($fog); - }); + await $subject + expect(AgentService.getImageSnapshot).to.have.been.calledWith($fog) + }) context('when AgentService#getImageSnapshot fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#getImageSnapshot succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('putImageSnapshotEndPoint()', () => { - def('fog', () => 'fog!'); + def('fog', () => 'fog!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.putImageSnapshotEndPoint($req, $fog)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.putImageSnapshotEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'putImageSnapshot').returns($response); - }); + $sandbox.stub(AgentService, 'putImageSnapshot').returns($response) + }) it('calls AgentService.putImageSnapshot with correct args', async () => { - await $subject; - expect(AgentService.putImageSnapshot).to.have.been.calledWith($req, $fog); - }); + await $subject + expect(AgentService.putImageSnapshot).to.have.been.calledWith($req, $fog) + }) context('when AgentService#putImageSnapshot fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#putImageSnapshot succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('postTrackingEndPoint()', () => { - def('fog', () => 'fog!'); + def('fog', () => 'fog!') def('req', () => ({ - body: {events: []} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.postTrackingEndPoint($req, $fog)); + body: {events: []}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.postTrackingEndPoint($req, $fog)) beforeEach(() => { - $sandbox.stub(AgentService, 'postTracking').returns($response); - }); + $sandbox.stub(AgentService, 'postTracking').returns($response) + }) it('calls AgentService.postTrackingEndPoint with correct args', async () => { - await $subject; - expect(AgentService.postTracking).to.have.been.calledWith($req.body.events, $fog); - }); + await $subject + expect(AgentService.postTracking).to.have.been.calledWith($req.body.events, $fog) + }) context('when AgentService#postTrackingEndPoint fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AgentService#postTrackingEndPoint succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); - -}); \ No newline at end of file + }) +}) diff --git a/test/src/controllers/catalog-controller.test.js b/test/src/controllers/catalog-controller.test.js index 18c611d04..d808d8379 100644 --- a/test/src/controllers/catalog-controller.test.js +++ b/test/src/controllers/catalog-controller.test.js @@ -1,46 +1,46 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); +const {expect} = require('chai') +const sinon = require('sinon') -const CatalogController = require('../../../src/controllers/catalog-controller'); -const CatalogService = require('../../../src/services/catalog-service'); +const CatalogController = require('../../../src/controllers/catalog-controller') +const CatalogService = require('../../../src/services/catalog-service') describe('Catalog Controller', () => { - def('subject', () => CatalogController); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => CatalogController) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.createCatalogItemEndPoint()', () => { - def('user', () => 'user!'); + def('user', () => 'user!') - def('name', () => 'testName'); - def('description', () => 'testDescription'); - def('category', () => 'testCategory'); - def('containerImage', () => 'testContainerImage'); - def('fogTypeId', () => 'testFogTypeId'); + def('name', () => 'testName') + def('description', () => 'testDescription') + def('category', () => 'testCategory') + def('containerImage', () => 'testContainerImage') + def('fogTypeId', () => 'testFogTypeId') def('images', () => [{ containerImage: $containerImage, - fogTypeId: $fogTypeId - }]); - def('publisher', () => 'testPublisher'); - def('diskRequired', () => 15); - def('ramRequired', () => 25); - def('picture', () => 'testPicture'); - def('isPublic', () => false); - def('registryId', () => 5); - def('inputInfoType', () => 'testInfoType'); - def('inputInfoFormat', () => 'testInfoFormat'); + fogTypeId: $fogTypeId, + }]) + def('publisher', () => 'testPublisher') + def('diskRequired', () => 15) + def('ramRequired', () => 25) + def('picture', () => 'testPicture') + def('isPublic', () => false) + def('registryId', () => 5) + def('inputInfoType', () => 'testInfoType') + def('inputInfoFormat', () => 'testInfoFormat') def('inputType', () => ({ infoType: $inputInfoType, - infoFormat: $inputInfoFormat - })); - def('outputInfoType', () => 'testInfoType'); - def('outputInfoFormat', () => 'testInfoFormat'); + infoFormat: $inputInfoFormat, + })) + def('outputInfoType', () => 'testInfoType') + def('outputInfoFormat', () => 'testInfoFormat') def('outputType', () => ({ infoType: $outputInfoType, - infoFormat: $outputInfoFormat - })); - def('configExample', () => '{}'); + infoFormat: $outputInfoFormat, + })) + def('configExample', () => '{}') def('req', () => ({ body: { @@ -56,19 +56,19 @@ describe('Catalog Controller', () => { registryId: $registryId, inputType: $inputType, outputType: $outputType, - configExample: $configExample - } - })); + configExample: $configExample, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.createCatalogItemEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.createCatalogItemEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(CatalogService, 'createCatalogItem').returns($response); - }); + $sandbox.stub(CatalogService, 'createCatalogItem').returns($response) + }) it('calls CatalogService.createCatalogItem with correct args', async () => { - await $subject; + await $subject expect(CatalogService.createCatalogItem).to.have.been.calledWith({ name: $name, description: $description, @@ -82,179 +82,177 @@ describe('Catalog Controller', () => { registryId: $registryId, inputType: $inputType, outputType: $outputType, - configExample: $configExample - }, $user); - }); + configExample: $configExample, + }, $user) + }) context('when CatalogService#createCatalogItem fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogService#createCatalogItem succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.listCatalogItemsEndPoint()', () => { - def('user', () => 'user!'); + def('user', () => 'user!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.listCatalogItemsEndPoint($req, $user)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.listCatalogItemsEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(CatalogService, 'listCatalogItems').returns($response); - }); + $sandbox.stub(CatalogService, 'listCatalogItems').returns($response) + }) it('calls CatalogService.listCatalogItems with correct args', async () => { - await $subject; + await $subject expect(CatalogService.listCatalogItems).to.have.been.calledWith($user, false) - }); + }) context('when CatalogService#listCatalogItems fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogService#listCatalogItems succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - - }); - + }) describe('.listCatalogItemEndPoint()', () => { - def('user', () => 'user!'); - def('id', () => 15); + def('user', () => 'user!') + def('id', () => 15) def('req', () => ({ params: { - id: $id - } - })); + id: $id, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.listCatalogItemEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.listCatalogItemEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(CatalogService, 'getCatalogItem').returns($response); - }); + $sandbox.stub(CatalogService, 'getCatalogItem').returns($response) + }) it('calls CatalogService.getCatalogItem with correct args', async () => { - await $subject; - expect(CatalogService.getCatalogItem).to.have.been.calledWith($id, $user, false); - }); + await $subject + expect(CatalogService.getCatalogItem).to.have.been.calledWith($id, $user, false) + }) context('when CatalogService#getCatalogItem fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogService#getCatalogItem succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.deleteCatalogItemEndPoint()', () => { - def('user', () => 'user!'); - def('id', () => 15); + def('user', () => 'user!') + def('id', () => 15) def('req', () => ({ params: { - id: $id - } - })); + id: $id, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.deleteCatalogItemEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.deleteCatalogItemEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(CatalogService, 'deleteCatalogItem').returns($response); - }); + $sandbox.stub(CatalogService, 'deleteCatalogItem').returns($response) + }) it('calls CatalogService.deleteCatalogItem with correct args', async () => { - await $subject; - expect(CatalogService.deleteCatalogItem).to.have.been.calledWith($id, $user, false); - }); + await $subject + expect(CatalogService.deleteCatalogItem).to.have.been.calledWith($id, $user, false) + }) context('when CatalogService#deleteCatalogItem fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogService#deleteCatalogItem succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.updateCatalogItemEndPoint()', () => { - def('user', () => 'user!'); - def('id', () => 15); - - def('name', () => 'testName'); - def('description', () => 'testDescription'); - def('category', () => 'testCategory'); - def('containerImage', () => 'testContainerImage'); - def('fogTypeId', () => 'testFogTypeId'); + def('user', () => 'user!') + def('id', () => 15) + + def('name', () => 'testName') + def('description', () => 'testDescription') + def('category', () => 'testCategory') + def('containerImage', () => 'testContainerImage') + def('fogTypeId', () => 'testFogTypeId') def('images', () => [{ containerImage: $containerImage, - fogTypeId: $fogTypeId - }]); - def('publisher', () => 'testPublisher'); - def('diskRequired', () => 15); - def('ramRequired', () => 25); - def('picture', () => 'testPicture'); - def('isPublic', () => false); - def('registryId', () => 5); - def('inputInfoType', () => 'testInfoType'); - def('inputInfoFormat', () => 'testInfoFormat'); + fogTypeId: $fogTypeId, + }]) + def('publisher', () => 'testPublisher') + def('diskRequired', () => 15) + def('ramRequired', () => 25) + def('picture', () => 'testPicture') + def('isPublic', () => false) + def('registryId', () => 5) + def('inputInfoType', () => 'testInfoType') + def('inputInfoFormat', () => 'testInfoFormat') def('inputType', () => ({ infoType: $inputInfoType, - infoFormat: $inputInfoFormat - })); - def('outputInfoType', () => 'testInfoType'); - def('outputInfoFormat', () => 'testInfoFormat'); + infoFormat: $inputInfoFormat, + })) + def('outputInfoType', () => 'testInfoType') + def('outputInfoFormat', () => 'testInfoFormat') def('outputType', () => ({ infoType: $outputInfoType, - infoFormat: $outputInfoFormat - })); - def('configExample', () => '{}'); + infoFormat: $outputInfoFormat, + })) + def('configExample', () => '{}') def('req', () => ({ params: { - id: $id + id: $id, }, body: { name: $name, @@ -269,19 +267,19 @@ describe('Catalog Controller', () => { registryId: $registryId, inputType: $inputType, outputType: $outputType, - configExample: $configExample - } - })); + configExample: $configExample, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.updateCatalogItemEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.updateCatalogItemEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(CatalogService, 'updateCatalogItem').returns($response); - }); + $sandbox.stub(CatalogService, 'updateCatalogItem').returns($response) + }) it('calls CatalogService.updateCatalogItem with correct args', async () => { - await $subject; + await $subject expect(CatalogService.updateCatalogItem).to.have.been.calledWith($id, { name: $name, description: $description, @@ -295,26 +293,24 @@ describe('Catalog Controller', () => { registryId: $registryId, inputType: $inputType, outputType: $outputType, - configExample: $configExample - }, $user, false); - }); + configExample: $configExample, + }, $user, false) + }) context('when CatalogService.updateCatalogItem fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogService.updateCatalogItem succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - - }); - -}); \ No newline at end of file + }) +}) diff --git a/test/src/controllers/controller-controller.test.js b/test/src/controllers/controller-controller.test.js index fe5b70471..a7b4e5386 100644 --- a/test/src/controllers/controller-controller.test.js +++ b/test/src/controllers/controller-controller.test.js @@ -1,115 +1,113 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); +const {expect} = require('chai') +const sinon = require('sinon') -const Controller = require('../../../src/controllers/controller'); -const ControllerService = require('../../../src/services/controller-service'); +const Controller = require('../../../src/controllers/controller') +const ControllerService = require('../../../src/services/controller-service') describe('Controller', () => { - def('subject', () => Controller); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => Controller) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.statusControllerEndPoint()', () => { def('req', () => ({ - body: {} - })); + body: {}, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.statusControllerEndPoint($req)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.statusControllerEndPoint($req)) beforeEach(() => { - $sandbox.stub(ControllerService, 'statusController').returns($response); - }); + $sandbox.stub(ControllerService, 'statusController').returns($response) + }) it('calls ControllerService.statusController with correct args', async () => { - await $subject; - expect(ControllerService.statusController).to.have.been.calledWith(false); - }); + await $subject + expect(ControllerService.statusController).to.have.been.calledWith(false) + }) context('when ControllerService#statusController fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ControllerService#statusController succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.emailActivationEndPoint()', () => { def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.emailActivationEndPoint($req, $user)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.emailActivationEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(ControllerService, 'emailActivation').returns($response); - }); + $sandbox.stub(ControllerService, 'emailActivation').returns($response) + }) it('calls ControllerService.emailActivation with correct args', async () => { - await $subject; + await $subject expect(ControllerService.emailActivation).to.have.been.calledWith(false) - }); + }) context('when ControllerService#emailActivation fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ControllerService#emailActivation succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - - }); + }) describe('.fogTypesEndPoint()', () => { def('req', () => ({ - body: {} - })); + body: {}, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.fogTypesEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.fogTypesEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(ControllerService, 'getFogTypes').returns($response); - }); + $sandbox.stub(ControllerService, 'getFogTypes').returns($response) + }) it('calls ControllerService.getFogTypes with correct args', async () => { - await $subject; - expect(ControllerService.getFogTypes).to.have.been.calledWith(false); - }); + await $subject + expect(ControllerService.getFogTypes).to.have.been.calledWith(false) + }) context('when ControllerService#getFogTypes fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ControllerService#getFogTypes succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); - -}); \ No newline at end of file + }) +}) diff --git a/test/src/controllers/diagnostics-controller.test.js b/test/src/controllers/diagnostics-controller.test.js index 1403afd63..df8dba453 100644 --- a/test/src/controllers/diagnostics-controller.test.js +++ b/test/src/controllers/diagnostics-controller.test.js @@ -1,238 +1,235 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); +const {expect} = require('chai') +const sinon = require('sinon') -const DiagnosticController = require('../../../src/controllers/diagnostic-controller'); -const DiagnosticService = require('../../../src/services/diagnostic-service'); +const DiagnosticController = require('../../../src/controllers/diagnostic-controller') +const DiagnosticService = require('../../../src/services/diagnostic-service') describe('Diagnostic Controller', () => { - def('subject', () => DiagnosticController); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => DiagnosticController) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.changeMicroserviceStraceStateEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') - def('enable', () => true); + def('enable', () => true) def('req', () => ({ params: { - uuid: $uuid + uuid: $uuid, }, body: { - enable: $enable - } - })); + enable: $enable, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.changeMicroserviceStraceStateEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.changeMicroserviceStraceStateEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(DiagnosticService, 'changeMicroserviceStraceState').returns($response); - }); + $sandbox.stub(DiagnosticService, 'changeMicroserviceStraceState').returns($response) + }) it('calls DiagnosticService.changeMicroserviceStraceState with correct args', async () => { - await $subject; + await $subject expect(DiagnosticService.changeMicroserviceStraceState).to.have.been.calledWith($uuid, { - enable: $enable - }, $user, false); - }); + enable: $enable, + }, $user, false) + }) context('when DiagnosticService#changeMicroserviceStraceState fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when DiagnosticService#changeMicroserviceStraceState succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.getMicroserviceStraceDataEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); - def('format', () => 'string'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') + def('format', () => 'string') def('req', () => ({ params: { - uuid: $uuid + uuid: $uuid, }, query: { - format: $format - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getMicroserviceStraceDataEndPoint($req, $user)); + format: $format, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getMicroserviceStraceDataEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(DiagnosticService, 'getMicroserviceStraceData').returns($response); - }); + $sandbox.stub(DiagnosticService, 'getMicroserviceStraceData').returns($response) + }) it('calls DiagnosticService.getMicroserviceStraceData with correct args', async () => { - await $subject; + await $subject expect(DiagnosticService.getMicroserviceStraceData).to.have.been.calledWith($uuid, { - format: $format + format: $format, }, $user, false) - }); + }) context('when DiagnosticService#getMicroserviceStraceData fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when DiagnosticService#getMicroserviceStraceData succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - - }); + }) describe('.postMicroserviceStraceDataToFtpEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') - def('ftpHost', () => 'testHost'); - def('ftpPort', () => 15); - def('ftpPass', () => 'ftpPass'); - def('ftpDestDir', () => 'ftpDestDirectory'); + def('ftpHost', () => 'testHost') + def('ftpPort', () => 15) + def('ftpPass', () => 'ftpPass') + def('ftpDestDir', () => 'ftpDestDirectory') def('req', () => ({ params: { - uuid: $uuid + uuid: $uuid, }, body: { ftpHost: $ftpHost, ftpPort: $ftpPort, ftpPass: $ftpPass, - ftpDestDir: $ftpDestDir - } - })); + ftpDestDir: $ftpDestDir, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.postMicroserviceStraceDataToFtpEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.postMicroserviceStraceDataToFtpEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(DiagnosticService, 'postMicroserviceStraceDatatoFtp').returns($response); - }); + $sandbox.stub(DiagnosticService, 'postMicroserviceStraceDatatoFtp').returns($response) + }) it('calls DiagnosticService.postMicroserviceStraceDatatoFtp with correct args', async () => { - await $subject; + await $subject expect(DiagnosticService.postMicroserviceStraceDatatoFtp).to.have.been.calledWith($uuid, { ftpHost: $ftpHost, ftpPort: $ftpPort, ftpPass: $ftpPass, - ftpDestDir: $ftpDestDir - }, $user, false); - }); + ftpDestDir: $ftpDestDir, + }, $user, false) + }) context('when DiagnosticService#postMicroserviceStraceDatatoFtp fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when DiagnosticService#postMicroserviceStraceDatatoFtp succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.createMicroserviceImageSnapshotEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') def('req', () => ({ params: { - uuid: $uuid - } - })); + uuid: $uuid, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.createMicroserviceImageSnapshotEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.createMicroserviceImageSnapshotEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(DiagnosticService, 'postMicroserviceImageSnapshotCreate').returns($response); - }); + $sandbox.stub(DiagnosticService, 'postMicroserviceImageSnapshotCreate').returns($response) + }) it('calls DiagnosticService.postMicroserviceImageSnapshotCreate with correct args', async () => { - await $subject; - expect(DiagnosticService.postMicroserviceImageSnapshotCreate).to.have.been.calledWith($uuid, $user, false); - }); + await $subject + expect(DiagnosticService.postMicroserviceImageSnapshotCreate).to.have.been.calledWith($uuid, $user, false) + }) context('when DiagnosticService#postMicroserviceImageSnapshotCreate fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when DiagnosticService#postMicroserviceImageSnapshotCreate succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.getMicroserviceImageSnapshotEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') def('req', () => ({ params: { - uuid: $uuid - } - })); + uuid: $uuid, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.getMicroserviceImageSnapshotEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.getMicroserviceImageSnapshotEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(DiagnosticService, 'getMicroserviceImageSnapshot').returns($response); - }); + $sandbox.stub(DiagnosticService, 'getMicroserviceImageSnapshot').returns($response) + }) it('calls DiagnosticService.getMicroserviceImageSnapshot with correct args', async () => { - await $subject; - expect(DiagnosticService.getMicroserviceImageSnapshot).to.have.been.calledWith($uuid, $user, false); - }); + await $subject + expect(DiagnosticService.getMicroserviceImageSnapshot).to.have.been.calledWith($uuid, $user, false) + }) context('when DiagnosticService.getMicroserviceImageSnapshot fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when DiagnosticService.getMicroserviceImageSnapshot succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - - }); - -}); \ No newline at end of file + }) +}) diff --git a/test/src/controllers/flow-controller.test.js b/test/src/controllers/flow-controller.test.js index ecb45b2a4..91fd73aed 100644 --- a/test/src/controllers/flow-controller.test.js +++ b/test/src/controllers/flow-controller.test.js @@ -1,228 +1,225 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); +const {expect} = require('chai') +const sinon = require('sinon') -const FlowController = require('../../../src/controllers/flow-controller'); -const FlowService = require('../../../src/services/flow-service'); +const FlowController = require('../../../src/controllers/flow-controller') +const FlowService = require('../../../src/services/flow-service') describe('Flow Controller', () => { - def('subject', () => FlowController); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => FlowController) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.createFlowEndPoint()', () => { - def('user', () => 'user!'); + def('user', () => 'user!') - def('name', () => 'testName'); - def('description', () => 'testDescription'); - def('isActivated', () => true); + def('name', () => 'testName') + def('description', () => 'testDescription') + def('isActivated', () => true) def('req', () => ({ body: { name: $name, description: $description, - isActivated: $isActivated - } - })); + isActivated: $isActivated, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.createFlowEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.createFlowEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(FlowService, 'createFlow').returns($response); - }); + $sandbox.stub(FlowService, 'createFlow').returns($response) + }) it('calls FlowService.createFlow with correct args', async () => { - await $subject; + await $subject expect(FlowService.createFlow).to.have.been.calledWith({ name: $name, description: $description, - isActivated: $isActivated - }, $user, false); - }); + isActivated: $isActivated, + }, $user, false) + }) context('when FlowService#createFlow fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowService#createFlow succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.getFlowsByUserEndPoint()', () => { - def('user', () => 'user!'); + def('user', () => 'user!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getFlowsByUserEndPoint($req, $user)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getFlowsByUserEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(FlowService, 'getUserFlows').returns($response); - }); + $sandbox.stub(FlowService, 'getUserFlows').returns($response) + }) it('calls FlowService.getUserFlows with correct args', async () => { - await $subject; + await $subject expect(FlowService.getUserFlows).to.have.been.calledWith($user, false) - }); + }) context('when FlowService#getUserFlows fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowService#getUserFlows succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - - }); + }) describe('.getFlowEndPoint()', () => { - def('user', () => 'user!'); - def('id', () => 15); + def('user', () => 'user!') + def('id', () => 15) def('req', () => ({ params: { - id: $id - } - })); + id: $id, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.getFlowEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.getFlowEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(FlowService, 'getFlowWithTransaction').returns($response); - }); + $sandbox.stub(FlowService, 'getFlowWithTransaction').returns($response) + }) it('calls FlowService.getFlowWithTransaction with correct args', async () => { - await $subject; - expect(FlowService.getFlowWithTransaction).to.have.been.calledWith($id, $user, false); - }); + await $subject + expect(FlowService.getFlowWithTransaction).to.have.been.calledWith($id, $user, false) + }) context('when FlowService#getFlowWithTransaction fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowService#getFlowWithTransaction succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.updateFlowEndPoint()', () => { - def('user', () => 'user!'); - def('id', () => 15); + def('user', () => 'user!') + def('id', () => 15) - def('name', () => 'updatedTestName'); - def('description', () => 'updatedTestDescription'); - def('isActivated', () => false); + def('name', () => 'updatedTestName') + def('description', () => 'updatedTestDescription') + def('isActivated', () => false) def('req', () => ({ params: { - id: $id + id: $id, }, body: { name: $name, description: $description, - isActivated: $isActivated - } - })); + isActivated: $isActivated, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.updateFlowEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.updateFlowEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(FlowService, 'updateFlow').returns($response); - }); + $sandbox.stub(FlowService, 'updateFlow').returns($response) + }) it('calls FlowService.updateFlow with correct args', async () => { - await $subject; + await $subject expect(FlowService.updateFlow).to.have.been.calledWith({ name: $name, description: $description, - isActivated: $isActivated - }, $id, $user, false); - }); + isActivated: $isActivated, + }, $id, $user, false) + }) context('when FlowService#updateFlow fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowService#updateFlow succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.deleteFlowEndPoint()', () => { - def('user', () => 'user!'); - def('id', () => 15); + def('user', () => 'user!') + def('id', () => 15) def('req', () => ({ params: { - id: $id - } - })); + id: $id, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.deleteFlowEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.deleteFlowEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(FlowService, 'deleteFlow').returns($response); - }); + $sandbox.stub(FlowService, 'deleteFlow').returns($response) + }) it('calls FlowService.deleteFlow with correct args', async () => { - await $subject; - expect(FlowService.deleteFlow).to.have.been.calledWith($id, $user, false); - }); + await $subject + expect(FlowService.deleteFlow).to.have.been.calledWith($id, $user, false) + }) context('when FlowService.deleteFlow fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowService.deleteFlow succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - - }); - -}); \ No newline at end of file + }) +}) diff --git a/test/src/controllers/iofog-controller.test.js b/test/src/controllers/iofog-controller.test.js index 9405c625d..5a74fb5c6 100644 --- a/test/src/controllers/iofog-controller.test.js +++ b/test/src/controllers/iofog-controller.test.js @@ -1,40 +1,40 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); +const {expect} = require('chai') +const sinon = require('sinon') -const ioFogController = require('../../../src/controllers/iofog-controller'); -const ioFogService = require('../../../src/services/iofog-service'); -const qs = require('qs'); +const ioFogController = require('../../../src/controllers/iofog-controller') +const ioFogService = require('../../../src/services/iofog-service') +const qs = require('qs') describe('ioFog Controller', () => { - def('subject', () => ioFogController); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => ioFogController) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.createFogEndPoint()', () => { - def('user', () => 'user!'); - - def('name', () => 'testName'); - def('location', () => 'testLocation'); - def('latitude', () => 15); - def('longitude', () => 16); - def('description', () => 'testDescription'); - def('dockerUrl', () => 'testDockerUrl'); - def('diskLimit', () => 25); - def('diskDirectory', () => 'testDiskDirectory'); - def('memoryLimit', () => 35); - def('cpuLimit', () => 45); - def('logLimit', () => 15); - def('logDirectory', () => 'testLogDirectory'); - def('logFileCount', () => 8); - def('statusFrequency', 6); - def('changeFrequency', 18); - def('deviceScanFrequency', 28); - def('bluetoothEnabled', () => false); - def('watchdogEnabled', () => true); - def('abstractedHardwareEnabled', () => false); - def('fogType', () => 0); + def('user', () => 'user!') + + def('name', () => 'testName') + def('location', () => 'testLocation') + def('latitude', () => 15) + def('longitude', () => 16) + def('description', () => 'testDescription') + def('dockerUrl', () => 'testDockerUrl') + def('diskLimit', () => 25) + def('diskDirectory', () => 'testDiskDirectory') + def('memoryLimit', () => 35) + def('cpuLimit', () => 45) + def('logLimit', () => 15) + def('logDirectory', () => 'testLogDirectory') + def('logFileCount', () => 8) + def('statusFrequency', 6) + def('changeFrequency', 18) + def('deviceScanFrequency', 28) + def('bluetoothEnabled', () => false) + def('watchdogEnabled', () => true) + def('abstractedHardwareEnabled', () => false) + def('fogType', () => 0) def('req', () => ({ body: { @@ -57,19 +57,19 @@ describe('ioFog Controller', () => { bluetoothEnabled: $bluetoothEnabled, watchdogEnabled: $watchdogEnabled, abstractedHardwareEnabled: $abstractedHardwareEnabled, - fogType: $fogType - } - })); + fogType: $fogType, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.createFogEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.createFogEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(ioFogService, 'createFog').returns($response); - }); + $sandbox.stub(ioFogService, 'createFog').returns($response) + }) it('calls ioFogService.createFog with correct args', async () => { - await $subject; + await $subject expect(ioFogService.createFog).to.have.been.calledWith({ name: $name, location: $location, @@ -90,55 +90,55 @@ describe('ioFog Controller', () => { bluetoothEnabled: $bluetoothEnabled, watchdogEnabled: $watchdogEnabled, abstractedHardwareEnabled: $abstractedHardwareEnabled, - fogType: $fogType - }, $user, false); - }); + fogType: $fogType, + }, $user, false) + }) context('when ioFogService#createFog fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogService#createFog succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.updateFogEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); - - def('name', () => 'testName'); - def('location', () => 'testLocation'); - def('latitude', () => 15); - def('longitude', () => 16); - def('description', () => 'testDescription'); - def('dockerUrl', () => 'testDockerUrl'); - def('diskLimit', () => 25); - def('diskDirectory', () => 'testDiskDirectory'); - def('memoryLimit', () => 35); - def('cpuLimit', () => 45); - def('logLimit', () => 15); - def('logDirectory', () => 'testLogDirectory'); - def('logFileCount', () => 8); - def('statusFrequency', 6); - def('changeFrequency', 18); - def('deviceScanFrequency', 28); - def('bluetoothEnabled', () => false); - def('watchdogEnabled', () => true); - def('abstractedHardwareEnabled', () => false); - def('fogType', () => 0); + def('user', () => 'user!') + def('uuid', () => 'testUuid') + + def('name', () => 'testName') + def('location', () => 'testLocation') + def('latitude', () => 15) + def('longitude', () => 16) + def('description', () => 'testDescription') + def('dockerUrl', () => 'testDockerUrl') + def('diskLimit', () => 25) + def('diskDirectory', () => 'testDiskDirectory') + def('memoryLimit', () => 35) + def('cpuLimit', () => 45) + def('logLimit', () => 15) + def('logDirectory', () => 'testLogDirectory') + def('logFileCount', () => 8) + def('statusFrequency', 6) + def('changeFrequency', 18) + def('deviceScanFrequency', 28) + def('bluetoothEnabled', () => false) + def('watchdogEnabled', () => true) + def('abstractedHardwareEnabled', () => false) + def('fogType', () => 0) def('req', () => ({ params: { - uuid: $uuid + uuid: $uuid, }, body: { name: $name, @@ -160,18 +160,18 @@ describe('ioFog Controller', () => { bluetoothEnabled: $bluetoothEnabled, watchdogEnabled: $watchdogEnabled, abstractedHardwareEnabled: $abstractedHardwareEnabled, - fogType: $fogType - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.updateFogEndPoint($req, $user)); + fogType: $fogType, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.updateFogEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(ioFogService, 'updateFog').returns($response); - }); + $sandbox.stub(ioFogService, 'updateFog').returns($response) + }) it('calls ioFogService.updateFog with correct args', async () => { - await $subject; + await $subject expect(ioFogService.updateFog).to.have.been.calledWith({ uuid: $uuid, name: $name, @@ -193,155 +193,154 @@ describe('ioFog Controller', () => { bluetoothEnabled: $bluetoothEnabled, watchdogEnabled: $watchdogEnabled, abstractedHardwareEnabled: $abstractedHardwareEnabled, - fogType: $fogType + fogType: $fogType, }, $user, false) - }); + }) context('when ioFogService#updateFog fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogService#updateFog succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - - }); + }) describe('.deleteFogEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'newTestUuid'); + def('user', () => 'user!') + def('uuid', () => 'newTestUuid') def('req', () => ({ params: { - uuid: $uuid - } - })); + uuid: $uuid, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.deleteFogEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.deleteFogEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(ioFogService, 'deleteFog').returns($response); - }); + $sandbox.stub(ioFogService, 'deleteFog').returns($response) + }) it('calls ioFogService.deleteFog with correct args', async () => { - await $subject; - expect(ioFogService.deleteFog).to.have.been.calledWith({uuid: $uuid}, $user, false); - }); + await $subject + expect(ioFogService.deleteFog).to.have.been.calledWith({uuid: $uuid}, $user, false) + }) context('when ioFogService#deleteFog fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogService#deleteFog succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.getFogEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') def('req', () => ({ params: { - uuid: $uuid - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getFogEndPoint($req, $user)); + uuid: $uuid, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getFogEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(ioFogService, 'getFogWithTransaction').returns($response); - }); + $sandbox.stub(ioFogService, 'getFogWithTransaction').returns($response) + }) it('calls ioFogService.getFogWithTransaction with correct args', async () => { - await $subject; - expect(ioFogService.getFogWithTransaction).to.have.been.calledWith({uuid: $uuid}, $user, false); - }); + await $subject + expect(ioFogService.getFogWithTransaction).to.have.been.calledWith({uuid: $uuid}, $user, false) + }) context('when ioFogService#getFogWithTransaction fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogService#getFogWithTransaction succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.getFogListEndPoint()', () => { - def('user', () => 'user!'); - def('filters', () => 'filtersQuery'); + def('user', () => 'user!') + def('filters', () => 'filtersQuery') def('req', () => ({ query: { - filters: $filters - } - })); - def('response', () => Promise.resolve()); + filters: $filters, + }, + })) + def('response', () => Promise.resolve()) def('queryParseResponse', () => ({ - filters: $filters - })); - def('subject', () => $subject.getFogListEndPoint($req, $user)); + filters: $filters, + })) + def('subject', () => $subject.getFogListEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(qs, 'parse').returns($queryParseResponse); - $sandbox.stub(ioFogService, 'getFogList').returns($response); - }); + $sandbox.stub(qs, 'parse').returns($queryParseResponse) + $sandbox.stub(ioFogService, 'getFogList').returns($response) + }) it('calls qs.parse with correct args', async () => { - await $subject; - expect(qs.parse).to.have.been.calledWith($queryParseResponse); - }); + await $subject + expect(qs.parse).to.have.been.calledWith($queryParseResponse) + }) context('when qs.parse fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when qs.parse succeeds', () => { it('calls ioFogService.getFogList with correct args', async () => { - await $subject; - expect(ioFogService.getFogList).to.have.been.calledWith($filters, $user, false); - }); + await $subject + expect(ioFogService.getFogList).to.have.been.calledWith($filters, $user, false) + }) context('when ioFogService.getFogList fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogService.getFogList succeeds', () => { it(`succeeds`, () => { @@ -349,201 +348,200 @@ describe('ioFog Controller', () => { }) }) }) - }); + }) describe('.generateProvisionKeyEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') def('req', () => ({ params: { - uuid: $uuid - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.generateProvisioningKeyEndPoint($req, $user)); + uuid: $uuid, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.generateProvisioningKeyEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(ioFogService, 'generateProvisioningKey').returns($response); - }); + $sandbox.stub(ioFogService, 'generateProvisioningKey').returns($response) + }) it('calls ioFogService.generateProvisioningKey with correct args', async () => { - await $subject; - expect(ioFogService.generateProvisioningKey).to.have.been.calledWith({uuid: $uuid}, $user, false); - }); + await $subject + expect(ioFogService.generateProvisioningKey).to.have.been.calledWith({uuid: $uuid}, $user, false) + }) context('when ioFogService#generateProvisioningKey fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogService#generateProvisioningKey succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('setFogVersionCommandEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); - def('versionCommand', () => 'version'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') + def('versionCommand', () => 'version') def('req', () => ({ params: { uuid: $uuid, - versionCommand: $versionCommand - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.setFogVersionCommandEndPoint($req, $user)); + versionCommand: $versionCommand, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.setFogVersionCommandEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(ioFogService, 'setFogVersionCommand').returns($response); - }); + $sandbox.stub(ioFogService, 'setFogVersionCommand').returns($response) + }) it('calls ioFogService.setFogVersionCommand with correct args', async () => { - await $subject; + await $subject expect(ioFogService.setFogVersionCommand).to.have.been.calledWith({ uuid: $uuid, - versionCommand: $versionCommand - }, $user, false); - }); + versionCommand: $versionCommand, + }, $user, false) + }) context('when ioFogService#setFogVersionCommand fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogService#setFogVersionCommand succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('setFogRebootCommandEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') def('req', () => ({ params: { - uuid: $uuid - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.setFogRebootCommandEndPoint($req, $user)); + uuid: $uuid, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.setFogRebootCommandEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(ioFogService, 'setFogRebootCommand').returns($response); - }); + $sandbox.stub(ioFogService, 'setFogRebootCommand').returns($response) + }) it('calls ioFogService.setFogRebootCommand with correct args', async () => { - await $subject; - expect(ioFogService.setFogRebootCommand).to.have.been.calledWith({uuid: $uuid}, $user, false); - }); + await $subject + expect(ioFogService.setFogRebootCommand).to.have.been.calledWith({uuid: $uuid}, $user, false) + }) context('when ioFogService#setFogRebootCommand fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogService#setFogRebootCommand succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('getHalHardwareInfoEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') def('req', () => ({ params: { - uuid: $uuid - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getHalHardwareInfoEndPoint($req, $user)); + uuid: $uuid, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getHalHardwareInfoEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(ioFogService, 'getHalHardwareInfo').returns($response); - }); + $sandbox.stub(ioFogService, 'getHalHardwareInfo').returns($response) + }) it('calls ioFogService.getHalHardwareInfo with correct args', async () => { - await $subject; - expect(ioFogService.getHalHardwareInfo).to.have.been.calledWith({uuid: $uuid}, $user, false); - }); + await $subject + expect(ioFogService.getHalHardwareInfo).to.have.been.calledWith({uuid: $uuid}, $user, false) + }) context('when ioFogService#getHalHardwareInfo fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogService#getHalHardwareInfo succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('getHalUsbInfoEndPoint.()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') def('req', () => ({ params: { - uuid: $uuid - } - })); - def('response', () => Promise.resolve({info: undefined})); - def('subject', () => $subject.getHalUsbInfoEndPoint($req, $user)); + uuid: $uuid, + }, + })) + def('response', () => Promise.resolve({info: undefined})) + def('subject', () => $subject.getHalUsbInfoEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(ioFogService, 'getHalUsbInfo').returns($response); - }); + $sandbox.stub(ioFogService, 'getHalUsbInfo').returns($response) + }) it('calls ioFogService.getHalUsbInfo with correct args', async () => { - await $subject; - expect(ioFogService.getHalUsbInfo).to.have.been.calledWith({uuid: $uuid}, $user, false); - }); + await $subject + expect(ioFogService.getHalUsbInfo).to.have.been.calledWith({uuid: $uuid}, $user, false) + }) context('when ioFogService#getHalUsbInfo fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogService#getHalUsbInfo succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.have.property('info'); + return expect($subject).to.eventually.have.property('info') }) }) - }); - -}); \ No newline at end of file + }) +}) diff --git a/test/src/controllers/microservices-controller.test.js b/test/src/controllers/microservices-controller.test.js index 897400c65..261c476ac 100644 --- a/test/src/controllers/microservices-controller.test.js +++ b/test/src/controllers/microservices-controller.test.js @@ -1,40 +1,40 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); +const {expect} = require('chai') +const sinon = require('sinon') -const MicroservicesController = require('../../../src/controllers/microservices-controller'); -const MicroservicesService = require('../../../src/services/microservices-service'); +const MicroservicesController = require('../../../src/controllers/microservices-controller') +const MicroservicesService = require('../../../src/services/microservices-service') describe('Microservices Controller', () => { - def('subject', () => MicroservicesController); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => MicroservicesController) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.createMicroserviceOnFogEndPoint()', () => { - def('user', () => 'user!'); - - def('name', () => 'testName'); - def('config', () => "{}"); - def('catalogItemId', () => 5); - def('flowId', () => 1); - def('iofogUuid', () => "testUuid"); - def('rootHostAccess', () => true); - def('logSize', () => 15); + def('user', () => 'user!') + + def('name', () => 'testName') + def('config', () => '{}') + def('catalogItemId', () => 5) + def('flowId', () => 1) + def('iofogUuid', () => 'testUuid') + def('rootHostAccess', () => true) + def('logSize', () => 15) def('volumeMappings', () => [{ - hostDestination: "/var/dest", - containerDestination: "/var/dest", - accessMode: true - }]); + hostDestination: '/var/dest', + containerDestination: '/var/dest', + accessMode: true, + }]) def('ports', () => [ { internal: 15, external: 55, - publicMode: true - } - ]); + publicMode: true, + }, + ]) def('routes', () => [ - "testAnotherUuid" - ]); + 'testAnotherUuid', + ]) def('req', () => ({ body: { @@ -47,19 +47,19 @@ describe('Microservices Controller', () => { logSize: $logSize, volumeMappings: $volumeMappings, ports: $ports, - routes: $routes - } - })); + routes: $routes, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.createMicroserviceOnFogEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.createMicroserviceOnFogEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(MicroservicesService, 'createMicroservice').returns($response); - }); + $sandbox.stub(MicroservicesService, 'createMicroservice').returns($response) + }) it('calls MicroservicesService.createMicroservice with correct args', async () => { - await $subject; + await $subject expect(MicroservicesService.createMicroservice).to.have.been.calledWith({ name: $name, config: $config, @@ -70,86 +70,85 @@ describe('Microservices Controller', () => { logSize: $logSize, volumeMappings: $volumeMappings, ports: $ports, - routes: $routes - }, $user, false); - }); + routes: $routes, + }, $user, false) + }) context('when MicroservicesService#createMicroservice fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicesService#createMicroservice succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.getMicroserviceEndPoint()', () => { - def('user', () => 'user!'); + def('user', () => 'user!') - def('uuid', () => 'testUuid'); + def('uuid', () => 'testUuid') def('req', () => ({ params: { - uuid: $uuid - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getMicroserviceEndPoint($req, $user)); + uuid: $uuid, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getMicroserviceEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(MicroservicesService, 'getMicroservice').returns($response); - }); + $sandbox.stub(MicroservicesService, 'getMicroservice').returns($response) + }) it('calls MicroservicesService.getMicroservice with correct args', async () => { - await $subject; + await $subject expect(MicroservicesService.getMicroservice).to.have.been.calledWith($uuid, $user, false) - }); + }) context('when MicroservicesService#getMicroservice fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicesService#getMicroservice succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - - }); + }) describe('.updateMicroserviceEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'newTestUuid'); - - def('name', () => 'testName'); - def('config', () => "{}"); - def('rebuild', () => true); - def('iofogUuid', () => "testUuid"); - def('rootHostAccess', () => true); - def('logSize', () => 15); + def('user', () => 'user!') + def('uuid', () => 'newTestUuid') + + def('name', () => 'testName') + def('config', () => '{}') + def('rebuild', () => true) + def('iofogUuid', () => 'testUuid') + def('rootHostAccess', () => true) + def('logSize', () => 15) def('volumeMappings', () => [{ - hostDestination: "/var/dest", - containerDestination: "/var/dest", - accessMode: true - }]); + hostDestination: '/var/dest', + containerDestination: '/var/dest', + accessMode: true, + }]) def('req', () => ({ params: { - uuid: $uuid + uuid: $uuid, }, body: { name: $name, @@ -158,19 +157,19 @@ describe('Microservices Controller', () => { iofogUuid: $iofogUuid, rootHostAccess: $rootHostAccess, logSize: $logSize, - volumeMappings: $volumeMappings - } - })); + volumeMappings: $volumeMappings, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.updateMicroserviceEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.updateMicroserviceEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(MicroservicesService, 'updateMicroservice').returns($response); - }); + $sandbox.stub(MicroservicesService, 'updateMicroservice').returns($response) + }) it('calls MicroservicesService.updateMicroservice with correct args', async () => { - await $subject; + await $subject expect(MicroservicesService.updateMicroservice).to.have.been.calledWith($uuid, { name: $name, config: $config, @@ -178,445 +177,444 @@ describe('Microservices Controller', () => { iofogUuid: $iofogUuid, rootHostAccess: $rootHostAccess, logSize: $logSize, - volumeMappings: $volumeMappings - }, $user, false); - }); + volumeMappings: $volumeMappings, + }, $user, false) + }) context('when MicroservicesService#updateMicroservice fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicesService#updateMicroservice succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.deleteMicroserviceEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') - def('withCleanup', () => 'withCleanup'); + def('withCleanup', () => 'withCleanup') def('req', () => ({ params: { - uuid: $uuid + uuid: $uuid, }, body: { - withCleanup: $withCleanup - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.deleteMicroserviceEndPoint($req, $user)); + withCleanup: $withCleanup, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.deleteMicroserviceEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(MicroservicesService, 'deleteMicroservice').returns($response); - }); + $sandbox.stub(MicroservicesService, 'deleteMicroservice').returns($response) + }) it('calls MicroservicesService.deleteMicroservice with correct args', async () => { - await $subject; + await $subject expect(MicroservicesService.deleteMicroservice).to.have.been.calledWith($uuid, { - withCleanup: $withCleanup - }, $user, false); - }); + withCleanup: $withCleanup, + }, $user, false) + }) context('when MicroservicesService#deleteMicroservice fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicesService#deleteMicroservice succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.getMicroservicesByFlowEndPoint()', () => { - def('user', () => 'user!'); - def('flowId', () => 1); + def('user', () => 'user!') + def('flowId', () => 1) def('req', () => ({ query: { - flowId: $flowId - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getMicroservicesByFlowEndPoint($req, $user)); + flowId: $flowId, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getMicroservicesByFlowEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(MicroservicesService, 'listMicroservices').returns($response); - }); + $sandbox.stub(MicroservicesService, 'listMicroservices').returns($response) + }) it('calls MicroservicesService.listMicroservices with correct args', async () => { - await $subject; - expect(MicroservicesService.listMicroservices).to.have.been.calledWith($flowId, $user, false); - }); + await $subject + expect(MicroservicesService.listMicroservices).to.have.been.calledWith($flowId, $user, false) + }) context('when MicroservicesService#listMicroservices fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicesService#listMicroservices succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.createMicroserviceRouteEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); - def('receiverUuid', () => 'testReceiverUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') + def('receiverUuid', () => 'testReceiverUuid') def('req', () => ({ params: { uuid: $uuid, - receiverUuid: $receiverUuid - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.createMicroserviceRouteEndPoint($req, $user)); + receiverUuid: $receiverUuid, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.createMicroserviceRouteEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(MicroservicesService, 'createRoute').returns($response); - }); + $sandbox.stub(MicroservicesService, 'createRoute').returns($response) + }) it('calls MicroservicesService.createRoute with correct args', async () => { - await $subject; - expect(MicroservicesService.createRoute).to.have.been.calledWith($uuid, $receiverUuid, $user, false); - }); + await $subject + expect(MicroservicesService.createRoute).to.have.been.calledWith($uuid, $receiverUuid, $user, false) + }) context('when MicroservicesService#createRoute fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicesService#createRoute succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('deleteMicroserviceRouteEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); - def('receiverUuid', () => 'testReceiverUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') + def('receiverUuid', () => 'testReceiverUuid') def('req', () => ({ params: { uuid: $uuid, - receiverUuid: $receiverUuid - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.deleteMicroserviceRouteEndPoint($req, $user)); + receiverUuid: $receiverUuid, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.deleteMicroserviceRouteEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(MicroservicesService, 'deleteRoute').returns($response); - }); + $sandbox.stub(MicroservicesService, 'deleteRoute').returns($response) + }) it('calls MicroservicesService.deleteRoute with correct args', async () => { - await $subject; - expect(MicroservicesService.deleteRoute).to.have.been.calledWith($uuid, $receiverUuid, $user, false); - }); + await $subject + expect(MicroservicesService.deleteRoute).to.have.been.calledWith($uuid, $receiverUuid, $user, false) + }) context('when MicroservicesService#deleteRoute fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicesService#deleteRoute succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('createMicroservicePortMappingEndPoint.()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); - def('internal', () => 55); - def('external', () => 66); - def('publicMode', () => true); + def('user', () => 'user!') + def('uuid', () => 'testUuid') + def('internal', () => 55) + def('external', () => 66) + def('publicMode', () => true) def('req', () => ({ params: { - uuid: $uuid + uuid: $uuid, }, body: { internal: $internal, external: $external, - publicMode: $publicMode - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.createMicroservicePortMappingEndPoint($req, $user)); + publicMode: $publicMode, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.createMicroservicePortMappingEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(MicroservicesService, 'createPortMapping').returns($response); - }); + $sandbox.stub(MicroservicesService, 'createPortMapping').returns($response) + }) it('calls MicroservicesService.createPortMapping with correct args', async () => { - await $subject; + await $subject expect(MicroservicesService.createPortMapping).to.have.been.calledWith($uuid, { internal: $internal, external: $external, - publicMode: $publicMode - }, $user, false); - }); + publicMode: $publicMode, + }, $user, false) + }) context('when MicroservicesService#createPortMapping fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicesService#createPortMapping succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('deleteMicroservicePortMappingEndPoint.()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); - def('internalPort', () => 55); + def('user', () => 'user!') + def('uuid', () => 'testUuid') + def('internalPort', () => 55) def('req', () => ({ params: { uuid: $uuid, - internalPort: $internalPort - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.deleteMicroservicePortMappingEndPoint($req, $user)); + internalPort: $internalPort, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.deleteMicroservicePortMappingEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(MicroservicesService, 'deletePortMapping').returns($response); - }); + $sandbox.stub(MicroservicesService, 'deletePortMapping').returns($response) + }) it('calls MicroservicesService.deletePortMapping with correct args', async () => { - await $subject; - expect(MicroservicesService.deletePortMapping).to.have.been.calledWith($uuid, $internalPort, $user, false); - }); + await $subject + expect(MicroservicesService.deletePortMapping).to.have.been.calledWith($uuid, $internalPort, $user, false) + }) context('when MicroservicesService#deletePortMapping fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicesService#deletePortMapping succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('getMicroservicePortMappingListEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') def('req', () => ({ params: { - uuid: $uuid - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getMicroservicePortMappingListEndPoint($req, $user)); + uuid: $uuid, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getMicroservicePortMappingListEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(MicroservicesService, 'listMicroservicePortMappings').returns($response); - }); + $sandbox.stub(MicroservicesService, 'listMicroservicePortMappings').returns($response) + }) it('calls MicroservicesService.listMicroservicePortMappings with correct args', async () => { - await $subject; - expect(MicroservicesService.listMicroservicePortMappings).to.have.been.calledWith($uuid, $user, false); - }); + await $subject + expect(MicroservicesService.listMicroservicePortMappings).to.have.been.calledWith($uuid, $user, false) + }) context('when MicroservicesService#listMicroservicePortMappings fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicesService#listMicroservicePortMappings succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.have.property('ports'); + return expect($subject).to.eventually.have.property('ports') }) }) - }); + }) describe('createMicroserviceVolumeMappingEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') - def('hostDestination', () => '/var/dest'); - def('containerDestination', () => '/var/dest'); - def('accessMode', () => 'rw'); + def('hostDestination', () => '/var/dest') + def('containerDestination', () => '/var/dest') + def('accessMode', () => 'rw') def('req', () => ({ params: { - uuid: $uuid + uuid: $uuid, }, body: { hostDestination: $hostDestination, containerDestination: $containerDestination, - accessMode: $accessMode - } - })); - def('response', () => Promise.resolve({id: 15})); - def('subject', () => $subject.createMicroserviceVolumeMappingEndPoint($req, $user)); + accessMode: $accessMode, + }, + })) + def('response', () => Promise.resolve({id: 15})) + def('subject', () => $subject.createMicroserviceVolumeMappingEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(MicroservicesService, 'createVolumeMapping').returns($response); - }); + $sandbox.stub(MicroservicesService, 'createVolumeMapping').returns($response) + }) it('calls MicroservicesService.createVolumeMapping with correct args', async () => { - await $subject; + await $subject expect(MicroservicesService.createVolumeMapping).to.have.been.calledWith($uuid, { hostDestination: $hostDestination, containerDestination: $containerDestination, - accessMode: $accessMode - }, $user, false); - }); + accessMode: $accessMode, + }, $user, false) + }) context('when MicroservicesService#createVolumeMapping fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicesService#createVolumeMapping succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.have.property('id'); + return expect($subject).to.eventually.have.property('id') }) }) - }); + }) describe('listMicroserviceVolumeMappingsEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); + def('user', () => 'user!') + def('uuid', () => 'testUuid') def('req', () => ({ params: { - uuid: $uuid - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.listMicroserviceVolumeMappingsEndPoint($req, $user)); + uuid: $uuid, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.listMicroserviceVolumeMappingsEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(MicroservicesService, 'listVolumeMappings').returns($response); - }); + $sandbox.stub(MicroservicesService, 'listVolumeMappings').returns($response) + }) it('calls MicroservicesService.listVolumeMappings with correct args', async () => { - await $subject; - expect(MicroservicesService.listVolumeMappings).to.have.been.calledWith($uuid, $user, false); - }); + await $subject + expect(MicroservicesService.listVolumeMappings).to.have.been.calledWith($uuid, $user, false) + }) context('when MicroservicesService#listVolumeMappings fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicesService#listVolumeMappings succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.have.property('volumeMappings'); + return expect($subject).to.eventually.have.property('volumeMappings') }) }) - }); + }) describe('deleteMicroserviceVolumeMappingEndPoint()', () => { - def('user', () => 'user!'); - def('uuid', () => 'testUuid'); - def('id', () => 35); + def('user', () => 'user!') + def('uuid', () => 'testUuid') + def('id', () => 35) def('req', () => ({ params: { uuid: $uuid, - id: $id - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.deleteMicroserviceVolumeMappingEndPoint($req, $user)); + id: $id, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.deleteMicroserviceVolumeMappingEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(MicroservicesService, 'deleteVolumeMapping').returns($response); - }); + $sandbox.stub(MicroservicesService, 'deleteVolumeMapping').returns($response) + }) it('calls MicroservicesService.deleteVolumeMapping with correct args', async () => { - await $subject; - expect(MicroservicesService.deleteVolumeMapping).to.have.been.calledWith($uuid, $id, $user, false); - }); + await $subject + expect(MicroservicesService.deleteVolumeMapping).to.have.been.calledWith($uuid, $id, $user, false) + }) context('when MicroservicesService#deleteVolumeMapping fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicesService#deleteVolumeMapping succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); - -}); \ No newline at end of file + }) +}) diff --git a/test/src/controllers/registry-controller.test.js b/test/src/controllers/registry-controller.test.js index 843d539d4..2cc4328af 100644 --- a/test/src/controllers/registry-controller.test.js +++ b/test/src/controllers/registry-controller.test.js @@ -1,25 +1,25 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); +const {expect} = require('chai') +const sinon = require('sinon') -const RegistryController = require('../../../src/controllers/registry-controller'); -const RegistryService = require('../../../src/services/registry-service'); +const RegistryController = require('../../../src/controllers/registry-controller') +const RegistryService = require('../../../src/services/registry-service') describe('Registry Controller', () => { - def('subject', () => RegistryController); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => RegistryController) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.createRegistryEndPoint()', () => { - def('user', () => 'user!'); + def('user', () => 'user!') - def('url', () => 'url'); - def('isPublic', () => true); - def('username', () => 'testUsername'); - def('password', () => 'testPassword'); - def('email', () => 'test@gmail.com'); - def('requiresCert', () => true); - def('certificate', () => "certificateString"); + def('url', () => 'url') + def('isPublic', () => true) + def('username', () => 'testUsername') + def('password', () => 'testPassword') + def('email', () => 'test@gmail.com') + def('requiresCert', () => true) + def('certificate', () => 'certificateString') def('req', () => ({ body: { @@ -29,19 +29,19 @@ describe('Registry Controller', () => { password: $password, email: $email, requiresCert: $requiresCert, - certificate: $certificate - } - })); + certificate: $certificate, + }, + })) - def('response', () => Promise.resolve()); - def('subject', () => $subject.createRegistryEndPoint($req, $user)); + def('response', () => Promise.resolve()) + def('subject', () => $subject.createRegistryEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(RegistryService, 'createRegistry').returns($response); - }); + $sandbox.stub(RegistryService, 'createRegistry').returns($response) + }) it('calls RegistryService.createRegistry with correct args', async () => { - await $subject; + await $subject expect(RegistryService.createRegistry).to.have.been.calledWith({ url: $url, isPublic: $isPublic, @@ -49,118 +49,117 @@ describe('Registry Controller', () => { password: $password, email: $email, requiresCert: $requiresCert, - certificate: $certificate - }, $user); - }); + certificate: $certificate, + }, $user) + }) context('when RegistryService#createRegistry fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when RegistryService#createRegistry succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.getRegistriesEndPoint()', () => { - def('user', () => 'user!'); + def('user', () => 'user!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getRegistriesEndPoint($req, $user)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getRegistriesEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(RegistryService, 'findRegistries').returns($response); - }); + $sandbox.stub(RegistryService, 'findRegistries').returns($response) + }) it('calls RegistryService.findRegistries with correct args', async () => { - await $subject; + await $subject expect(RegistryService.findRegistries).to.have.been.calledWith($user, false) - }); + }) context('when RegistryService#findRegistries fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when RegistryService#findRegistries succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - - }); + }) describe('.deleteRegistryEndPoint()', () => { - def('user', () => 'user!'); - def('id', () => 15); + def('user', () => 'user!') + def('id', () => 15) def('req', () => ({ params: { - id: $id - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.deleteRegistryEndPoint($req, $user)); + id: $id, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.deleteRegistryEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(RegistryService, 'deleteRegistry').returns($response); - }); + $sandbox.stub(RegistryService, 'deleteRegistry').returns($response) + }) it('calls RegistryService.deleteRegistry with correct args', async () => { - await $subject; + await $subject expect(RegistryService.deleteRegistry).to.have.been.calledWith({ - id: parseInt($req.params.id) + id: parseInt($req.params.id), }, $user, false) - }); + }) context('when RegistryService#deleteRegistry fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when RegistryService#deleteRegistry succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.updateRegistryEndPoint()', () => { - def('user', () => 'user!'); - def('id', () => 15); + def('user', () => 'user!') + def('id', () => 15) - def('url', () => 'updatedUrl'); - def('isPublic', () => false); - def('username', () => 'updatedUsername'); - def('password', () => 'updatedPassword'); - def('email', () => 'updatedTest@gmail.com'); - def('requiresCert', () => false); - def('certificate', () => "updatedCertificateString"); + def('url', () => 'updatedUrl') + def('isPublic', () => false) + def('username', () => 'updatedUsername') + def('password', () => 'updatedPassword') + def('email', () => 'updatedTest@gmail.com') + def('requiresCert', () => false) + def('certificate', () => 'updatedCertificateString') def('req', () => ({ params: { - id: $id + id: $id, }, body: { url: $url, @@ -169,18 +168,18 @@ describe('Registry Controller', () => { password: $password, email: $email, requiresCert: $requiresCert, - certificate: $certificate - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.updateRegistryEndPoint($req, $user)); + certificate: $certificate, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.updateRegistryEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(RegistryService, 'updateRegistry').returns($response); - }); + $sandbox.stub(RegistryService, 'updateRegistry').returns($response) + }) it('calls RegistryService.updateRegistry with correct args', async () => { - await $subject; + await $subject expect(RegistryService.updateRegistry).to.have.been.calledWith({ url: $url, isPublic: $isPublic, @@ -188,24 +187,24 @@ describe('Registry Controller', () => { password: $password, email: $email, requiresCert: $requiresCert, - certificate: $certificate - }, $id, $user, false); - }); + certificate: $certificate, + }, $id, $user, false) + }) context('when RegistryService#updateRegistry fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when RegistryService#updateRegistry succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); -}); \ No newline at end of file + }) +}) diff --git a/test/src/controllers/tunnel-controller.test.js b/test/src/controllers/tunnel-controller.test.js index ab0cb2dd4..6841ffd52 100644 --- a/test/src/controllers/tunnel-controller.test.js +++ b/test/src/controllers/tunnel-controller.test.js @@ -1,8 +1,8 @@ -const { expect } = require('chai') +const {expect} = require('chai') const sinon = require('sinon') const TunnelController = require('../../../src/controllers/tunnel-controller') -const TunnelService = require('../../../src/services/tunnel-service'); +const TunnelService = require('../../../src/services/tunnel-service') describe('Tunnel Controller', () => { def('subject', () => TunnelController) @@ -33,7 +33,7 @@ describe('Tunnel Controller', () => { context('when action is "open"', async () => { it('calls TunnelService#openTunnel with correct args', async () => { await $subject - expect(TunnelService.openTunnel).to.have.been.calledWith({ iofogUuid: $id }, $user, false) + expect(TunnelService.openTunnel).to.have.been.calledWith({iofogUuid: $id}, $user, false) }) context('when TunnelService#openTunnel fails', () => { @@ -58,7 +58,7 @@ describe('Tunnel Controller', () => { it('calls TunnelService#closeTunnel with correct args', async () => { await $subject - expect(TunnelService.closeTunnel).to.have.been.calledWith({ iofogUuid: $id }, $user) + expect(TunnelService.closeTunnel).to.have.been.calledWith({iofogUuid: $id}, $user) }) context('when TunnelService#closeTunnel fails', () => { @@ -107,7 +107,7 @@ describe('Tunnel Controller', () => { it('calls TunnelService#findTunnel with correct args', async () => { await $subject - expect(TunnelService.findTunnel).to.have.been.calledWith({ iofogUuid: $id }, $user) + expect(TunnelService.findTunnel).to.have.been.calledWith({iofogUuid: $id}, $user) }) context('when TunnelService#findTunnel fails', () => { diff --git a/test/src/controllers/user-controller.test.js b/test/src/controllers/user-controller.test.js index 617ff8537..435c7d062 100644 --- a/test/src/controllers/user-controller.test.js +++ b/test/src/controllers/user-controller.test.js @@ -1,24 +1,24 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); +const {expect} = require('chai') +const sinon = require('sinon') -const UserController = require('../../../src/controllers/user-controller'); -const UserService = require('../../../src/services/user-service'); -const AppHelper = require('../../../src/helpers/app-helper'); -const Validator = require('../../../src/schemas'); +const UserController = require('../../../src/controllers/user-controller') +const UserService = require('../../../src/services/user-service') +const AppHelper = require('../../../src/helpers/app-helper') +const Validator = require('../../../src/schemas') describe('User Controller', () => { - def('subject', () => UserController); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => UserController) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) - const error = 'Error!'; + const error = 'Error!' describe('.userSignupEndPoint()', () => { - def('firstName', () => 'firstName'); - def('lastName', () => 'lastName'); - def('email', () => 'test@gmail.com'); - def('password', () => 'testPassword'); + def('firstName', () => 'firstName') + def('lastName', () => 'lastName') + def('email', () => 'test@gmail.com') + def('password', () => 'testPassword') def('req', () => ({ body: { @@ -26,454 +26,451 @@ describe('User Controller', () => { lastName: $lastName, email: $email, - password: $password - } - })); - def('response', () => Promise.resolve()); - def('encryptedPassword', () => 'encryptedPassword'); - def('validatorResponse', () => Promise.resolve(true)); - def('encryptTextResponse', () => $encryptedPassword); - def('subject', () => $subject.userSignupEndPoint($req)); + password: $password, + }, + })) + def('response', () => Promise.resolve()) + def('encryptedPassword', () => 'encryptedPassword') + def('validatorResponse', () => Promise.resolve(true)) + def('encryptTextResponse', () => $encryptedPassword) + def('subject', () => $subject.userSignupEndPoint($req)) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(AppHelper, 'encryptText').returns($encryptTextResponse); - $sandbox.stub(UserService, 'signUp').returns($response); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(AppHelper, 'encryptText').returns($encryptTextResponse) + $sandbox.stub(UserService, 'signUp').returns($response) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; + await $subject expect(Validator.validate).to.have.been.calledWith({ firstName: $firstName, lastName: $lastName, email: $email, - password: $password - }, Validator.schemas.signUp); - }); + password: $password, + }, Validator.schemas.signUp) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls AppHelper#encryptText() with correct args', async () => { - await $subject; - expect(AppHelper.encryptText).to.have.been.calledWith($password, $email); - }); + await $subject + expect(AppHelper.encryptText).to.have.been.calledWith($password, $email) + }) context('when AppHelper#encryptText() fails', () => { it('fails', () => { - return expect($subject).to.eventually.equal(undefined); - }); - }); + return expect($subject).to.eventually.equal(undefined) + }) + }) context('when AppHelper#encryptText() succeeds', () => { it('calls UserService.signUp with correct args', async () => { - await $subject; + await $subject expect(UserService.signUp).to.have.been.calledWith({ firstName: $firstName, lastName: $lastName, email: $email, - password: $encryptedPassword + password: $encryptedPassword, }, false) - }); + }) context('when UserService#signUp fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserService#signUp succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); - - }); - }); + }) + }) + }) describe('.userLoginEndPoint()', () => { - def('email', () => 'test@gmail.com'); - def('password', () => 'testPassword'); + def('email', () => 'test@gmail.com') + def('password', () => 'testPassword') def('req', () => ({ body: { email: $email, - password: $password - } - })); - def('response', () => Promise.resolve()); - def('validatorResponse', () => Promise.resolve(true)); - def('subject', () => $subject.userLoginEndPoint($req)); + password: $password, + }, + })) + def('response', () => Promise.resolve()) + def('validatorResponse', () => Promise.resolve(true)) + def('subject', () => $subject.userLoginEndPoint($req)) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(UserService, 'login').returns($response); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(UserService, 'login').returns($response) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; + await $subject expect(Validator.validate).to.have.been.calledWith({ email: $email, - password: $password - }, Validator.schemas.login); - }); + password: $password, + }, Validator.schemas.login) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls UserService.login with correct args', async () => { - await $subject; + await $subject expect(UserService.login).to.have.been.calledWith({ email: $email, - password: $password + password: $password, }, false) - }); + }) context('when UserService#login fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserService#login succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - - }); - }); + }) + }) describe('.resendActivationEndPoint()', () => { - def('email', () => 'test@gmail.com'); + def('email', () => 'test@gmail.com') def('req', () => ({ query: { - email: $email - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.resendActivationEndPoint($req)); + email: $email, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.resendActivationEndPoint($req)) beforeEach(() => { - $sandbox.stub(UserService, 'resendActivation').returns($response); - }); + $sandbox.stub(UserService, 'resendActivation').returns($response) + }) it('calls UserService.resendActivation with correct args', async () => { - await $subject; + await $subject expect(UserService.resendActivation).to.have.been.calledWith({ - email: $email + email: $email, }, false) - }); + }) context('when UserService#resendActivation fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserService#resendActivation succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.activateUserAccountEndPoint()', () => { - def('activationCode', () => 'testActivationCode'); + def('activationCode', () => 'testActivationCode') def('req', () => ({ body: { - activationCode: $activationCode - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.activateUserAccountEndPoint($req)); + activationCode: $activationCode, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.activateUserAccountEndPoint($req)) beforeEach(() => { - $sandbox.stub(UserService, 'activateUser').returns($response); - }); + $sandbox.stub(UserService, 'activateUser').returns($response) + }) it('calls UserService.activateUser with correct args', async () => { - await $subject; + await $subject expect(UserService.activateUser).to.have.been.calledWith({ - activationCode: $activationCode + activationCode: $activationCode, }, false) - }); + }) context('when UserService#activateUser fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserService#activateUser succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.userLogoutEndPoint()', () => { - def('activationCode', () => 'testActivationCode'); - def('user', () => 'user!'); + def('activationCode', () => 'testActivationCode') + def('user', () => 'user!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.userLogoutEndPoint($req, $user)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.userLogoutEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(UserService, 'logout').returns($response); - }); + $sandbox.stub(UserService, 'logout').returns($response) + }) it('calls UserService.logout with correct args', async () => { - await $subject; + await $subject expect(UserService.logout).to.have.been.calledWith($user, false) - }); + }) context('when UserService#logout fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserService#logout succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.getUserProfileEndPoint()', () => { - def('user', () => 'user!'); + def('user', () => 'user!') def('req', () => ({ - body: {} - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.getUserProfileEndPoint($req, $user)); + body: {}, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.getUserProfileEndPoint($req, $user)) it(`succeeds`, () => { - return expect($subject).to.eventually.include.all.keys(["firstName", "lastName", "email"]) + return expect($subject).to.eventually.include.all.keys(['firstName', 'lastName', 'email']) }) - }); + }) describe('.updateUserProfileEndPoint()', () => { - def('firstName', () => 'firstName2'); - def('lastName', () => 'lastName2'); - def('user', () => 'user!'); + def('firstName', () => 'firstName2') + def('lastName', () => 'lastName2') + def('user', () => 'user!') def('req', () => ({ body: { firstName: $firstName, - lastName: $lastName - } - })); - def('profileData', () => $req.body); - def('response', () => Promise.resolve()); - def('subject', () => $subject.updateUserProfileEndPoint($req, $user)); + lastName: $lastName, + }, + })) + def('profileData', () => $req.body) + def('response', () => Promise.resolve()) + def('subject', () => $subject.updateUserProfileEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(UserService, 'updateUserDetails').returns($response); - }); + $sandbox.stub(UserService, 'updateUserDetails').returns($response) + }) it('calls UserService.updateUserDetails with correct args', async () => { - await $subject; - expect(UserService.updateUserDetails).to.have.been.calledWith($user, $profileData, false); - }); + await $subject + expect(UserService.updateUserDetails).to.have.been.calledWith($user, $profileData, false) + }) context('when UserService#updateUserDetails fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserService#updateUserDetails succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.deleteUserProfileEndPoint()', () => { - def('user', () => 'user!'); + def('user', () => 'user!') def('req', () => ({ body: { - force: true - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.deleteUserProfileEndPoint($req, $user)); + force: true, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.deleteUserProfileEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(UserService, 'deleteUser').returns($response); - }); + $sandbox.stub(UserService, 'deleteUser').returns($response) + }) it('calls UserService.deleteUser with correct args', async () => { - await $subject; - expect(UserService.deleteUser).to.have.been.calledWith(true, $user, false); - }); + await $subject + expect(UserService.deleteUser).to.have.been.calledWith(true, $user, false) + }) context('when UserService#deleteUser fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserService#deleteUser succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.updateUserPasswordEndPoint()', () => { - def('user', () => 'user!'); + def('user', () => 'user!') - def('oldPassword', () => 'oldPassword'); - def('newPassword', () => 'newPassword'); + def('oldPassword', () => 'oldPassword') + def('newPassword', () => 'newPassword') def('req', () => ({ body: { oldPassword: $oldPassword, - newPassword: $newPassword - } - })); - def('response', () => Promise.resolve()); - def('validatorResponse', () => Promise.resolve(true)); - def('subject', () => $subject.updateUserPasswordEndPoint($req, $user)); + newPassword: $newPassword, + }, + })) + def('response', () => Promise.resolve()) + def('validatorResponse', () => Promise.resolve(true)) + def('subject', () => $subject.updateUserPasswordEndPoint($req, $user)) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(UserService, 'updateUserPassword').returns($response); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(UserService, 'updateUserPassword').returns($response) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; + await $subject expect(Validator.validate).to.have.been.calledWith({ oldPassword: $oldPassword, - newPassword: $newPassword - }, Validator.schemas.updatePassword); - }); + newPassword: $newPassword, + }, Validator.schemas.updatePassword) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls UserService.updateUserPassword with correct args', async () => { - await $subject; + await $subject expect(UserService.updateUserPassword).to.have.been.calledWith({ oldPassword: $oldPassword, - newPassword: $newPassword - }, $user, false); - }); + newPassword: $newPassword, + }, $user, false) + }) context('when UserService#updateUserPassword fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserService#updateUserPassword succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); - }); + }) + }) describe('.resetUserPasswordEndPoint()', () => { - def('user', () => 'user!'); + def('user', () => 'user!') - def('email', () => 'test@gmail.com'); + def('email', () => 'test@gmail.com') def('req', () => ({ body: { - email: $email - } - })); - def('response', () => Promise.resolve()); - def('subject', () => $subject.resetUserPasswordEndPoint($req)); + email: $email, + }, + })) + def('response', () => Promise.resolve()) + def('subject', () => $subject.resetUserPasswordEndPoint($req)) beforeEach(() => { - $sandbox.stub(UserService, 'resetUserPassword').returns($response); - }); + $sandbox.stub(UserService, 'resetUserPassword').returns($response) + }) it('calls UserService.resetUserPassword with correct args', async () => { - await $subject; + await $subject expect(UserService.resetUserPassword).to.have.been.calledWith({ - email: $email - }, false); - }); + email: $email, + }, false) + }) context('when UserService#resetUserPassword fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('response', () => Promise.reject(error)); + def('response', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserService#resetUserPassword succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); - -}); \ No newline at end of file + }) +}) diff --git a/test/src/helpers/app-helpers.test.js b/test/src/helpers/app-helpers.test.js index 0a14acf05..e12956ce0 100644 --- a/test/src/helpers/app-helpers.test.js +++ b/test/src/helpers/app-helpers.test.js @@ -1,88 +1,88 @@ -const crypto = require('crypto'); -const {expect} = require('chai'); -const fs = require('fs'); -const path = require('path'); -const portscanner = require('portscanner'); -const sinon = require('sinon'); +const crypto = require('crypto') +const {expect} = require('chai') +const fs = require('fs') +const path = require('path') +const portscanner = require('portscanner') +const sinon = require('sinon') -const AppHelpers = require('../../../src/helpers/app-helper'); -const Config = require('../../../src/config'); +const AppHelpers = require('../../../src/helpers/app-helper') +const Config = require('../../../src/config') describe('App Helpers', () => { - const text = 'some-text'; - const salt = 'kosher-salt'; - const encrypted = '18f4faa5c532708c8f'; - const processedSalt = 'c2cd22c1a8133704f09fc8a218088b1b'; - const encryptedPasswordLine = '17f4faa5c532708c8f:18f4faa5c532708c8f'; - - def('subject', () => AppHelpers); - def('sandbox', () => sinon.createSandbox()); + const text = 'some-text' + const salt = 'kosher-salt' + const encrypted = '18f4faa5c532708c8f' + const processedSalt = 'c2cd22c1a8133704f09fc8a218088b1b' + const encryptedPasswordLine = '17f4faa5c532708c8f:18f4faa5c532708c8f' + + def('subject', () => AppHelpers) + def('sandbox', () => sinon.createSandbox()) def('cipher', () => ({ update: $sandbox.stub().returns(''), - final: $sandbox.stub().returns(encrypted) - })); + final: $sandbox.stub().returns(encrypted), + })) def('decipher', () => ({ update: $sandbox.stub().returns(''), - final: $sandbox.stub().returns(text) - })); + final: $sandbox.stub().returns(text), + })) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.encryptText()', () => { - def('subject', () => $subject.encryptText(text, salt)); - def('iv', () => '17f4faa5c532708c8f'); + def('subject', () => $subject.encryptText(text, salt)) + def('iv', () => '17f4faa5c532708c8f') beforeEach(() => { - $sandbox.stub(crypto, 'randomBytes').returns($iv); - $sandbox.stub(crypto, 'createCipheriv').returns($cipher); - }); + $sandbox.stub(crypto, 'randomBytes').returns($iv) + $sandbox.stub(crypto, 'createCipheriv').returns($cipher) + }) it('calls crypto#createCipheriv() with correct args', () => { $subject expect(crypto.createCipheriv).to.have.been.calledWith('aes-256-ctr', processedSalt, $iv) - }); + }) it('calls crypto.cipher#update() with correct args', () => { $subject expect($cipher.update).to.have.been.calledWith(text, 'utf8', 'hex') - }); + }) it('calls crypto.cipher#final() with correct args', () => { $subject expect($cipher.final).to.have.been.calledWith('hex') - }); + }) it('returns the encrypted text', () => { expect($subject).to.equal(encryptedPasswordLine) }) - }); + }) describe('.decryptText()', () => { - def('iv', () => '17f4faa5c532708c8f'); - def('subject', () => $subject.decryptText(encryptedPasswordLine, salt)); + def('iv', () => '17f4faa5c532708c8f') + def('subject', () => $subject.decryptText(encryptedPasswordLine, salt)) beforeEach(() => { - $sandbox.stub(crypto, 'createDecipheriv').returns($decipher); - }); + $sandbox.stub(crypto, 'createDecipheriv').returns($decipher) + }) it('calls crypto.decipher#final() with correct args', () => { $subject expect($decipher.final).to.have.been.calledWith('utf8') - }); + }) it('returns the decrypted text', () => { expect($subject).to.equal(text) }) - }); + }) describe('.generateRandomString()', () => { - def('size', () => 12); + def('size', () => 12) context('when size is greater than zero', () => { it('returns a random string with length of size', () => { expect(AppHelpers.generateRandomString($size)).to.have.lengthOf($size) }) - }); + }) context('when size is zero', () => { def('size', () => 0) @@ -135,8 +135,8 @@ describe('App Helpers', () => { beforeEach(() => { $sandbox.stub(Config, 'get') - .withArgs('Tunnel:PortRange') - .returns(`${portRangeFrom}-${portRangeTo}`) + .withArgs('Tunnel:PortRange') + .returns(`${portRangeFrom}-${portRangeTo}`) $sandbox.stub(portscanner, 'findAPortNotInUse').returns(Promise.resolve(availablePort)) }) @@ -284,87 +284,86 @@ describe('App Helpers', () => { name: undefined, id: undefined, ioFogUuid: 'testIoFogUuid', - location: 'testLocation' - }; + location: 'testLocation', + } const output = { ioFogUuid: 'testIoFogUuid', - location: 'testLocation' - }; + location: 'testLocation', + } - def('subject', () => $subject.deleteUndefinedFields(input)); + def('subject', () => $subject.deleteUndefinedFields(input)) context('passing input object', () => { it('returns output without undefined values', () => { - expect($subject).to.be.deep.equal(output); + expect($subject).to.be.deep.equal(output) }) - }); - }); + }) + }) describe('.validateBooleanCliOptions()', () => { - def('trueOption', () => 'testOption'); - def('falseOption', () => 'testOption2'); - def('subject', () => $subject.validateBooleanCliOptions($trueOption, $falseOption)); + def('trueOption', () => 'testOption') + def('falseOption', () => 'testOption2') + def('subject', () => $subject.validateBooleanCliOptions($trueOption, $falseOption)) context('when true option is true and false option is false', () => { - def('trueOption', () => 'testOption'); - def('falseOption', () => undefined); + def('trueOption', () => 'testOption') + def('falseOption', () => undefined) it('returns true', () => { - expect($subject).to.be.equal(true); + expect($subject).to.be.equal(true) }) - }); + }) context('when true option is false and false option is true', () => { - def('trueOption', () => undefined); - def('falseOption', () => 'testOption'); + def('trueOption', () => undefined) + def('falseOption', () => 'testOption') it('returns false', () => { - expect($subject).to.be.equal(false); + expect($subject).to.be.equal(false) }) - }); - }); + }) + }) describe('.formatMessage()', () => { - def('input', () => 'testOption {}'); - def('argument', () => 'test'); - def('output', () => 'testOption test'); - def('subject', () => $subject.formatMessage($input, $argument)); + def('input', () => 'testOption {}') + def('argument', () => 'test') + def('output', () => 'testOption test') + def('subject', () => $subject.formatMessage($input, $argument)) context('when input and argument passed', () => { it('returns output with argument', () => { - expect($subject).to.be.equal($output); + expect($subject).to.be.equal($output) }) - }); - }); + }) + }) describe('.stringifyCliJsonSchema()', () => { def('json', () => ({ id: 15, - name: 'testName' - })); - def('output', () => '\\{\n "id": 15,\n "name": "testName"\n\\}'); - def('subject', () => $subject.stringifyCliJsonSchema($json)); + name: 'testName', + })) + def('output', () => '\\{\n "id": 15,\n "name": "testName"\n\\}') + def('subject', () => $subject.stringifyCliJsonSchema($json)) context('when json passed', () => { it('returns json as formatted string', () => { - expect($subject).to.be.equal($output); + expect($subject).to.be.equal($output) }) - }); - - }); + }) + }) describe('.trimCertificate()', () => { def('certificate', () => '-----BEGIN CERTIFICATE-----\n' + 'testttt' + - '-----END CERTIFICATE-----'); - def('output', () => 'testttt'); - def('subject', () => $subject.trimCertificate($certificate)); + '-----END CERTIFICATE-----') + def('output', () => 'testttt') + def('subject', () => $subject.trimCertificate($certificate)) context('when called with certificate', () => { it('returns trimmed certificate', () => { - expect($subject).to.be.equal($output); + expect($subject).to.be.equal($output) }) - }); - }); -}); + }) + }) +}) diff --git a/test/src/services/access-token-service.test.js b/test/src/services/access-token-service.test.js index ba058e0af..e24b01620 100644 --- a/test/src/services/access-token-service.test.js +++ b/test/src/services/access-token-service.test.js @@ -1,77 +1,77 @@ -const { expect } = require('chai'); -const sinon = require('sinon'); +const {expect} = require('chai') +const sinon = require('sinon') -const AccessTokenManager = require('../../../src/sequelize/managers/access-token-manager'); -const AccessTokenService = require('../../../src/services/access-token-service'); +const AccessTokenManager = require('../../../src/sequelize/managers/access-token-manager') +const AccessTokenService = require('../../../src/services/access-token-service') describe('AccessToken Service', () => { - def('subject', () => AccessTokenService); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => AccessTokenService) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.createAccessToken()', () => { - const accessToken = "accessToken"; - const transaction = {}; - const error = 'Error!'; + const accessToken = 'accessToken' + const transaction = {} + const error = 'Error!' - def('accessTokenObj', () => 'accessTokenResponse'); + def('accessTokenObj', () => 'accessTokenResponse') - def('subject', () => $subject.createAccessToken(accessToken, transaction)); - def('accessTokenResponse', () => Promise.resolve($accessTokenObj)); + def('subject', () => $subject.createAccessToken(accessToken, transaction)) + def('accessTokenResponse', () => Promise.resolve($accessTokenObj)) beforeEach(() => { - $sandbox.stub(AccessTokenManager, 'create').returns($accessTokenResponse); - }); + $sandbox.stub(AccessTokenManager, 'create').returns($accessTokenResponse) + }) it('calls AccessTokenManager#create() with correct args', async () => { - await $subject; - expect(AccessTokenManager.create).to.have.been.calledWith(accessToken, transaction); - }); + await $subject + expect(AccessTokenManager.create).to.have.been.calledWith(accessToken, transaction) + }) context('when AccessTokenManager#create() fails', () => { - def('accessTokenResponse', () => Promise.reject(error)); + def('accessTokenResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AccessTokenManager#create() succeeds', () => { it('fulfills the promise', () => { return expect($subject).to.eventually.equal($accessTokenObj) }) }) - }); + }) describe('.removeAccessTokenByUserId()', () => { - const userId = 15; - const transaction = {}; - const error = 'Error!'; + const userId = 15 + const transaction = {} + const error = 'Error!' - def('removeTokenObj', () => 'removeToken'); + def('removeTokenObj', () => 'removeToken') - def('subject', () => $subject.removeAccessTokenByUserId(userId, transaction)); - def('removeTokenResponse', () => Promise.resolve($removeTokenObj)); + def('subject', () => $subject.removeAccessTokenByUserId(userId, transaction)) + def('removeTokenResponse', () => Promise.resolve($removeTokenObj)) beforeEach(() => { - $sandbox.stub(AccessTokenManager, 'delete').returns($removeTokenResponse); - }); + $sandbox.stub(AccessTokenManager, 'delete').returns($removeTokenResponse) + }) it('calls AccessTokenManager#delete() with correct args', async () => { - await $subject; + await $subject expect(AccessTokenManager.delete).to.have.been.calledWith({ - userId: userId - }, transaction); - }); + userId: userId, + }, transaction) + }) context('when AccessTokenManager#delete() fails', () => { - def('removeTokenResponse', () => Promise.reject(error)); + def('removeTokenResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AccessTokenManager#delete() succeeds', () => { it('fulfills the promise', () => { @@ -79,5 +79,4 @@ describe('AccessToken Service', () => { }) }) }) - -}); \ No newline at end of file +}) diff --git a/test/src/services/agent-service.test.js b/test/src/services/agent-service.test.js index 7708288ca..4a47cbb86 100644 --- a/test/src/services/agent-service.test.js +++ b/test/src/services/agent-service.test.js @@ -1,226 +1,224 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); - -const AgentService = require('../../../src/services/agent-service'); -const Validator = require('../../../src/schemas'); -const FogProvisionKeyManager = require('../../../src/sequelize/managers/iofog-provision-key-manager'); -const MicroserviceManager = require('../../../src/sequelize/managers/microservice-manager'); -const ioFogManager = require('../../../src/sequelize/managers/iofog-manager'); -const FogAccessTokenService = require('../../../src/services/iofog-access-token-service'); -const AppHelper = require('../../../src/helpers/app-helper'); -const ChangeTrackingService = require('../../../src/services/change-tracking-service'); -const MicroserviceStatusManager = require('../../../src/sequelize/managers/microservice-status-manager'); -const MicroserviceService = require('../../../src/services/microservices-service'); -const RegistryManager = require('../../../src/sequelize/managers/registry-manager'); -const TunnelManager = require('../../../src/sequelize/managers/tunnel-manager'); -const StraceManager = require('../../../src/sequelize/managers/strace-manager'); -const ioFogVersionCommandManager = require('../../../src/sequelize/managers/iofog-version-command-manager'); -const ioFogProvisionKeyManager = require('../../../src/sequelize/managers/iofog-provision-key-manager'); -const HWInfoManager = require('../../../src/sequelize/managers/hw-info-manager'); -const USBInfoManager = require('../../../src/sequelize/managers/usb-info-manager'); -const Sequelize = require('sequelize'); -const Op = Sequelize.Op; -const path = require('path'); -const formidable = ('./incoming_form'); -const IncomingForm = formidable.IncomingForm; -const MicroserviceStates = require('../../../src/enums/microservice-state'); -const FogStates = require('../../../src/enums/fog-state'); -const TrackingEventManager = require('../../../src/sequelize/managers/tracking-event-manager'); - -global.appRoot = path.resolve(__dirname); +const {expect} = require('chai') +const sinon = require('sinon') + +const AgentService = require('../../../src/services/agent-service') +const Validator = require('../../../src/schemas') +const FogProvisionKeyManager = require('../../../src/sequelize/managers/iofog-provision-key-manager') +const MicroserviceManager = require('../../../src/sequelize/managers/microservice-manager') +const ioFogManager = require('../../../src/sequelize/managers/iofog-manager') +const FogAccessTokenService = require('../../../src/services/iofog-access-token-service') +const AppHelper = require('../../../src/helpers/app-helper') +const ChangeTrackingService = require('../../../src/services/change-tracking-service') +const MicroserviceStatusManager = require('../../../src/sequelize/managers/microservice-status-manager') +const MicroserviceService = require('../../../src/services/microservices-service') +const RegistryManager = require('../../../src/sequelize/managers/registry-manager') +const TunnelManager = require('../../../src/sequelize/managers/tunnel-manager') +const StraceManager = require('../../../src/sequelize/managers/strace-manager') +const ioFogVersionCommandManager = require('../../../src/sequelize/managers/iofog-version-command-manager') +const ioFogProvisionKeyManager = require('../../../src/sequelize/managers/iofog-provision-key-manager') +const HWInfoManager = require('../../../src/sequelize/managers/hw-info-manager') +const USBInfoManager = require('../../../src/sequelize/managers/usb-info-manager') +const Sequelize = require('sequelize') +const Op = Sequelize.Op +const path = require('path') +const MicroserviceStates = require('../../../src/enums/microservice-state') +const FogStates = require('../../../src/enums/fog-state') +const TrackingEventManager = require('../../../src/sequelize/managers/tracking-event-manager') + +global.appRoot = path.resolve(__dirname) describe('Agent Service', () => { - def('subject', () => AgentService); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => AgentService) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.agentProvision()', () => { const provisionData = { type: 1, - key: 'dpodkqwdpj' - }; + key: 'dpodkqwdpj', + } - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('uuid', () => 'testUuid'); - def('token', () => 'testToken'); + def('uuid', () => 'testUuid') + def('token', () => 'testToken') - def('provisionResponse', () => 'provisionResponse'); + def('provisionResponse', () => 'provisionResponse') - def('subject', () => $subject.agentProvision(provisionData, transaction)); - def('accessTokenResponse', () => Promise.resolve($accessTokenObj)); + def('subject', () => $subject.agentProvision(provisionData, transaction)) + def('accessTokenResponse', () => Promise.resolve($accessTokenObj)) - def('validatorResponse', () => Promise.resolve(true)); + def('validatorResponse', () => Promise.resolve(true)) def('fogProvisionKeyManagerResponse', () => Promise.resolve({ - uuid: $uuid - })); - def('microserviceManagerResponse', () => Promise.resolve()); + uuid: $uuid, + })) + def('microserviceManagerResponse', () => Promise.resolve()) def('iofogManagerResponse', () => Promise.resolve({ - uuid: $uuid - })); + uuid: $uuid, + })) def('fogAccessTokenServiceGenerateResponse', () => Promise.resolve({ - token: $token - })); - def('fogAccessTokenServiceUpdateResponse', () => Promise.resolve()); - def('iofogManagerUpdateResponse', () => Promise.resolve()); - def('fogProvisionKeyManagerDeleteResponse', () => Promise.resolve()); + token: $token, + })) + def('fogAccessTokenServiceUpdateResponse', () => Promise.resolve()) + def('iofogManagerUpdateResponse', () => Promise.resolve()) + def('fogProvisionKeyManagerDeleteResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(FogProvisionKeyManager, 'findOne').returns($fogProvisionKeyManagerResponse); - $sandbox.stub(MicroserviceManager, 'findAllWithDependencies').returns($microserviceManagerResponse); - $sandbox.stub(ioFogManager, 'findOne').returns($iofogManagerResponse); - $sandbox.stub(FogAccessTokenService, 'generateAccessToken').returns($fogAccessTokenServiceGenerateResponse); - $sandbox.stub(FogAccessTokenService, 'updateAccessToken').returns($fogAccessTokenServiceUpdateResponse); - $sandbox.stub(ioFogManager, 'update').returns($iofogManagerUpdateResponse); - $sandbox.stub(FogProvisionKeyManager, 'delete').returns($fogProvisionKeyManagerDeleteResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(FogProvisionKeyManager, 'findOne').returns($fogProvisionKeyManagerResponse) + $sandbox.stub(MicroserviceManager, 'findAllWithDependencies').returns($microserviceManagerResponse) + $sandbox.stub(ioFogManager, 'findOne').returns($iofogManagerResponse) + $sandbox.stub(FogAccessTokenService, 'generateAccessToken').returns($fogAccessTokenServiceGenerateResponse) + $sandbox.stub(FogAccessTokenService, 'updateAccessToken').returns($fogAccessTokenServiceUpdateResponse) + $sandbox.stub(ioFogManager, 'update').returns($iofogManagerUpdateResponse) + $sandbox.stub(FogProvisionKeyManager, 'delete').returns($fogProvisionKeyManagerDeleteResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(provisionData, Validator.schemas.agentProvision); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(provisionData, Validator.schemas.agentProvision) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls FogProvisionKeyManager.findOne with correct args', async () => { - await $subject; + await $subject expect(FogProvisionKeyManager.findOne).to.have.been.calledWith({ - provisionKey: provisionData.key - }, transaction); - }); + provisionKey: provisionData.key, + }, transaction) + }) context('when FogProvisionKeyManager#findOne fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('fogProvisionKeyManagerResponse', () => Promise.reject(error)); + def('fogProvisionKeyManagerResponse', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findOne succeeds', () => { it('calls ioFogManager.findOne with correct args', async () => { - await $subject; + await $subject expect(ioFogManager.findOne).to.have.been.calledWith({ - uuid: $fogProvisionKeyManagerResponse.uuid - }, transaction); - }); + uuid: $fogProvisionKeyManagerResponse.uuid, + }, transaction) + }) context('when ioFogManager#findOne fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('iofogManagerResponse', () => Promise.reject(error)); + def('iofogManagerResponse', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findOne succeeds', () => { it('calls MicroserviceManager.findAllWithDependencies with correct args', async () => { - await $subject; + await $subject expect(MicroserviceManager.findAllWithDependencies).to.have.been.calledWith({ - iofogUuid: $uuid - }, {}, transaction); - }); + iofogUuid: $uuid, + }, {}, transaction) + }) context('when MicroserviceManager#findAllWithDependencies fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('microserviceManagerResponse', () => Promise.reject(error)); + def('microserviceManagerResponse', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#findAllWithDependencies succeeds', () => { it('calls FogAccessTokenService.generateAccessToken with correct args', async () => { - await $subject; - expect(FogAccessTokenService.generateAccessToken).to.have.been.calledWith(transaction); - }); + await $subject + expect(FogAccessTokenService.generateAccessToken).to.have.been.calledWith(transaction) + }) context('when FogAccessTokenService#generateAccessToken fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('fogAccessTokenServiceGenerateResponse', () => Promise.reject(error)); + def('fogAccessTokenServiceGenerateResponse', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FogAccessTokenService#generateAccessToken succeeds', () => { it('calls FogAccessTokenService.updateAccessToken with correct args', async () => { - await $subject; + await $subject expect(FogAccessTokenService.updateAccessToken).to.have.been.calledWith($uuid, { - token: $token - }, transaction); - }); + token: $token, + }, transaction) + }) context('when FogAccessTokenService#updateAccessToken fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('fogAccessTokenServiceUpdateResponse', () => Promise.reject(error)); + def('fogAccessTokenServiceUpdateResponse', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FogAccessTokenService#updateAccessToken succeeds', () => { it('calls ioFogManager.update with correct args', async () => { - await $subject; + await $subject expect(ioFogManager.update).to.have.been.calledWith({ - uuid: $uuid + uuid: $uuid, }, { - fogTypeId: provisionData.type - }, transaction); - }); + fogTypeId: provisionData.type, + }, transaction) + }) context('when ioFogManager#update fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('iofogManagerUpdateResponse', () => Promise.reject(error)); + def('iofogManagerUpdateResponse', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#update succeeds', () => { it('calls FogProvisionKeyManager.delete with correct args', async () => { - await $subject; + await $subject expect(FogProvisionKeyManager.delete).to.have.been.calledWith({ - provisionKey: provisionData.key - }, transaction); - }); + provisionKey: provisionData.key, + }, transaction) + }) context('when FogProvisionKeyManager#delete fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('fogProvisionKeyManagerDeleteResponse', () => Promise.reject(error)); + def('fogProvisionKeyManagerDeleteResponse', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FogProvisionKeyManager#delete succeeds', () => { it(`succeeds`, () => { return expect($subject).to.eventually.have.property('uuid') && - expect($subject).to.eventually.have.property('token'); + expect($subject).to.eventually.have.property('token') }) }) }) @@ -229,106 +227,102 @@ describe('Agent Service', () => { }) }) }) - }); - }); + }) + }) describe('.agentDeprovision()', () => { + const deprovisionData = {microserviceUuids: ['uuid']} + const fogManagerUpdateData = {daemonStatus: FogStates.UNKNOWN, ipAddress: '0.0.0.0'} - const deprovisionData = {microserviceUuids:["uuid"]}; - const fogManagerUpdateData = {daemonStatus: FogStates.UNKNOWN, ipAddress: '0.0.0.0'}; - - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' def('fog', () => ({ - uuid: $uuid - })); + uuid: $uuid, + })) - def('updateAgentResponse', () => 'updateAgentResponse'); + def('updateAgentResponse', () => 'updateAgentResponse') - def('subject', () => $subject.agentDeprovision(deprovisionData, $fog, transaction)); + def('subject', () => $subject.agentDeprovision(deprovisionData, $fog, transaction)) - def('validatorResponse', () => Promise.resolve(true)); - def('microserviceStatusUpdateResponse', () => Promise.resolve()); - def('iofogManagerUpdateResponse', () => Promise.resolve()); + def('validatorResponse', () => Promise.resolve(true)) + def('microserviceStatusUpdateResponse', () => Promise.resolve()) + def('iofogManagerUpdateResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(MicroserviceStatusManager, 'update').returns($microserviceStatusUpdateResponse); - $sandbox.stub(ioFogManager, 'update').returns($iofogManagerUpdateResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(MicroserviceStatusManager, 'update').returns($microserviceStatusUpdateResponse) + $sandbox.stub(ioFogManager, 'update').returns($iofogManagerUpdateResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(deprovisionData, Validator.schemas.agentDeprovision); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(deprovisionData, Validator.schemas.agentDeprovision) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls MicroserviceStatusManager.update with correct args', async () => { - await $subject; + await $subject expect(MicroserviceStatusManager.update).to.have.been.calledWith( - {microserviceUuid: deprovisionData.microserviceUuids}, - {status: MicroserviceStates.NOT_RUNNING}, - transaction - ); - }); + {microserviceUuid: deprovisionData.microserviceUuids}, + {status: MicroserviceStates.NOT_RUNNING}, + transaction + ) + }) context('when MicroserviceStatusManager#update fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('microserviceStatusUpdateResponse', () => Promise.reject(error)); + def('microserviceStatusUpdateResponse', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith = (error) }) - }); + }) context('when MicroserviceStatusManager#update succeeds', () => { it('calls ioFogManager.update with correct args', async () => { - await $subject; + await $subject expect(ioFogManager.update).to.have.been.calledWith({ - uuid: $uuid - }, fogManagerUpdateData, transaction); - }); + uuid: $uuid, + }, fogManagerUpdateData, transaction) + }) context('when ioFogManager#update fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('iofogManagerUpdateResponse', () => Promise.reject(error)); + def('iofogManagerUpdateResponse', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#update succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) - }) - }); - }); - - + }) + }) describe('.updateAgentConfig()', () => { const agentConfig = { - networkInterface: "testNetworkInterface", - dockerUrl: "testDockerUrl", + networkInterface: 'testNetworkInterface', + dockerUrl: 'testDockerUrl', diskLimit: 5, - diskDirectory: "testDiskDirectory", + diskDirectory: 'testDiskDirectory', memoryLimit: 15, cpuLimit: 25, logLimit: 35, @@ -340,90 +334,89 @@ describe('Agent Service', () => { watchdogEnabled: false, latitude: 35, longitude: 36, - gpsMode: 'testGpsMode' - }; + gpsMode: 'testGpsMode', + } - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('uuid', () => 'testUuid'); + def('uuid', () => 'testUuid') def('fog', () => ({ - uuid: $uuid - })); + uuid: $uuid, + })) - def('token', () => 'testToken'); + def('token', () => 'testToken') - def('updateAgentResponse', () => 'updateAgentResponse'); + def('updateAgentResponse', () => 'updateAgentResponse') - def('subject', () => $subject.updateAgentConfig(agentConfig, $fog, transaction)); + def('subject', () => $subject.updateAgentConfig(agentConfig, $fog, transaction)) - def('validatorResponse', () => Promise.resolve(true)); - def('deleteUndefinedFieldsResponse', () => agentConfig); - def('iofogManagerUpdateResponse', () => Promise.resolve()); + def('validatorResponse', () => Promise.resolve(true)) + def('deleteUndefinedFieldsResponse', () => agentConfig) + def('iofogManagerUpdateResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse); - $sandbox.stub(ioFogManager, 'update').returns($iofogManagerUpdateResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse) + $sandbox.stub(ioFogManager, 'update').returns($iofogManagerUpdateResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(agentConfig, Validator.schemas.updateAgentConfig); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(agentConfig, Validator.schemas.updateAgentConfig) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls AppHelper.deleteUndefinedFields with correct args', async () => { - await $subject; - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(agentConfig); - }); + await $subject + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(agentConfig) + }) context('when AppHelper#deleteUndefinedFields fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('deleteUndefinedFieldsResponse', () => error); + def('deleteUndefinedFieldsResponse', () => error) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith = (error) }) - }); + }) context('when AppHelper#deleteUndefinedFields succeeds', () => { it('calls ioFogManager.update with correct args', async () => { - await $subject; + await $subject expect(ioFogManager.update).to.have.been.calledWith({ - uuid: $uuid - }, agentConfig, transaction); - }); + uuid: $uuid, + }, agentConfig, transaction) + }) context('when ioFogManager#update fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('iofogManagerUpdateResponse', () => Promise.reject(error)); + def('iofogManagerUpdateResponse', () => Promise.reject(error)) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#update succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) - }) - }); - }); + }) + }) describe('.getAgentConfigChanges()', () => { const configChanges = { @@ -437,82 +430,82 @@ describe('Agent Service', () => { registries: undefined, tunnel: undefined, diagnostics: undefined, - isImageSnapshot: undefined - }; + isImageSnapshot: undefined, + } - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('uuid', () => 'testUuid'); + def('uuid', () => 'testUuid') def('fog', () => ({ - uuid: $uuid - })); + uuid: $uuid, + })) - def('token', () => 'testToken'); + def('token', () => 'testToken') - def('subject', () => $subject.getAgentConfigChanges($fog, transaction)); + def('subject', () => $subject.getAgentConfigChanges($fog, transaction)) - def('getByFogIdResponse', () => 'getByFogIdResponse'); - def('updateIfChangedResponse', () => Promise.resolve()); + def('getByFogIdResponse', () => 'getByFogIdResponse') + def('updateIfChangedResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(ChangeTrackingService, 'getByIoFogUuid').returns($getByFogIdResponse); - $sandbox.stub(ChangeTrackingService, 'updateIfChanged').returns($updateIfChangedResponse); - }); + $sandbox.stub(ChangeTrackingService, 'getByIoFogUuid').returns($getByFogIdResponse) + $sandbox.stub(ChangeTrackingService, 'updateIfChanged').returns($updateIfChangedResponse) + }) it('calls ChangeTrackingService#getByIoFogUuid() with correct args', async () => { - await $subject; - expect(ChangeTrackingService.getByIoFogUuid).to.have.been.calledWith($uuid, transaction); - }); + await $subject + expect(ChangeTrackingService.getByIoFogUuid).to.have.been.calledWith($uuid, transaction) + }) context('when ChangeTrackingService#getByIoFogUuid() fails', () => { - def('getByFogIdResponse', () => Promise.reject(error)); + def('getByFogIdResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#getByIoFogUuid() succeeds', () => { it('calls ChangeTrackingService.updateIfChanged with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.updateIfChanged).to.have.been.calledWith($uuid, - ChangeTrackingService.events.clean, transaction); - }); + ChangeTrackingService.events.clean, transaction) + }) context('when ChangeTrackingService#updateIfChanged fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('deleteUndefinedFieldsResponse', () => error); + def('deleteUndefinedFieldsResponse', () => error) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith = (error) }) - }); + }) context('when ChangeTrackingService#updateIfChanged succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.deep.equal(configChanges); + return expect($subject).to.eventually.deep.equal(configChanges) }) }) - }); - }); + }) + }) describe('.updateAgentStatus()', () => { - const microservicesStatus = "[{\"containerId\":\"testContainerId\", \"status\":\"RUNNING\"" + - ",\"startTime\":5325543453454,\"operatingDuration\":534535435435,\"cpuUsage\":35,\"memoryUsage\":45}]"; + const microservicesStatus = '[{"containerId":"testContainerId", "status":"RUNNING"' + + ',"startTime":5325543453454,"operatingDuration":534535435435,"cpuUsage":35,"memoryUsage":45}]' const microserviceStatus = { - "containerId": "testContainerId", - "status": "RUNNING", - "startTime": 5325543453454, - "operatingDuration": 534535435435, - "cpuUsage": 35, - "memoryUsage": 45 - }; + 'containerId': 'testContainerId', + 'status': 'RUNNING', + 'startTime': 5325543453454, + 'operatingDuration': 534535435435, + 'cpuUsage': 35, + 'memoryUsage': 45, + } - const microserviceStatusArray = [microserviceStatus]; + const microserviceStatusArray = [microserviceStatus] const fogStatus = { daemonStatus: 'RUNNING', @@ -537,8 +530,8 @@ describe('Agent Service', () => { version: '1.0.0', isReadyToUpgrade: false, isReadyToRollback: false, - microserviceStatus: microservicesStatus - }; + microserviceStatus: microservicesStatus, + } const agentStatus = { daemonStatus: 'RUNNING', @@ -562,157 +555,157 @@ describe('Agent Service', () => { tunnelStatus: 'testTunnelStatus', version: '1.0.0', isReadyToUpgrade: false, - isReadyToRollback: false - }; + isReadyToRollback: false, + } - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('uuid', () => 'testUuid'); + def('uuid', () => 'testUuid') def('fog', () => ({ - uuid: $uuid - })); + uuid: $uuid, + })) - def('token', () => 'testToken'); + def('token', () => 'testToken') - def('subject', () => $subject.updateAgentStatus(fogStatus, $fog, transaction)); + def('subject', () => $subject.updateAgentStatus(fogStatus, $fog, transaction)) - def('validatorResponse', () => Promise.resolve(true)); - def('deleteUndefinedFieldsResponse', () => agentStatus); - def('deleteUndefinedFieldsResponse2', () => microserviceStatus); - def('updateResponse', () => Promise.resolve()); - def('jsonParseResponse', () => microserviceStatusArray); - def('updateMicroserviceStatusesResponse', () => Promise.resolve()); - def('deleteNotRunningResponse', () => Promise.resolve()); + def('validatorResponse', () => Promise.resolve(true)) + def('deleteUndefinedFieldsResponse', () => agentStatus) + def('deleteUndefinedFieldsResponse2', () => microserviceStatus) + def('updateResponse', () => Promise.resolve()) + def('jsonParseResponse', () => microserviceStatusArray) + def('updateMicroserviceStatusesResponse', () => Promise.resolve()) + def('deleteNotRunningResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) $sandbox.stub(AppHelper, 'deleteUndefinedFields') - .onFirstCall().returns($deleteUndefinedFieldsResponse) - .onSecondCall().returns($deleteUndefinedFieldsResponse2); - $sandbox.stub(ioFogManager, 'update').returns($updateResponse); - $sandbox.stub(JSON, 'parse').returns($jsonParseResponse); - $sandbox.stub(MicroserviceStatusManager, 'update').returns($updateMicroserviceStatusesResponse); - $sandbox.stub(MicroserviceService, 'deleteNotRunningMicroservices').returns($deleteNotRunningResponse); - }); + .onFirstCall().returns($deleteUndefinedFieldsResponse) + .onSecondCall().returns($deleteUndefinedFieldsResponse2) + $sandbox.stub(ioFogManager, 'update').returns($updateResponse) + $sandbox.stub(JSON, 'parse').returns($jsonParseResponse) + $sandbox.stub(MicroserviceStatusManager, 'update').returns($updateMicroserviceStatusesResponse) + $sandbox.stub(MicroserviceService, 'deleteNotRunningMicroservices').returns($deleteNotRunningResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(fogStatus, Validator.schemas.updateAgentStatus); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(fogStatus, Validator.schemas.updateAgentStatus) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls AppHelper.deleteUndefinedFields with correct args', async () => { - await $subject; - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(agentStatus); - }); + await $subject + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(agentStatus) + }) context('when AppHelper#deleteUndefinedFields fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('$deleteUndefinedFieldsResponse', () => error); + def('$deleteUndefinedFieldsResponse', () => error) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith = (error) }) - }); + }) context('when AppHelper#deleteUndefinedFields succeeds', () => { it('calls ioFogManager.update with correct args', async () => { - await $subject; + await $subject expect(ioFogManager.update).to.have.been.calledWith({ - uuid: $uuid - }, agentStatus, transaction); - }); + uuid: $uuid, + }, agentStatus, transaction) + }) context('when ioFogManager#update fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('updateResponse', () => error); + def('updateResponse', () => error) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith = (error) }) - }); + }) context('when ioFogManager#update succeeds', () => { it('calls JSON.parse with correct args', async () => { - await $subject; - expect(JSON.parse).to.have.been.calledWith(fogStatus.microserviceStatus); - }); + await $subject + expect(JSON.parse).to.have.been.calledWith(fogStatus.microserviceStatus) + }) context('when JSON#parse fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('jsonParseResponse', () => error); + def('jsonParseResponse', () => error) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith = (error) }) - }); + }) context('when JSON#parse succeeds', () => { it('calls AppHelper.deleteUndefinedFields with correct args', async () => { - await $subject; - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(microserviceStatus); - }); + await $subject + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(microserviceStatus) + }) context('when AppHelper#deleteUndefinedFields fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('$deleteUndefinedFieldsResponse2', () => error); + def('$deleteUndefinedFieldsResponse2', () => error) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith = (error) }) - }); + }) context('when AppHelper#deleteUndefinedFields succeeds', () => { it('calls MicroserviceStatusManager.update with correct args', async () => { - await $subject; + await $subject expect(MicroserviceStatusManager.update).to.have.been.calledWith({ - microserviceUuid: microserviceStatus.id - }, microserviceStatus, transaction); - }); + microserviceUuid: microserviceStatus.id, + }, microserviceStatus, transaction) + }) context('when MicroserviceStatusManager#update fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('updateMicroserviceStatusesResponse', () => error); + def('updateMicroserviceStatusesResponse', () => error) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith = (error) }) - }); + }) context('when MicroserviceStatusManager#update succeeds', () => { it('calls MicroserviceService.deleteNotRunningMicroservices with correct args', async () => { - await $subject; - expect(MicroserviceService.deleteNotRunningMicroservices).to.have.been.calledWith($fog, transaction); - }); + await $subject + expect(MicroserviceService.deleteNotRunningMicroservices).to.have.been.calledWith($fog, transaction) + }) context('when MicroserviceService#deleteNotRunningMicroservices fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('deleteNotRunningResponse', () => error); + def('deleteNotRunningResponse', () => error) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith = (error) }) - }); + }) context('when MicroserviceService#deleteNotRunningMicroservices succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) }) @@ -720,15 +713,15 @@ describe('Agent Service', () => { }) }) }) - }); - }); + }) + }) describe('.getAgentMicroservices()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - const routes = []; + const routes = [] const microserviceWithValidImage = { uuid: 'testMicroserviceUuid', @@ -745,15 +738,15 @@ describe('Agent Service', () => { catalogItem: { images: [{ fogTypeId: 1, - containerImage: 'testContainerImage' - } + containerImage: 'testContainerImage', + }, ], registry: { - id: 10 - } + id: 10, + }, }, - routes: routes - }; + routes: routes, + } const microserviceWithInvalidImage = { uuid: 'testMicroserviceUuid', @@ -770,16 +763,15 @@ describe('Agent Service', () => { catalogItem: { images: [{ fogTypeId: 3, - containerImage: 'testContainerImage' - } + containerImage: 'testContainerImage', + }, ], registry: { - id: 10 - } + id: 10, + }, }, - routes: routes - }; - + routes: routes, + } const microserviceResponse = { @@ -796,95 +788,95 @@ describe('Agent Service', () => { delete: false, deleteWithCleanup: false, routes: routes, - registryId: 10 - }] - }; + registryId: 10, + }], + } - def('uuid', () => 'testUuid'); - def('fogTypeId', () => 1); + def('uuid', () => 'testUuid') + def('fogTypeId', () => 1) def('fog', () => ({ uuid: $uuid, - fogTypeId: $fogTypeId - })); + fogTypeId: $fogTypeId, + })) - def('token', () => 'testToken'); + def('token', () => 'testToken') - def('subject', () => $subject.getAgentMicroservices($fog, transaction)); + def('subject', () => $subject.getAgentMicroservices($fog, transaction)) - def('findAllMicroservicesResponse', () => Promise.resolve([microserviceWithValidImage, microserviceWithInvalidImage])); - def('getPhysicalConnectionsResponse', () => Promise.resolve(routes)); - def('updateResponse', () => Promise.resolve(microserviceResponse)); + def('findAllMicroservicesResponse', () => Promise.resolve([microserviceWithValidImage, microserviceWithInvalidImage])) + def('getPhysicalConnectionsResponse', () => Promise.resolve(routes)) + def('updateResponse', () => Promise.resolve(microserviceResponse)) beforeEach(() => { - $sandbox.stub(MicroserviceManager, 'findAllActiveFlowMicroservices').returns($findAllMicroservicesResponse); - $sandbox.stub(MicroserviceService, 'getPhysicalConnections').returns($getPhysicalConnectionsResponse); - $sandbox.stub(MicroserviceManager, 'update').returns($updateResponse); - }); + $sandbox.stub(MicroserviceManager, 'findAllActiveFlowMicroservices').returns($findAllMicroservicesResponse) + $sandbox.stub(MicroserviceService, 'getPhysicalConnections').returns($getPhysicalConnectionsResponse) + $sandbox.stub(MicroserviceManager, 'update').returns($updateResponse) + }) it('calls MicroserviceManager#findAllActiveFlowMicroservices() with correct args', async () => { - await $subject; - expect(MicroserviceManager.findAllActiveFlowMicroservices).to.have.been.calledWith($uuid, transaction); - }); + await $subject + expect(MicroserviceManager.findAllActiveFlowMicroservices).to.have.been.calledWith($uuid, transaction) + }) context('when MicroserviceManager#findAllActiveFlowMicroservices() fails', () => { - def('findAllMicroservicesResponse', () => Promise.reject(error)); + def('findAllMicroservicesResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#findAllActiveFlowMicroservices() succeeds', () => { it('calls MicroserviceService.getPhysicalConnections with correct args', async () => { - await $subject; - expect(MicroserviceService.getPhysicalConnections).to.have.been.calledWith(microserviceWithValidImage, transaction); - }); + await $subject + expect(MicroserviceService.getPhysicalConnections).to.have.been.calledWith(microserviceWithValidImage, transaction) + }) context('when MicroserviceService#getPhysicalConnections fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('getPhysicalConnectionsResponse', () => error); + def('getPhysicalConnectionsResponse', () => error) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith = (error) }) - }); + }) context('when MicroserviceService#getPhysicalConnections succeeds', () => { it('calls MicroserviceManager.update with correct args', async () => { - await $subject; + await $subject expect(MicroserviceManager.update).to.have.been.calledWith({ - uuid: microserviceWithValidImage.uuid + uuid: microserviceWithValidImage.uuid, }, { - rebuild: false - }, transaction); - }); + rebuild: false, + }, transaction) + }) context('when MicroserviceManager#update fails', () => { - const error = 'Error!'; + const error = 'Error!' - def('updateResponse', () => error); + def('updateResponse', () => error) it(`fails with "${error}"`, () => { return expect($subject).to.be.rejectedWith = (error) }) - }); + }) context('when MicroserviceManager#update succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.deep.equal(microserviceResponse); + return expect($subject).to.eventually.deep.equal(microserviceResponse) }) }) }) - }); - }); + }) + }) describe('.getAgentMicroservice()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - const routes = []; + const routes = [] const microservice = { uuid: 'testMicroserviceUuid', @@ -899,631 +891,630 @@ describe('Agent Service', () => { delete: false, deleteWithCleanup: false, routes: routes, - registryId: 10 - }; + registryId: 10, + } const microserviceResponse = { - microservice: microservice - }; + microservice: microservice, + } - def('uuid', () => 'testUuid'); - def('microserviceUuid', () => 'testMicroserviceUuid'); + def('uuid', () => 'testUuid') + def('microserviceUuid', () => 'testMicroserviceUuid') def('fog', () => ({ - uuid: $uuid - })); + uuid: $uuid, + })) - def('token', () => 'testToken'); + def('token', () => 'testToken') - def('subject', () => $subject.getAgentMicroservice($microserviceUuid, $fog, transaction)); + def('subject', () => $subject.getAgentMicroservice($microserviceUuid, $fog, transaction)) - def('findMicroserviceResponse', () => Promise.resolve(microservice)); + def('findMicroserviceResponse', () => Promise.resolve(microservice)) beforeEach(() => { - $sandbox.stub(MicroserviceManager, 'findOneWithDependencies').returns($findMicroserviceResponse); - }); + $sandbox.stub(MicroserviceManager, 'findOneWithDependencies').returns($findMicroserviceResponse) + }) it('calls MicroserviceManager#findOneWithDependencies() with correct args', async () => { - await $subject; + await $subject expect(MicroserviceManager.findOneWithDependencies).to.have.been.calledWith({ uuid: $microserviceUuid, - iofogUuid: $uuid - }, {}, transaction); - }); + iofogUuid: $uuid, + }, {}, transaction) + }) context('when MicroserviceManager#findOneWithDependencies() fails', () => { - def('findMicroserviceResponse', () => Promise.reject(error)); + def('findMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#findOneWithDependencies() succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.deep.equal(microserviceResponse); + return expect($subject).to.eventually.deep.equal(microserviceResponse) }) - }); - }); + }) + }) describe('.getAgentRegistries()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('uuid', () => 'testUuid'); - def('userId', () => 15); + def('uuid', () => 'testUuid') + def('userId', () => 15) def('fog', () => ({ uuid: $uuid, - userId: $userId - })); + userId: $userId, + })) - def('token', () => 'testToken'); + def('token', () => 'testToken') - def('subject', () => $subject.getAgentRegistries($fog, transaction)); + def('subject', () => $subject.getAgentRegistries($fog, transaction)) - def('getAgentRegistriesResponse', () => Promise.resolve()); + def('getAgentRegistriesResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(RegistryManager, 'findAll').returns($getAgentRegistriesResponse); - }); + $sandbox.stub(RegistryManager, 'findAll').returns($getAgentRegistriesResponse) + }) it('calls RegistryManager#findAll() with correct args', async () => { - await $subject; + await $subject expect(RegistryManager.findAll).to.have.been.calledWith({ [Op.or]: [ { - userId: $userId + userId: $userId, }, { - isPublic: true - } - ] - }, transaction); - }); + isPublic: true, + }, + ], + }, transaction) + }) context('when RegistryManager#findAll() fails', () => { - def('getAgentRegistriesResponse', () => Promise.reject(error)); + def('getAgentRegistriesResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when RegistryManager#findAll() succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.have.property('registries'); + return expect($subject).to.eventually.have.property('registries') }) - }); - }); + }) + }) describe('.getAgentTunnel()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('uuid', () => 'testUuid'); + def('uuid', () => 'testUuid') def('fog', () => ({ - uuid: $uuid - })); + uuid: $uuid, + })) - def('token', () => 'testToken'); + def('token', () => 'testToken') - def('subject', () => $subject.getAgentTunnel($fog, transaction)); + def('subject', () => $subject.getAgentTunnel($fog, transaction)) - def('getTunnelResponse', () => Promise.resolve({})); + def('getTunnelResponse', () => Promise.resolve({})) beforeEach(() => { - $sandbox.stub(TunnelManager, 'findOne').returns($getTunnelResponse); - }); + $sandbox.stub(TunnelManager, 'findOne').returns($getTunnelResponse) + }) it('calls TunnelManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(TunnelManager.findOne).to.have.been.calledWith({ - iofogUuid: $uuid - }, transaction); - }); + iofogUuid: $uuid, + }, transaction) + }) context('when TunnelManager#findOne() fails', () => { - def('getTunnelResponse', () => Promise.reject(error)); + def('getTunnelResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when TunnelManager#findOne() succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.have.property('tunnel'); + return expect($subject).to.eventually.have.property('tunnel') }) - }); - }); + }) + }) describe('.getAgentStrace()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('uuid', () => 'testUuid'); + def('uuid', () => 'testUuid') def('fog', () => ({ - uuid: $uuid - })); + uuid: $uuid, + })) - def('microserviceUuid', () => 'testMicroserviceUuid'); - def('straceRun', () => 'testStraceRun'); + def('microserviceUuid', () => 'testMicroserviceUuid') + def('straceRun', () => 'testStraceRun') def('strace', () => ({ microserviceUuid: $microserviceUuid, - straceRun: $straceRun - })); + straceRun: $straceRun, + })) def('getStracesData', () => ({ microservice: [{ - strace: $strace - }] - })); + strace: $strace, + }], + })) def('straceResponse', () => ({ - straceValues: [$strace] - })); + straceValues: [$strace], + })) - def('subject', () => $subject.getAgentStrace($fog, transaction)); + def('subject', () => $subject.getAgentStrace($fog, transaction)) - def('getStracesResponse', () => Promise.resolve($getStracesData)); + def('getStracesResponse', () => Promise.resolve($getStracesData)) beforeEach(() => { - $sandbox.stub(ioFogManager, 'findFogStraces').returns($getStracesResponse); - }); + $sandbox.stub(ioFogManager, 'findFogStraces').returns($getStracesResponse) + }) it('calls ioFogManager#findFogStraces() with correct args', async () => { - await $subject; + await $subject expect(ioFogManager.findFogStraces).to.have.been.calledWith({ - uuid: $uuid - }, transaction); - }); + uuid: $uuid, + }, transaction) + }) context('when ioFogManager#findFogStraces() fails', () => { - def('getStracesResponse', () => Promise.reject(error)); + def('getStracesResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findFogStraces() succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.deep.equal($straceResponse); + return expect($subject).to.eventually.deep.equal($straceResponse) }) - }); - }); + }) + }) describe('.updateAgentStrace()', () => { + const transaction = {} + const error = 'Error!' - const transaction = {}; - const error = 'Error!'; - - def('uuid', () => 'testUuid'); + def('uuid', () => 'testUuid') def('fog', () => ({ - uuid: $uuid - })); + uuid: $uuid, + })) - def('microserviceUuid', () => 'testMicroserviceUuid'); - def('buffer', () => 'testBuffer'); + def('microserviceUuid', () => 'testMicroserviceUuid') + def('buffer', () => 'testBuffer') def('strace', () => ({ microserviceUuid: $microserviceUuid, - buffer: $buffer - })); + buffer: $buffer, + })) def('straceData', () => ({ - straceData: [$strace] - })); + straceData: [$strace], + })) def('straceResponse', () => ({ - straceValues: [$strace] - })); + straceValues: [$strace], + })) - def('subject', () => $subject.updateAgentStrace($straceData, $fog, transaction)); + def('subject', () => $subject.updateAgentStrace($straceData, $fog, transaction)) - def('validatorResponse', () => Promise.resolve(true)); - def('pushBufferResponse', () => Promise.resolve()); + def('validatorResponse', () => Promise.resolve(true)) + def('pushBufferResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(StraceManager, 'pushBufferByMicroserviceUuid').returns($pushBufferResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(StraceManager, 'pushBufferByMicroserviceUuid').returns($pushBufferResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith($straceData, Validator.schemas.updateAgentStrace); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith($straceData, Validator.schemas.updateAgentStrace) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls StraceManager#pushBufferByMicroserviceUuid() with correct args', async () => { - await $subject; + await $subject expect(StraceManager.pushBufferByMicroserviceUuid).to.have.been.calledWith($microserviceUuid, $buffer, - transaction); - }); + transaction) + }) context('when StraceManager#pushBufferByMicroserviceUuid() fails', () => { - def('pushBufferResponse', () => Promise.reject(error)); + def('pushBufferResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when StraceManager#pushBufferByMicroserviceUuid() succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); - }); - }); + }) + }) + }) describe('.getAgentChangeVersionCommand()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('uuid', () => 'testUuid'); + def('uuid', () => 'testUuid') def('fog', () => ({ - uuid: $uuid - })); + uuid: $uuid, + })) - def('versionCommandLine', () => 'testVersionCommand'); + def('versionCommandLine', () => 'testVersionCommand') def('versionCommand', () => ({ - versionCommand: $versionCommandLine - })); + versionCommand: $versionCommandLine, + })) - def('provisionKey', () => 'testKey'); - def('expirationTime', () => 12535352525); + def('provisionKey', () => 'testKey') + def('expirationTime', () => 12535352525) def('provision', () => ({ provisionKey: $provisionKey, - expirationTime: $expirationTime - })); + expirationTime: $expirationTime, + })) def('response', () => ({ versionCommand: $versionCommandLine, provisionKey: $provisionKey, - expirationTime: $expirationTime - })); + expirationTime: $expirationTime, + })) - def('subject', () => $subject.getAgentChangeVersionCommand($fog, transaction)); + def('subject', () => $subject.getAgentChangeVersionCommand($fog, transaction)) - def('findCommandResponse', () => Promise.resolve($versionCommand)); - def('findProvisionResponse', () => Promise.resolve($provision)); + def('findCommandResponse', () => Promise.resolve($versionCommand)) + def('findProvisionResponse', () => Promise.resolve($provision)) beforeEach(() => { - $sandbox.stub(ioFogVersionCommandManager, 'findOne').returns($findCommandResponse); - $sandbox.stub(ioFogProvisionKeyManager, 'findOne').returns($findProvisionResponse); - }); + $sandbox.stub(ioFogVersionCommandManager, 'findOne').returns($findCommandResponse) + $sandbox.stub(ioFogProvisionKeyManager, 'findOne').returns($findProvisionResponse) + }) it('calls ioFogVersionCommandManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(ioFogVersionCommandManager.findOne).to.have.been.calledWith({ - iofogUuid: $uuid - }, transaction); - }); + iofogUuid: $uuid, + }, transaction) + }) context('when ioFogVersionCommandManager#findOne() fails', () => { - def('findCommandResponse', () => Promise.reject(error)); + def('findCommandResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogVersionCommandManager#findOne() succeeds', () => { it('calls ioFogProvisionKeyManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(ioFogProvisionKeyManager.findOne).to.have.been.calledWith({ - iofogUuid: $uuid - }, transaction); + iofogUuid: $uuid, + }, transaction) context('when ioFogProvisionKeyManager#findOne() fails', () => { - def('findProvisionResponse', () => Promise.reject(error)); + def('findProvisionResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.equal(undefined); + return expect($subject).to.be.equal(undefined) }) - }); + }) context('when ioFogProvisionKeyManager#findOne() succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.equal($response); + return expect($subject).to.equal($response) }) - }); - }); - }); - }); + }) + }) + }) + }) describe('.updateHalHardwareInfo()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('uuid', () => 'testUuid'); + def('uuid', () => 'testUuid') def('fog', () => ({ - uuid: $uuid - })); + uuid: $uuid, + })) - def('info', () => 'testInfo'); + def('info', () => 'testInfo') def('hardwareData', () => ({ - info: $info - })); + info: $info, + })) def('response', () => ({ versionCommand: $versionCommandLine, provisionKey: $provisionKey, - expirationTime: $expirationTime - })); + expirationTime: $expirationTime, + })) - def('subject', () => $subject.updateHalHardwareInfo($hardwareData, $fog, transaction)); + def('subject', () => $subject.updateHalHardwareInfo($hardwareData, $fog, transaction)) - def('validatorResponse', () => Promise.resolve(true)); - def('hwResponse', () => Promise.resolve()); + def('validatorResponse', () => Promise.resolve(true)) + def('hwResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(HWInfoManager, 'updateOrCreate').returns($hwResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(HWInfoManager, 'updateOrCreate').returns($hwResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith($hardwareData, Validator.schemas.updateHardwareInfo); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith($hardwareData, Validator.schemas.updateHardwareInfo) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls HWInfoManager#updateOrCreate() with correct args', async () => { - await $subject; + await $subject expect(HWInfoManager.updateOrCreate).to.have.been.calledWith({ - iofogUuid: $uuid - }, $hardwareData, transaction); + iofogUuid: $uuid, + }, $hardwareData, transaction) context('when HWInfoManager#updateOrCreate() fails', () => { - def('hwResponse', () => Promise.reject(error)); + def('hwResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.equal(undefined); + return expect($subject).to.be.equal(undefined) }) - }); + }) context('when HWInfoManager#updateOrCreate() succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.equal(undefined); + return expect($subject).to.equal(undefined) }) - }); - }); - }); - }); + }) + }) + }) + }) describe('.updateHalUsbInfo()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('uuid', () => 'testUuid'); + def('uuid', () => 'testUuid') def('fog', () => ({ - uuid: $uuid - })); + uuid: $uuid, + })) - def('info', () => 'testInfo'); + def('info', () => 'testInfo') def('usbData', () => ({ - info: $info - })); + info: $info, + })) def('response', () => ({ versionCommand: $versionCommandLine, provisionKey: $provisionKey, - expirationTime: $expirationTime - })); + expirationTime: $expirationTime, + })) - def('subject', () => $subject.updateHalUsbInfo($usbData, $fog, transaction)); + def('subject', () => $subject.updateHalUsbInfo($usbData, $fog, transaction)) - def('validatorResponse', () => Promise.resolve(true)); - def('usbResponse', () => Promise.resolve()); + def('validatorResponse', () => Promise.resolve(true)) + def('usbResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(USBInfoManager, 'updateOrCreate').returns($usbResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(USBInfoManager, 'updateOrCreate').returns($usbResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith($usbData, Validator.schemas.updateUsbInfo); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith($usbData, Validator.schemas.updateUsbInfo) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls USBInfoManager#updateOrCreate() with correct args', async () => { - await $subject; + await $subject expect(USBInfoManager.updateOrCreate).to.have.been.calledWith({ - iofogUuid: $uuid - }, $usbData, transaction); + iofogUuid: $uuid, + }, $usbData, transaction) context('when USBInfoManager#updateOrCreate() fails', () => { - def('usbResponse', () => Promise.reject(error)); + def('usbResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.equal(undefined); + return expect($subject).to.be.equal(undefined) }) - }); + }) context('when USBInfoManager#updateOrCreate() succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.equal(undefined); + return expect($subject).to.equal(undefined) }) - }); - }); - }); - }); + }) + }) + }) + }) describe('.deleteNode()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('uuid', () => 'testUuid'); + def('uuid', () => 'testUuid') def('fog', () => ({ - uuid: $uuid - })); + uuid: $uuid, + })) - def('subject', () => $subject.deleteNode($fog, transaction)); + def('subject', () => $subject.deleteNode($fog, transaction)) - def('deleteResponse', () => Promise.resolve($getStracesData)); + def('deleteResponse', () => Promise.resolve($getStracesData)) beforeEach(() => { - $sandbox.stub(ioFogManager, 'delete').returns($deleteResponse); - }); + $sandbox.stub(ioFogManager, 'delete').returns($deleteResponse) + }) it('calls ioFogManager#delete() with correct args', async () => { - await $subject; + await $subject expect(ioFogManager.delete).to.have.been.calledWith({ - uuid: $uuid - }, transaction); - }); + uuid: $uuid, + }, transaction) + }) context('when ioFogManager#delete() fails', () => { - def('deleteResponse', () => Promise.reject(error)); + def('deleteResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#delete() succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); - }); + }) + }) describe('.getImageSnapshot()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('uuid', () => 'testUuid'); + def('uuid', () => 'testUuid') def('fog', () => ({ - uuid: $uuid - })); + uuid: $uuid, + })) - def('microserviceUuid', () => 'testMicroserviceUuid'); + def('microserviceUuid', () => 'testMicroserviceUuid') def('microserviceResponse', () => ({ - uuid: $microserviceUuid - })); + uuid: $microserviceUuid, + })) - def('subject', () => $subject.getImageSnapshot($fog, transaction)); + def('subject', () => $subject.getImageSnapshot($fog, transaction)) - def('findResponse', () => Promise.resolve($microserviceResponse)); + def('findResponse', () => Promise.resolve($microserviceResponse)) beforeEach(() => { - $sandbox.stub(MicroserviceManager, 'findOne').returns($findResponse); - }); + $sandbox.stub(MicroserviceManager, 'findOne').returns($findResponse) + }) it('calls MicroserviceManager#delete() with correct args', async () => { - await $subject; + await $subject expect(MicroserviceManager.findOne).to.have.been.calledWith({ iofogUuid: $uuid, - imageSnapshot: 'get_image' - }, transaction); - }); + imageSnapshot: 'get_image', + }, transaction) + }) context('when MicroserviceManager#delete() fails', () => { - def('findResponse', () => Promise.reject(error)); + def('findResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#delete() succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.eventually.have.property('uuid'); + return expect($subject).to.eventually.have.property('uuid') }) - }); - }); + }) + }) // TODO // describe('.putImageSnapshot()', () => { describe('postTrackingEndPoint()', () => { - const error = 'Error!'; + const error = 'Error!' - def('fog', () => 'fog!'); - def('events', () => []); - def('transaction', () => {}); + def('fog', () => 'fog!') + def('events', () => []) + def('transaction', () => {}) - def('subject', () => $subject.postTracking($events, $fog, $transaction)); + def('subject', () => $subject.postTracking($events, $fog, $transaction)) - def('validatorResponse', () => Promise.resolve(true)); - def('bulkCreateResponse', () => Promise.resolve()); + def('validatorResponse', () => Promise.resolve(true)) + def('bulkCreateResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(TrackingEventManager, 'bulkCreate').returns($bulkCreateResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(TrackingEventManager, 'bulkCreate').returns($bulkCreateResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith($events, Validator.schemas.trackingArray); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith($events, Validator.schemas.trackingArray) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls TrackingEventManager#bulkCreate() with correct args', async () => { - await $subject; - expect(TrackingEventManager.bulkCreate).to.have.been.calledWith($events, $transaction); + await $subject + expect(TrackingEventManager.bulkCreate).to.have.been.calledWith($events, $transaction) context('when TrackingEventManager#bulkCreate() fails', () => { - def('bulkCreateResponse', () => Promise.reject(error)); + def('bulkCreateResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.equal(undefined); + return expect($subject).to.be.equal(undefined) }) - }); + }) context('when TrackingEventManager#bulkCreate() succeeds', () => { it(`succeeds`, () => { - return expect($subject).to.equal(undefined); + return expect($subject).to.equal(undefined) }) - }); - }); - }); - }); -}); \ No newline at end of file + }) + }) + }) + }) +}) diff --git a/test/src/services/catalog-service.test.js b/test/src/services/catalog-service.test.js index ed505e6c4..78b611b68 100644 --- a/test/src/services/catalog-service.test.js +++ b/test/src/services/catalog-service.test.js @@ -1,67 +1,64 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); - -const CatalogItemManager = require('../../../src/sequelize/managers/catalog-item-manager'); -const CatalogService = require('../../../src/services/catalog-service'); -const Validator = require('../../../src/schemas'); -const CatalogItemImageManager = require('../../../src/sequelize/managers/catalog-item-image-manager'); -const CatalogItemInputTypeManager = require('../../../src/sequelize/managers/catalog-item-input-type-manager'); -const CatalogItemOutputTypeManager = require('../../../src/sequelize/managers/catalog-item-output-type-manager'); -const RegistryManager = require('../../../src/sequelize/managers/registry-manager'); -const AppHelper = require('../../../src/helpers/app-helper'); -const Sequelize = require('sequelize'); -const Op = Sequelize.Op; -const MicroserviceManager = require('../../../src/sequelize/managers/microservice-manager'); -const ChangeTrackingService = require('../../../src/services/change-tracking-service'); -const Errors = require('../../../src/helpers/errors'); -const ErrorMessages = require('../../../src/helpers/error-messages'); +const {expect} = require('chai') +const sinon = require('sinon') + +const CatalogItemManager = require('../../../src/sequelize/managers/catalog-item-manager') +const CatalogService = require('../../../src/services/catalog-service') +const Validator = require('../../../src/schemas') +const CatalogItemImageManager = require('../../../src/sequelize/managers/catalog-item-image-manager') +const CatalogItemInputTypeManager = require('../../../src/sequelize/managers/catalog-item-input-type-manager') +const CatalogItemOutputTypeManager = require('../../../src/sequelize/managers/catalog-item-output-type-manager') +const RegistryManager = require('../../../src/sequelize/managers/registry-manager') +const AppHelper = require('../../../src/helpers/app-helper') +const Sequelize = require('sequelize') +const Op = Sequelize.Op +const MicroserviceManager = require('../../../src/sequelize/managers/microservice-manager') describe('Catalog Service', () => { - def('subject', () => CatalogService); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => CatalogService) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.createCatalogItem()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } const data = { - "name": "testName", - "description": "string", - "category": "string", - "images": [ + 'name': 'testName', + 'description': 'string', + 'category': 'string', + 'images': [ { - "containerImage": "x86 docker image name", - "fogTypeId": 1 + 'containerImage': 'x86 docker image name', + 'fogTypeId': 1, }, { - "containerImage": "ARM docker image name", - "fogTypeId": 2 - } + 'containerImage': 'ARM docker image name', + 'fogTypeId': 2, + }, ], - "publisher": "string", - "diskRequired": 0, - "ramRequired": 0, - "picture": "string", - "isPublic": true, - "registryId": 1, - "inputType": { - "infoType": "string", - "infoFormat": "string" + 'publisher': 'string', + 'diskRequired': 0, + 'ramRequired': 0, + 'picture': 'string', + 'isPublic': true, + 'registryId': 1, + 'inputType': { + 'infoType': 'string', + 'infoFormat': 'string', }, - "outputType": { - "infoType": "string", - "infoFormat": "string" + 'outputType': { + 'infoType': 'string', + 'infoFormat': 'string', }, - "configExample": "string" - }; + 'configExample': 'string', + } - let catalogItem = { + const catalogItem = { name: data.name, description: data.description, category: data.category, @@ -72,225 +69,226 @@ describe('Catalog Service', () => { picture: data.picture, isPublic: data.isPublic, registryId: data.registryId, - userId: user.id - }; + userId: user.id, + } const catalogItemImages = [ { fogTypeId: 1, - catalogItemId: catalogItem.id + catalogItemId: catalogItem.id, }, { fogTypeId: 2, - catalogItemId: catalogItem.id - } - ]; + catalogItemId: catalogItem.id, + }, + ] if (data.images) { - for (let image of data.images) { + for (const image of data.images) { switch (image.fogTypeId) { case 1: - catalogItemImages[0].containerImage = image.containerImage; - break; + catalogItemImages[0].containerImage = image.containerImage + break case 2: - catalogItemImages[1].containerImage = image.containerImage; - break; + catalogItemImages[1].containerImage = image.containerImage + break } } } - let catalogItemInputType = { - catalogItemId: catalogItem.id - }; + const catalogItemInputType = { + catalogItemId: catalogItem.id, + } if (data.inputType) { - catalogItemInputType.infoType = data.inputType.infoType; - catalogItemInputType.infoFormat = data.inputType.infoFormat; + catalogItemInputType.infoType = data.inputType.infoType + catalogItemInputType.infoFormat = data.inputType.infoFormat } - let catalogItemOutputType = { - catalogItemId: catalogItem.id - }; + const catalogItemOutputType = { + catalogItemId: catalogItem.id, + } if (data.outputType) { - catalogItemOutputType.infoType = data.outputType.infoType; - catalogItemOutputType.infoFormat = data.outputType.infoFormat; + catalogItemOutputType.infoType = data.outputType.infoType + catalogItemOutputType.infoFormat = data.outputType.infoFormat } - def('subject', () => $subject.createCatalogItem(data, user, transaction)); + def('subject', () => $subject.createCatalogItem(data, user, transaction)) - def('validatorResponse', () => Promise.resolve(true)); - def('catalogItemFindResponse', () => Promise.resolve()); - def('deleteUndefinedFieldsResponse1', () => catalogItem); - def('deleteUndefinedFieldsResponse2', () => catalogItemInputType); - def('deleteUndefinedFieldsResponse3', () => catalogItemOutputType); - def('registryFindResponse', () => Promise.resolve({})); - def('catalogItemCreateResponse', () => Promise.resolve(catalogItem)); - def('catalogItemImageCreateResponse', () => Promise.resolve()); - def('catalogItemInputTypeCreateResponse', () => Promise.resolve()); - def('catalogItemOutputTypeCreateResponse', () => Promise.resolve({})); + def('validatorResponse', () => Promise.resolve(true)) + def('catalogItemFindResponse', () => Promise.resolve()) + def('deleteUndefinedFieldsResponse1', () => catalogItem) + def('deleteUndefinedFieldsResponse2', () => catalogItemInputType) + def('deleteUndefinedFieldsResponse3', () => catalogItemOutputType) + def('registryFindResponse', () => Promise.resolve({})) + def('catalogItemCreateResponse', () => Promise.resolve(catalogItem)) + def('catalogItemImageCreateResponse', () => Promise.resolve()) + def('catalogItemInputTypeCreateResponse', () => Promise.resolve()) + def('catalogItemOutputTypeCreateResponse', () => Promise.resolve({})) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(CatalogItemManager, 'findOne').returns($catalogItemFindResponse); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(CatalogItemManager, 'findOne').returns($catalogItemFindResponse) $sandbox.stub(AppHelper, 'deleteUndefinedFields') - .onFirstCall().returns($deleteUndefinedFieldsResponse1) - .onSecondCall().returns($deleteUndefinedFieldsResponse2) - .onThirdCall().returns($deleteUndefinedFieldsResponse3); - $sandbox.stub(RegistryManager, 'findOne').returns($registryFindResponse); - $sandbox.stub(CatalogItemManager, 'create').returns($catalogItemCreateResponse); - $sandbox.stub(CatalogItemImageManager, 'bulkCreate').returns($catalogItemImageCreateResponse); - $sandbox.stub(CatalogItemInputTypeManager, 'create').returns($catalogItemInputTypeCreateResponse); - $sandbox.stub(CatalogItemOutputTypeManager, 'create').returns($catalogItemOutputTypeCreateResponse); - }); + .onFirstCall().returns($deleteUndefinedFieldsResponse1) + .onSecondCall().returns($deleteUndefinedFieldsResponse2) + .onThirdCall().returns($deleteUndefinedFieldsResponse3) + $sandbox.stub(RegistryManager, 'findOne').returns($registryFindResponse) + $sandbox.stub(CatalogItemManager, 'create').returns($catalogItemCreateResponse) + $sandbox.stub(CatalogItemImageManager, 'bulkCreate').returns($catalogItemImageCreateResponse) + $sandbox.stub(CatalogItemInputTypeManager, 'create').returns($catalogItemInputTypeCreateResponse) + $sandbox.stub(CatalogItemOutputTypeManager, 'create').returns($catalogItemOutputTypeCreateResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(data, Validator.schemas.catalogItemCreate); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(data, Validator.schemas.catalogItemCreate) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls CatalogItemManager#findOne() with correct args', async () => { - await $subject; + await $subject const where = catalogItem.id ? {[Op.or]: [{userId: catalogItem.userId}, {userId: null}], name: data.name, id: {[Op.ne]: catalogItem.id}} - : {[Op.or]: [{userId: catalogItem.userId}, {userId: null}], name: data.name}; - expect(CatalogItemManager.findOne).to.have.been.calledWith(where, transaction); - }); + : {[Op.or]: [{userId: catalogItem.userId}, {userId: null}], name: data.name} + expect(CatalogItemManager.findOne).to.have.been.calledWith(where, transaction) + }) context('when CatalogItemManager#findOne() fails', () => { - def('catalogItemFindResponse', () => Promise.reject(error)); + def('catalogItemFindResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogItemManager#findOne() succeeds', () => { it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(catalogItem); - }); + await $subject + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(catalogItem) + }) context('when AppHelper#deleteUndefinedFields() fails', () => { - def('deleteUndefinedFieldsResponse1', () => error); + def('deleteUndefinedFieldsResponse1', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.have.property('id') }) - }); + }) context('when AppHelper#deleteUndefinedFields() succeeds', () => { it('calls CatalogItemManager#create() with correct args', async () => { - await $subject; - expect(CatalogItemManager.create).to.have.been.calledWith(catalogItem, transaction); - }); + await $subject + expect(CatalogItemManager.create).to.have.been.calledWith(catalogItem, transaction) + }) context('when CatalogItemManager#create() fails', () => { - def('catalogItemCreateResponse', () => Promise.reject(error)); + def('catalogItemCreateResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogItemManager#create() succeeds', () => { it('calls CatalogItemImageManager#bulkCreate() with correct args', async () => { - await $subject; - expect(CatalogItemImageManager.bulkCreate).to.have.been.calledWith(catalogItemImages, transaction); - }); + await $subject + expect(CatalogItemImageManager.bulkCreate).to.have.been.calledWith(catalogItemImages, transaction) + }) context('when CatalogItemImageManager#bulkCreate() fails', () => { - def('catalogItemImageCreateResponse', () => Promise.reject(error)); + def('catalogItemImageCreateResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogItemImageManager#bulkCreate() succeeds', () => { it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(catalogItemInputType); - }); + await $subject + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(catalogItemInputType) + }) context('when AppHelper#deleteUndefinedFields() fails', () => { - def('deleteUndefinedFieldsResponse2', () => error); + def('deleteUndefinedFieldsResponse2', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.have.property('id') }) - }); + }) context('when AppHelper#deleteUndefinedFields() succeeds', () => { - it('calls RegistryManager#findOne() with correct args', async () => { - await $subject; - expect(RegistryManager.findOne).to.have.been.calledWith({ - id: data.registryId - }, transaction) - }); - - context('when RegistryManager#findOne() fails', () => { - def('registryFindResponse', () => Promise.reject(error)); - - it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error) + it('calls RegistryManager#findOne() with correct args', async () => { + await $subject + expect(RegistryManager.findOne).to.have.been.calledWith({ + id: data.registryId, + }, transaction) }) - }); - - context('when RegistryManager#findOne() succeeds', () => { - it('calls CatalogItemInputTypeManager#create() with correct args', async() => { - await $subject; - expect(CatalogItemInputTypeManager.create).to.have.been.calledWith(catalogItemInputType); - }); - context('when CatalogItemInputTypeManager#create() fails', () => { - def('catalogItemInputTypeCreateResponse', () => Promise.reject(error)); + context('when RegistryManager#findOne() fails', () => { + def('registryFindResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) - context('when CatalogItemInputTypeManager#create() succeeds', () => { - it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(catalogItemOutputType); - }); + context('when RegistryManager#findOne() succeeds', () => { + it('calls CatalogItemInputTypeManager#create() with correct args', async () => { + await $subject + expect(CatalogItemInputTypeManager.create).to.have.been.calledWith(catalogItemInputType) + }) - context('when AppHelper#deleteUndefinedFields() fails', () => { - def('deleteUndefinedFieldsResponse3', () => error); + context('when CatalogItemInputTypeManager#create() fails', () => { + def('catalogItemInputTypeCreateResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.have.property('id') + return expect($subject).to.be.rejectedWith(error) }) - }); + }) - context('when AppHelper#deleteUndefinedFields() succeeds', () => { - it('calls CatalogItemOutputTypeManager#create() with correct args', async () => { - await $subject; - expect(CatalogItemOutputTypeManager.create).to.have.been.calledWith(catalogItemOutputType); - }); + context('when CatalogItemInputTypeManager#create() succeeds', () => { + it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { + await $subject + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(catalogItemOutputType) + }) - context('when CatalogItemOutputTypeManager#create() fails', () => { - def('catalogItemOutputTypeCreateResponse', () => Promise.reject(error)); + context('when AppHelper#deleteUndefinedFields() fails', () => { + def('deleteUndefinedFieldsResponse3', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error) + return expect($subject).to.eventually.have.property('id') }) - }); + }) - context('when CatalogItemOutputTypeManager#create() succeeds', () => { - it('succeeds', () => { - return expect($subject).to.eventually.have.property('id') + context('when AppHelper#deleteUndefinedFields() succeeds', () => { + it('calls CatalogItemOutputTypeManager#create() with correct args', async () => { + await $subject + expect(CatalogItemOutputTypeManager.create).to.have.been.calledWith(catalogItemOutputType) + }) + + context('when CatalogItemOutputTypeManager#create() fails', () => { + def('catalogItemOutputTypeCreateResponse', () => Promise.reject(error)) + + it(`fails with ${error}`, () => { + return expect($subject).to.be.rejectedWith(error) + }) + }) + + context('when CatalogItemOutputTypeManager#create() succeeds', () => { + it('succeeds', () => { + return expect($subject).to.eventually.have.property('id') + }) }) }) }) @@ -302,58 +300,57 @@ describe('Catalog Service', () => { }) }) }) - }); describe('.updateCatalogItem()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const id = 25; + const id = 25 const data = { - "name": "string", - "description": "string", - "category": "string", - "images": [ + 'name': 'string', + 'description': 'string', + 'category': 'string', + 'images': [ { - "containerImage": "x86 docker image name", - "fogTypeId": 1 + 'containerImage': 'x86 docker image name', + 'fogTypeId': 1, }, { - "containerImage": "ARM docker image name", - "fogTypeId": 2 - } + 'containerImage': 'ARM docker image name', + 'fogTypeId': 2, + }, ], - "publisher": "string", - "diskRequired": 0, - "ramRequired": 0, - "picture": "string", - "isPublic": true, - "registryId": 1, - "inputType": { - "infoType": "string", - "infoFormat": "string" + 'publisher': 'string', + 'diskRequired': 0, + 'ramRequired': 0, + 'picture': 'string', + 'isPublic': true, + 'registryId': 1, + 'inputType': { + 'infoType': 'string', + 'infoFormat': 'string', }, - "outputType": { - "infoType": "string", - "infoFormat": "string" + 'outputType': { + 'infoType': 'string', + 'infoFormat': 'string', }, - "configExample": "string" - }; + 'configExample': 'string', + } - const isCLI = false; + const isCLI = false const where = isCLI ? {id: id} - : {id: id, userId: user.id}; + : {id: id, userId: user.id} - data.id = id; + data.id = id - let catalogItem = { + const catalogItem = { name: data.name, description: data.description, category: data.category, @@ -363,298 +360,298 @@ describe('Catalog Service', () => { ramRequired: data.ramRequired, picture: data.picture, isPublic: data.isPublic, - registryId: data.registryId - }; + registryId: data.registryId, + } const image1 = { fogTypeId: 1, - catalogItemId: id - }; + catalogItemId: id, + } const image2 = { fogTypeId: 2, - catalogItemId: id - }; + catalogItemId: id, + } const catalogItemImages = [ - image1, image2 - ]; + image1, image2, + ] if (data.images) { - for (let image of data.images) { + for (const image of data.images) { switch (image.fogTypeId) { case 1: - catalogItemImages[0].containerImage = image.containerImage; - break; + catalogItemImages[0].containerImage = image.containerImage + break case 2: - catalogItemImages[1].containerImage = image.containerImage; - break; + catalogItemImages[1].containerImage = image.containerImage + break } } } const updatedImage1 = { fogTypeId: 1, - containerImage: "x86 docker image name", - }; + containerImage: 'x86 docker image name', + } const updatedImage2 = { fogTypeId: 2, - containerImage: "ARM docker image name", - }; + containerImage: 'ARM docker image name', + } - let catalogItemInputType = { - catalogItemId: id - }; + const catalogItemInputType = { + catalogItemId: id, + } if (data.inputType) { - catalogItemInputType.infoType = data.inputType.infoType; - catalogItemInputType.infoFormat = data.inputType.infoFormat; + catalogItemInputType.infoType = data.inputType.infoType + catalogItemInputType.infoFormat = data.inputType.infoFormat } - let catalogItemOutputType = { - catalogItemId: id - }; + const catalogItemOutputType = { + catalogItemId: id, + } if (data.outputType) { - catalogItemOutputType.infoType = data.outputType.infoType; - catalogItemOutputType.infoFormat = data.outputType.infoFormat; + catalogItemOutputType.infoType = data.outputType.infoType + catalogItemOutputType.infoFormat = data.outputType.infoFormat } - def('subject', () => $subject.updateCatalogItem(id, data, user, isCLI, transaction)); + def('subject', () => $subject.updateCatalogItem(id, data, user, isCLI, transaction)) - def('validatorResponse', () => Promise.resolve(true)); - def('deleteUndefinedFieldsResponse1', () => catalogItem); - def('deleteUndefinedFieldsResponse2', () => catalogItemInputType); - def('deleteUndefinedFieldsResponse3', () => catalogItemOutputType); - def('isEmptyResponse', () => false); - def('registryFindResponse', () => Promise.resolve({})); - def('catalogItemFindResponse1', () => Promise.resolve(catalogItem)); - def('catalogItemFindResponse2', () => Promise.resolve()); - def('catalogItemUpdateResponse', () => Promise.resolve()); - def('catalogItemImageUpdateOrCreateResponse', () => Promise.resolve()); - def('catalogItemInputTypeUpdateOrCreateResponse', () => Promise.resolve()); - def('catalogItemOutputTypeUpdateOrCreateResponse', () => Promise.resolve({})); - def('microservicesResponse', () => Promise.resolve([])); + def('validatorResponse', () => Promise.resolve(true)) + def('deleteUndefinedFieldsResponse1', () => catalogItem) + def('deleteUndefinedFieldsResponse2', () => catalogItemInputType) + def('deleteUndefinedFieldsResponse3', () => catalogItemOutputType) + def('isEmptyResponse', () => false) + def('registryFindResponse', () => Promise.resolve({})) + def('catalogItemFindResponse1', () => Promise.resolve(catalogItem)) + def('catalogItemFindResponse2', () => Promise.resolve()) + def('catalogItemUpdateResponse', () => Promise.resolve()) + def('catalogItemImageUpdateOrCreateResponse', () => Promise.resolve()) + def('catalogItemInputTypeUpdateOrCreateResponse', () => Promise.resolve()) + def('catalogItemOutputTypeUpdateOrCreateResponse', () => Promise.resolve({})) + def('microservicesResponse', () => Promise.resolve([])) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) $sandbox.stub(AppHelper, 'deleteUndefinedFields') - .onFirstCall().returns($deleteUndefinedFieldsResponse1) - .onSecondCall().returns($deleteUndefinedFieldsResponse2) - .onThirdCall().returns($deleteUndefinedFieldsResponse3); - $sandbox.stub(AppHelper, 'isEmpty').returns($isEmptyResponse); - $sandbox.stub(RegistryManager, 'findOne').returns($registryFindResponse); + .onFirstCall().returns($deleteUndefinedFieldsResponse1) + .onSecondCall().returns($deleteUndefinedFieldsResponse2) + .onThirdCall().returns($deleteUndefinedFieldsResponse3) + $sandbox.stub(AppHelper, 'isEmpty').returns($isEmptyResponse) + $sandbox.stub(RegistryManager, 'findOne').returns($registryFindResponse) $sandbox.stub(CatalogItemManager, 'findOne') - .onCall(0).returns($catalogItemFindResponse1) - .onCall(1).returns($catalogItemFindResponse2) - .onCall(2).returns($catalogItemFindResponse1) - .onCall(3).returns($catalogItemFindResponse2); - $sandbox.stub(CatalogItemManager, 'update').returns($catalogItemUpdateResponse); - $sandbox.stub(CatalogItemImageManager, 'updateOrCreate').returns($catalogItemImageUpdateOrCreateResponse); // twice - $sandbox.stub(CatalogItemInputTypeManager, 'updateOrCreate').returns($catalogItemInputTypeUpdateOrCreateResponse); - $sandbox.stub(CatalogItemOutputTypeManager, 'updateOrCreate').returns($catalogItemOutputTypeUpdateOrCreateResponse); - //TODO test success fail and arguments - $sandbox.stub(MicroserviceManager, 'findAllWithStatuses').returns($microservicesResponse); - }); + .onCall(0).returns($catalogItemFindResponse1) + .onCall(1).returns($catalogItemFindResponse2) + .onCall(2).returns($catalogItemFindResponse1) + .onCall(3).returns($catalogItemFindResponse2) + $sandbox.stub(CatalogItemManager, 'update').returns($catalogItemUpdateResponse) + $sandbox.stub(CatalogItemImageManager, 'updateOrCreate').returns($catalogItemImageUpdateOrCreateResponse) // twice + $sandbox.stub(CatalogItemInputTypeManager, 'updateOrCreate').returns($catalogItemInputTypeUpdateOrCreateResponse) + $sandbox.stub(CatalogItemOutputTypeManager, 'updateOrCreate').returns($catalogItemOutputTypeUpdateOrCreateResponse) + // TODO test success fail and arguments + $sandbox.stub(MicroserviceManager, 'findAllWithStatuses').returns($microservicesResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(data, Validator.schemas.catalogItemUpdate); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(data, Validator.schemas.catalogItemUpdate) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(catalogItem); - }); + await $subject + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(catalogItem) + }) context('when AppHelper#deleteUndefinedFields() fails', () => { - def('deleteUndefinedFieldsResponse1', () => error); + def('deleteUndefinedFieldsResponse1', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#deleteUndefinedFields() succeeds', () => { it('calls AppHelper#isEmpty() with correct args', async () => { - await $subject; - expect(AppHelper.isEmpty).to.have.been.calledWith(catalogItem); - }); + await $subject + expect(AppHelper.isEmpty).to.have.been.calledWith(catalogItem) + }) context('when AppHelper#isEmpty() fails', () => { - def('isEmptyResponse', () => error); + def('isEmptyResponse', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#isEmpty() succeeds', () => { it('calls RegistryManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(RegistryManager.findOne).to.have.been.calledWith({ - id: data.registryId + id: data.registryId, }, transaction) - }); + }) context('when RegistryManager#findOne() fails', () => { - def('registryFindResponse', () => Promise.reject(error)); + def('registryFindResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when RegistryManager#findOne() succeeds', () => { it('calls CatalogItemManager#findOne() with correct args', async () => { - await $subject; + await $subject const whereFind = catalogItem.id ? { [Op.or]: [{userId: catalogItem.userId}, {userId: null}], name: data.name, - id: {[Op.ne]: catalogItem.id} + id: {[Op.ne]: catalogItem.id}, } - : {[Op.or]: [{userId: catalogItem.userId}, {userId: null}], name: data.name}; - expect(CatalogItemManager.findOne).to.have.been.calledWith(whereFind, transaction); - }); + : {[Op.or]: [{userId: catalogItem.userId}, {userId: null}], name: data.name} + expect(CatalogItemManager.findOne).to.have.been.calledWith(whereFind, transaction) + }) context('when CatalogItemManager#findOne() succeeds', () => { it('calls CatalogItemManager#findOne() with correct args', async () => { - await $subject; + await $subject const whereFind = catalogItem.id ? { [Op.or]: [{userId: catalogItem.userId}, {userId: null}], name: data.name, - id: {[Op.ne]: catalogItem.id} + id: {[Op.ne]: catalogItem.id}, } - : {[Op.or]: [{userId: catalogItem.userId}, {userId: null}], name: data.name}; - expect(CatalogItemManager.findOne).to.have.been.calledWith(whereFind, transaction); - }); + : {[Op.or]: [{userId: catalogItem.userId}, {userId: null}], name: data.name} + expect(CatalogItemManager.findOne).to.have.been.calledWith(whereFind, transaction) + }) context('when CatalogItemManager#findOne() succeeds', () => { it('calls CatalogItemManager#update() with correct args', async () => { - await $subject; - expect(CatalogItemManager.update).to.have.been.calledWith(where, catalogItem, transaction); - }); + await $subject + expect(CatalogItemManager.update).to.have.been.calledWith(where, catalogItem, transaction) + }) context('when CatalogItemManager#update() fails', () => { - def('catalogItemUpdateResponse', () => Promise.reject(error)); + def('catalogItemUpdateResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogItemManager#update() succeeds', () => { it('calls CatalogItemImageManager#updateOrCreate() with correct args', async () => { - await $subject; + await $subject expect(CatalogItemImageManager.updateOrCreate).to.have.been.calledWith({ catalogItemId: data.id, - fogTypeId: image1.fogTypeId + fogTypeId: image1.fogTypeId, }, { catalogItemId: data.id, fogTypeId: image1.fogTypeId, - containerImage: updatedImage1.containerImage - }, transaction); - }); + containerImage: updatedImage1.containerImage, + }, transaction) + }) context('when CatalogItemImageManager#updateOrCreate() fails', () => { - def('catalogItemImageUpdateOrCreateResponse', () => error); + def('catalogItemImageUpdateOrCreateResponse', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when CatalogItemImageManager#updateOrCreate() succeeds', () => { it('calls CatalogItemImageManager#updateOrCreate() with correct args', async () => { - await $subject; + await $subject expect(CatalogItemImageManager.updateOrCreate).to.have.been.calledWith({ catalogItemId: id, - fogTypeId: image2.fogTypeId + fogTypeId: image2.fogTypeId, }, { catalogItemId: id, fogTypeId: image2.fogTypeId, - containerImage: updatedImage2.containerImage - }, transaction); - }); + containerImage: updatedImage2.containerImage, + }, transaction) + }) context('when CatalogItemImageManager#updateOrCreate() fails', () => { - def('catalogItemImageUpdateOrCreateResponse', () => Promise.reject(error)); + def('catalogItemImageUpdateOrCreateResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogItemImageManager#updateOrCreate() succeeds', () => { it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(catalogItemInputType); - }); + await $subject + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(catalogItemInputType) + }) context('when AppHelper#deleteUndefinedFields() fails', () => { - def('deleteUndefinedFieldsResponse2', () => error); + def('deleteUndefinedFieldsResponse2', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#deleteUndefinedFields() succeeds', () => { it('calls CatalogItemInputTypeManager#updateOrCreate() with correct args', async () => { - await $subject; + await $subject expect(CatalogItemInputTypeManager.updateOrCreate).to.have.been.calledWith({ - catalogItemId: data.id - }, catalogItemInputType, transaction); - }); + catalogItemId: data.id, + }, catalogItemInputType, transaction) + }) context('when CatalogItemInputTypeManager#updateOrCreate() fails', () => { - def('catalogItemInputTypeUpdateOrCreateResponse', () => Promise.reject(error)); + def('catalogItemInputTypeUpdateOrCreateResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogItemInputTypeManager#updateOrCreate() succeeds', () => { it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(catalogItemOutputType); - }); + await $subject + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(catalogItemOutputType) + }) context('when AppHelper#deleteUndefinedFields() fails', () => { - def('deleteUndefinedFieldsResponse3', () => error); + def('deleteUndefinedFieldsResponse3', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#deleteUndefinedFields() succeeds', () => { it('calls CatalogItemOutputTypeManager#updateOrCreate() with correct args', async () => { - await $subject; + await $subject expect(CatalogItemOutputTypeManager.updateOrCreate).to.have.been.calledWith({ - catalogItemId: data.id - }, catalogItemOutputType, transaction); - }); + catalogItemId: data.id, + }, catalogItemOutputType, transaction) + }) context('when CatalogItemOutputTypeManager#updateOrCreate() fails', () => { - def('catalogItemOutputTypeUpdateOrCreateResponse', () => Promise.reject(error)); + def('catalogItemOutputTypeUpdateOrCreateResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogItemOutputTypeManager#updateOrCreate() succeeds', () => { it('succeeds', () => { @@ -673,299 +670,293 @@ describe('Catalog Service', () => { }) }) }) - }); + }) describe('.listCatalogItems()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const isCLI = false; + const isCLI = false const where = isCLI ? {[Op.or]: [{category: {[Op.ne]: 'SYSTEM'}}, {category: null}]} : { [Op.or]: [{userId: user.id}, {userId: null}], - [Op.or]: [{category: {[Op.ne]: 'SYSTEM'}}, {category: null}] - }; + [Op.or]: [{category: {[Op.ne]: 'SYSTEM'}}, {category: null}], + } const attributes = isCLI ? {} - : {exclude: ["userId"]}; + : {exclude: ['userId']} - def('subject', () => $subject.listCatalogItems(user, isCLI, transaction)); + def('subject', () => $subject.listCatalogItems(user, isCLI, transaction)) - def('catalogItemsFindResponse', () => Promise.resolve()); + def('catalogItemsFindResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(CatalogItemManager, 'findAllWithDependencies').returns($catalogItemFindResponse); - }); + $sandbox.stub(CatalogItemManager, 'findAllWithDependencies').returns($catalogItemFindResponse) + }) it('calls CatalogItemManager#findAllWithDependencies() with correct args', async () => { - await $subject; - expect(CatalogItemManager.findAllWithDependencies).to.have.been.calledWith(where, attributes, transaction); - }); + await $subject + expect(CatalogItemManager.findAllWithDependencies).to.have.been.calledWith(where, attributes, transaction) + }) context('when CatalogItemManager#findAllWithDependencies() fails', () => { - def('catalogItemsFindResponse', () => Promise.reject(error)); + def('catalogItemsFindResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.eventually.have.property('catalogItems'); + return expect($subject).to.be.eventually.have.property('catalogItems') }) - }); + }) context('when CatalogItemManager#findAllWithDependencies() succeeds', () => { it('succeeds', () => { return expect($subject).to.eventually.have.property('catalogItems') }) }) - - }); + }) describe('.getCatalogItem()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const isCLI = false; + const isCLI = false - const id = 5; + const id = 5 const where = isCLI ? {id: id} : { id: id, [Op.or]: [{userId: user.id}, {userId: null}], - [Op.or]: [{category: {[Op.ne]: 'SYSTEM'}}, {category: null}] - }; + [Op.or]: [{category: {[Op.ne]: 'SYSTEM'}}, {category: null}], + } const attributes = isCLI ? {} - : {exclude: ["userId"]}; + : {exclude: ['userId']} - def('subject', () => $subject.getCatalogItem(id, user, isCLI, transaction)); + def('subject', () => $subject.getCatalogItem(id, user, isCLI, transaction)) - def('catalogItemFindResponse', () => Promise.resolve({})); + def('catalogItemFindResponse', () => Promise.resolve({})) beforeEach(() => { - $sandbox.stub(CatalogItemManager, 'findOneWithDependencies').returns($catalogItemFindResponse); - }); + $sandbox.stub(CatalogItemManager, 'findOneWithDependencies').returns($catalogItemFindResponse) + }) it('calls CatalogItemManager#findOneWithDependencies() with correct args', async () => { - await $subject; - expect(CatalogItemManager.findOneWithDependencies).to.have.been.calledWith(where, attributes, transaction); - }); + await $subject + expect(CatalogItemManager.findOneWithDependencies).to.have.been.calledWith(where, attributes, transaction) + }) context('when CatalogItemManager#findOneWithDependencies() fails', () => { - def('catalogItemFindResponse', () => Promise.reject(error)); + def('catalogItemFindResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogItemManager#findOneWithDependencies() succeeds', () => { it('succeeds', () => { return expect($subject).to.eventually.deep.equal({}) }) }) - - }); + }) describe('.deleteCatalogItem()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const isCLI = false; + const isCLI = false - const id = 5; + const id = 5 const where = isCLI ? {id: id} - : {userId: user.id, id: id}; + : {userId: user.id, id: id} - def('subject', () => $subject.deleteCatalogItem(id, user, isCLI, transaction)); + def('subject', () => $subject.deleteCatalogItem(id, user, isCLI, transaction)) - def('catalogItemFindResponse', () => Promise.resolve({})); - def('response', () => 1); - def('catalogItemDeleteResponse', () => Promise.resolve($response)); + def('catalogItemFindResponse', () => Promise.resolve({})) + def('response', () => 1) + def('catalogItemDeleteResponse', () => Promise.resolve($response)) beforeEach(() => { - $sandbox.stub(CatalogItemManager, 'findOne').returns($catalogItemFindResponse); - $sandbox.stub(CatalogItemManager, 'delete').returns($catalogItemDeleteResponse); - }); + $sandbox.stub(CatalogItemManager, 'findOne').returns($catalogItemFindResponse) + $sandbox.stub(CatalogItemManager, 'delete').returns($catalogItemDeleteResponse) + }) it('calls CatalogItemManager#findOne() with correct args', async () => { - await $subject; + await $subject whereFind = isCLI ? { - id: id + id: id, } : { userId: user.id, - id: id - }; + id: id, + } expect(CatalogItemManager.findOne).to.have.been.calledWith(whereFind, transaction) - }); + }) context('when CatalogItemManager#findOne() fails', () => { - def('catalogItemFindResponse', () => Promise.reject(error)); + def('catalogItemFindResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogItemManager#findOne() succeeds', () => { - it('calls CatalogItemManager#delete() with correct args', async () => { - await $subject; - expect(CatalogItemManager.delete).to.have.been.calledWith(where, transaction); - }); + await $subject + expect(CatalogItemManager.delete).to.have.been.calledWith(where, transaction) + }) context('when CatalogItemManager#delete() fails', () => { - def('catalogItemDeleteResponse', () => Promise.reject(error)); + def('catalogItemDeleteResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogItemManager#delete() succeeds', () => { it('succeeds', () => { return expect($subject).to.eventually.deep.equal($response) }) }) - })}); + }) + }) describe('.getNetworkCatalogItem()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('subject', () => $subject.getNetworkCatalogItem(transaction)); + def('subject', () => $subject.getNetworkCatalogItem(transaction)) - def('response', () => 1); - def('catalogItemFindResponse', () => Promise.resolve($response)); + def('response', () => 1) + def('catalogItemFindResponse', () => Promise.resolve($response)) beforeEach(() => { - $sandbox.stub(CatalogItemManager, 'findOne').returns($catalogItemFindResponse); - }); + $sandbox.stub(CatalogItemManager, 'findOne').returns($catalogItemFindResponse) + }) it('calls CatalogItemManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(CatalogItemManager.findOne).to.have.been.calledWith({ name: 'Networking Tool', category: 'SYSTEM', publisher: 'Eclipse ioFog', registry_id: 1, - user_id: null - }, transaction); - }); + user_id: null, + }, transaction) + }) context('when CatalogItemManager#findOne() fails', () => { - def('catalogItemFindResponse', () => Promise.reject(error)); + def('catalogItemFindResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogItemManager#findOne() succeeds', () => { it('succeeds', () => { return expect($subject).to.eventually.deep.equal($response) }) }) - - }); + }) describe('.getBluetoothCatalogItem()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('subject', () => $subject.getBluetoothCatalogItem(transaction)); + def('subject', () => $subject.getBluetoothCatalogItem(transaction)) - def('response', () => 1); - def('catalogItemFindResponse', () => Promise.resolve($response)); + def('response', () => 1) + def('catalogItemFindResponse', () => Promise.resolve($response)) beforeEach(() => { - $sandbox.stub(CatalogItemManager, 'findOne').returns($catalogItemFindResponse); - }); + $sandbox.stub(CatalogItemManager, 'findOne').returns($catalogItemFindResponse) + }) it('calls CatalogItemManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(CatalogItemManager.findOne).to.have.been.calledWith({ name: 'RESTBlue', category: 'SYSTEM', publisher: 'Eclipse ioFog', registry_id: 1, - user_id: null - }, transaction); - }); + user_id: null, + }, transaction) + }) context('when CatalogItemManager#findOne() fails', () => { - def('catalogItemFindResponse', () => Promise.reject(error)); + def('catalogItemFindResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogItemManager#findOne() succeeds', () => { it('succeeds', () => { return expect($subject).to.eventually.deep.equal($response) }) }) - - }); + }) describe('.getHalCatalogItem()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('subject', () => $subject.getHalCatalogItem(transaction)); + def('subject', () => $subject.getHalCatalogItem(transaction)) - def('response', () => 1); - def('catalogItemFindResponse', () => Promise.resolve($response)); + def('response', () => 1) + def('catalogItemFindResponse', () => Promise.resolve($response)) beforeEach(() => { - $sandbox.stub(CatalogItemManager, 'findOne').returns($catalogItemFindResponse); - }); + $sandbox.stub(CatalogItemManager, 'findOne').returns($catalogItemFindResponse) + }) it('calls CatalogItemManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(CatalogItemManager.findOne).to.have.been.calledWith({ name: 'HAL', category: 'SYSTEM', publisher: 'Eclipse ioFog', registry_id: 1, - user_id: null - }, transaction); - }); + user_id: null, + }, transaction) + }) context('when CatalogItemManager#findOne() fails', () => { - def('catalogItemFindResponse', () => Promise.reject(error)); + def('catalogItemFindResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogItemManager#findOne() succeeds', () => { it('succeeds', () => { return expect($subject).to.eventually.deep.equal($response) }) }) - - }); - -}); \ No newline at end of file + }) +}) diff --git a/test/src/services/change-tracking-service.test.js b/test/src/services/change-tracking-service.test.js index d61cadb0c..7538174d8 100644 --- a/test/src/services/change-tracking-service.test.js +++ b/test/src/services/change-tracking-service.test.js @@ -1,159 +1,158 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); +const {expect} = require('chai') +const sinon = require('sinon') -const ChangeTrackingManager = require('../../../src/sequelize/managers/change-tracking-manager'); -const ChangeTrackingService = require('../../../src/services/change-tracking-service'); +const ChangeTrackingManager = require('../../../src/sequelize/managers/change-tracking-manager') +const ChangeTrackingService = require('../../../src/services/change-tracking-service') describe('ChangeTracking Service', () => { - def('subject', () => ChangeTrackingService); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => ChangeTrackingService) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.create()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - const ioFogUuid = 'testUuid'; + const ioFogUuid = 'testUuid' - def('subject', () => $subject.create(ioFogUuid, transaction)); - def('createResponse', () => Promise.resolve()); + def('subject', () => $subject.create(ioFogUuid, transaction)) + def('createResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(ChangeTrackingManager, 'create').returns($createResponse); - }); + $sandbox.stub(ChangeTrackingManager, 'create').returns($createResponse) + }) it('calls ChangeTrackingManager#create() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingManager.create).to.have.been.calledWith({ - iofogUuid: ioFogUuid - }, transaction); - }); + iofogUuid: ioFogUuid, + }, transaction) + }) context('when ChangeTrackingManager#create() fails', () => { - def('createResponse', () => Promise.reject(error)); + def('createResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingManager#create() succeeds', () => { it('fulfills the promise', () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.update()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - const ioFogUuid = 'testUuid'; + const ioFogUuid = 'testUuid' - def('subject', () => $subject.update(ioFogUuid, data, transaction)); - def('updateResponse', () => Promise.resolve()); + def('subject', () => $subject.update(ioFogUuid, data, transaction)) + def('updateResponse', () => Promise.resolve()) - const data = ChangeTrackingService.events.clean; + const data = ChangeTrackingService.events.clean beforeEach(() => { - $sandbox.stub(ChangeTrackingManager, 'update').returns($updateResponse); - }); + $sandbox.stub(ChangeTrackingManager, 'update').returns($updateResponse) + }) it('calls ChangeTrackingManager#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingManager.update).to.have.been.calledWith({ - iofogUuid: ioFogUuid - }, data, transaction); - }); + iofogUuid: ioFogUuid, + }, data, transaction) + }) context('when ChangeTrackingManager#update() fails', () => { - def('updateResponse', () => Promise.reject(error)); + def('updateResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingManager#update() succeeds', () => { it('fulfills the promise', () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.updateIfChanged()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - const ioFogUuid = 'testUuid'; + const ioFogUuid = 'testUuid' - const data = ChangeTrackingService.events.clean; + const data = ChangeTrackingService.events.clean - def('subject', () => $subject.updateIfChanged(ioFogUuid, data, transaction)); - def('updateResponse', () => Promise.resolve()); + def('subject', () => $subject.updateIfChanged(ioFogUuid, data, transaction)) + def('updateResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(ChangeTrackingManager, 'updateIfChanged').returns($updateResponse); - }); + $sandbox.stub(ChangeTrackingManager, 'updateIfChanged').returns($updateResponse) + }) it('calls ChangeTrackingManager#updateIfChanged() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingManager.updateIfChanged).to.have.been.calledWith({ - iofogUuid: ioFogUuid - }, data, transaction); - }); + iofogUuid: ioFogUuid, + }, data, transaction) + }) context('when ChangeTrackingManager#updateIfChanged() fails', () => { - def('updateResponse', () => Promise.reject(error)); + def('updateResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingManager#updateIfChanged() succeeds', () => { it('fulfills the promise', () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.getByIoFogUuid()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - const ioFogUuid = 'testUuid'; + const ioFogUuid = 'testUuid' - def('subject', () => $subject.getByIoFogUuid(ioFogUuid, transaction)); - def('updateResponse', () => Promise.resolve()); + def('subject', () => $subject.getByIoFogUuid(ioFogUuid, transaction)) + def('updateResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(ChangeTrackingManager, 'findOne').returns($updateResponse); - }); + $sandbox.stub(ChangeTrackingManager, 'findOne').returns($updateResponse) + }) it('calls ChangeTrackingManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingManager.findOne).to.have.been.calledWith({ - iofogUuid: ioFogUuid - }, transaction); - }); + iofogUuid: ioFogUuid, + }, transaction) + }) context('when ChangeTrackingManager#findOne() fails', () => { - def('updateResponse', () => Promise.reject(error)); + def('updateResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingManager#findOne() succeeds', () => { it('fulfills the promise', () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); - -}); \ No newline at end of file + }) +}) diff --git a/test/src/services/connector-port-service.test.js b/test/src/services/connector-port-service.test.js index c2cb72e22..ad697c07d 100644 --- a/test/src/services/connector-port-service.test.js +++ b/test/src/services/connector-port-service.test.js @@ -58,4 +58,4 @@ // }) // }) // }) -// }); \ No newline at end of file +// }); diff --git a/test/src/services/connector-service.test.js b/test/src/services/connector-service.test.js index 0b98128e3..198fa859c 100644 --- a/test/src/services/connector-service.test.js +++ b/test/src/services/connector-service.test.js @@ -1,25 +1,24 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); - -const ConnectorManager = require('../../../src/sequelize/managers/connector-manager'); -const MicroserviceService = require('../../../src/services/microservices-service'); -const ConnectorService = require('../../../src/services/connector-service'); -const Validator = require('../../../src/schemas'); -const AppHelper = require('../../../src/helpers/app-helper'); -const ConnectorPortManager = require('../../../src/sequelize/managers/connector-port-manager'); -const Sequelize = require('sequelize'); -const Op = Sequelize.Op; -const qs = require('qs'); +const {expect} = require('chai') +const sinon = require('sinon') + +const ConnectorManager = require('../../../src/sequelize/managers/connector-manager') +const MicroserviceService = require('../../../src/services/microservices-service') +const ConnectorService = require('../../../src/services/connector-service') +const Validator = require('../../../src/schemas') +const AppHelper = require('../../../src/helpers/app-helper') +const ConnectorPortManager = require('../../../src/sequelize/managers/connector-port-manager') +const Sequelize = require('sequelize') +const Op = Sequelize.Op describe('Connector Service', () => { - def('subject', () => ConnectorService); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => ConnectorService) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.createConnector()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const connectorData = { name: 'testName', @@ -27,121 +26,121 @@ describe('Connector Service', () => { publicIp: 'testPublicIp', cert: 'testCert', isSelfSignedCert: false, - devMode: true - }; + devMode: true, + } - def('subject', () => $subject.createConnector(connectorData, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('isValidDomainResponse', () => false); - def('isValidPublicIpResponse', () => true); - def('isValidPublicIpResponse2', () => true); - def('findConnectorResponse', () => Promise.resolve()); - def('createConnectorResponse', () => Promise.resolve()); + def('subject', () => $subject.createConnector(connectorData, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('isValidDomainResponse', () => false) + def('isValidPublicIpResponse', () => true) + def('isValidPublicIpResponse2', () => true) + def('findConnectorResponse', () => Promise.resolve()) + def('createConnectorResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(AppHelper, 'isValidDomain').returns($isValidDomainResponse); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(AppHelper, 'isValidDomain').returns($isValidDomainResponse) $sandbox.stub(AppHelper, 'isValidPublicIP') - .onFirstCall().returns($isValidPublicIpResponse) - .onSecondCall().returns($isValidPublicIpResponse2); - $sandbox.stub(ConnectorManager, 'findOne').returns($findConnectorResponse); - $sandbox.stub(ConnectorManager, 'create').returns($createConnectorResponse); - }); + .onFirstCall().returns($isValidPublicIpResponse) + .onSecondCall().returns($isValidPublicIpResponse2) + $sandbox.stub(ConnectorManager, 'findOne').returns($findConnectorResponse) + $sandbox.stub(ConnectorManager, 'create').returns($createConnectorResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(connectorData, Validator.schemas.connectorCreate); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(connectorData, Validator.schemas.connectorCreate) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls AppHelper#isValidDomain() with correct args', async () => { - await $subject; - expect(AppHelper.isValidDomain).to.have.been.calledWith(connectorData.domain); - }); + await $subject + expect(AppHelper.isValidDomain).to.have.been.calledWith(connectorData.domain) + }) context('when AppHelper#isValidDomain() fails', () => { - def('isValidDomainResponse', () => error); + def('isValidDomainResponse', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#isValidDomain() succeeds', () => { it('calls AppHelper#isValidPublicIP() with correct args', async () => { - await $subject; - expect(AppHelper.isValidPublicIP).to.have.been.calledWith(connectorData.domain); - }); + await $subject + expect(AppHelper.isValidPublicIP).to.have.been.calledWith(connectorData.domain) + }) context('when AppHelper#isValidPublicIP() fails', () => { - def('isValidPublicIpResponse', () => error); + def('isValidPublicIpResponse', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#isValidPublicIP() succeeds', () => { it('calls AppHelper#isValidPublicIP() with correct args', async () => { - await $subject; - expect(AppHelper.isValidPublicIP).to.have.been.calledWith(connectorData.publicIp); - }); + await $subject + expect(AppHelper.isValidPublicIP).to.have.been.calledWith(connectorData.publicIp) + }) context('when AppHelper#isValidPublicIP() fails', () => { - def('isValidPublicIpResponse2', () => error); + def('isValidPublicIpResponse2', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#isValidPublicIP() succeeds', () => { it('calls ConnectorManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(ConnectorManager.findOne).to.have.been.calledWith({ [Op.or]: [ { - name: connectorData.name + name: connectorData.name, }, { - publicIp: connectorData.publicIp + publicIp: connectorData.publicIp, }, { - domain: connectorData.domain - } - ] - }, transaction); - }); + domain: connectorData.domain, + }, + ], + }, transaction) + }) context('when ConnectorManager#findOne() fails', () => { - def('findConnectorResponse', () => Promise.reject(error)); + def('findConnectorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ConnectorManager#findOne() succeeds', () => { it('calls ConnectorManager#create() with correct args', async () => { - await $subject; - expect(ConnectorManager.create).to.have.been.calledWith(connectorData, transaction); - }); + await $subject + expect(ConnectorManager.create).to.have.been.calledWith(connectorData, transaction) + }) context('when ConnectorManager#create() fails', () => { - def('createConnectorResponse', () => Promise.reject(error)); + def('createConnectorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ConnectorManager#create() succeeds', () => { it('fulfills the promise', () => { @@ -153,11 +152,11 @@ describe('Connector Service', () => { }) }) }) - }); + }) describe('.updateConnector()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const connectorData = { name: 'testName', @@ -165,149 +164,149 @@ describe('Connector Service', () => { publicIp: 'testPublicIp', cert: 'testCert', isSelfSignedCert: false, - devMode: true - }; + devMode: true, + } - const connector = {}; + const connector = {} - def('subject', () => $subject.updateConnector(connectorData, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('isValidDomainResponse', () => false); - def('isValidPublicIpResponse', () => true); - def('isValidPublicIpResponse2', () => true); - def('updateConnectorResponse', () => Promise.resolve()); - def('findOneConnectorResponse', () => Promise.resolve(connector)); - def('updateRouteOverConnectorResponse', () => Promise.resolve()); - def('updatePortMappingOverConnectorResponse', () => Promise.resolve()); + def('subject', () => $subject.updateConnector(connectorData, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('isValidDomainResponse', () => false) + def('isValidPublicIpResponse', () => true) + def('isValidPublicIpResponse2', () => true) + def('updateConnectorResponse', () => Promise.resolve()) + def('findOneConnectorResponse', () => Promise.resolve(connector)) + def('updateRouteOverConnectorResponse', () => Promise.resolve()) + def('updatePortMappingOverConnectorResponse', () => Promise.resolve()) const queryConnectorData = { - publicIp: connectorData.publicIp - }; + publicIp: connectorData.publicIp, + } beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(AppHelper, 'isValidDomain').returns($isValidDomainResponse); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(AppHelper, 'isValidDomain').returns($isValidDomainResponse) $sandbox.stub(AppHelper, 'isValidPublicIP') - .onFirstCall().returns($isValidPublicIpResponse) - .onSecondCall().returns($isValidPublicIpResponse2); - $sandbox.stub(ConnectorManager, 'update').returns($updateConnectorResponse); - $sandbox.stub(ConnectorManager, 'findOne').returns($findOneConnectorResponse); - $sandbox.stub(MicroserviceService, 'updateRouteOverConnector').returns($updateRouteOverConnectorResponse); - $sandbox.stub(MicroserviceService, 'updatePortMappingOverConnector').returns($updatePortMappingOverConnectorResponse); - }); + .onFirstCall().returns($isValidPublicIpResponse) + .onSecondCall().returns($isValidPublicIpResponse2) + $sandbox.stub(ConnectorManager, 'update').returns($updateConnectorResponse) + $sandbox.stub(ConnectorManager, 'findOne').returns($findOneConnectorResponse) + $sandbox.stub(MicroserviceService, 'updateRouteOverConnector').returns($updateRouteOverConnectorResponse) + $sandbox.stub(MicroserviceService, 'updatePortMappingOverConnector').returns($updatePortMappingOverConnectorResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(connectorData, Validator.schemas.connectorUpdate); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(connectorData, Validator.schemas.connectorUpdate) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls AppHelper#isValidDomain() with correct args', async () => { - await $subject; - expect(AppHelper.isValidDomain).to.have.been.calledWith(connectorData.domain); - }); + await $subject + expect(AppHelper.isValidDomain).to.have.been.calledWith(connectorData.domain) + }) context('when AppHelper#isValidDomain() fails', () => { - def('isValidDomainResponse', () => error); + def('isValidDomainResponse', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#isValidDomain() succeeds', () => { it('calls AppHelper#isValidPublicIP() with correct args', async () => { - await $subject; - expect(AppHelper.isValidPublicIP).to.have.been.calledWith(connectorData.domain); - }); + await $subject + expect(AppHelper.isValidPublicIP).to.have.been.calledWith(connectorData.domain) + }) context('when AppHelper#isValidPublicIP() fails', () => { - def('isValidPublicIpResponse', () => error); + def('isValidPublicIpResponse', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#isValidPublicIP() succeeds', () => { it('calls AppHelper#isValidPublicIP() with correct args', async () => { - await $subject; - expect(AppHelper.isValidPublicIP).to.have.been.calledWith(connectorData.publicIp); - }); + await $subject + expect(AppHelper.isValidPublicIP).to.have.been.calledWith(connectorData.publicIp) + }) context('when AppHelper#isValidPublicIP() fails', () => { - def('isValidPublicIpResponse2', () => error); + def('isValidPublicIpResponse2', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#isValidPublicIP() succeeds', () => { it('calls ConnectorManager#update() with correct args', async () => { - await $subject; - expect(ConnectorManager.update).to.have.been.calledWith(queryConnectorData, connectorData, transaction); - }); + await $subject + expect(ConnectorManager.update).to.have.been.calledWith(queryConnectorData, connectorData, transaction) + }) context('when ConnectorManager#update() fails', () => { - def('updateConnectorResponse', () => Promise.reject(error)); + def('updateConnectorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ConnectorManager#update() succeeds', () => { it('calls ConnectorManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(ConnectorManager.findOne).to.have.been.calledWith({ - publicIp: connectorData.publicIp - }, transaction); - }); + publicIp: connectorData.publicIp, + }, transaction) + }) context('when ConnectorManager#findOne() fails', () => { - def('findOneConnectorResponse', () => Promise.reject(error)); + def('findOneConnectorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ConnectorManager#findOne() succeeds', () => { it('calls MicroserviceService#updateRouteOverConnector() with correct args', async () => { - await $subject; - expect(MicroserviceService.updateRouteOverConnector).to.have.been.calledWith(connector, transaction); - }); + await $subject + expect(MicroserviceService.updateRouteOverConnector).to.have.been.calledWith(connector, transaction) + }) context('when MicroserviceService#updateRouteOverConnector() fails', () => { - def('updateRouteOverConnectorResponse', () => Promise.reject(error)); + def('updateRouteOverConnectorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceService#updateRouteOverConnector() succeeds', () => { it('calls MicroserviceService#updatePortMappingOverConnector() with correct args', async () => { - await $subject; - expect(MicroserviceService.updatePortMappingOverConnector).to.have.been.calledWith(connector, transaction); - }); + await $subject + expect(MicroserviceService.updatePortMappingOverConnector).to.have.been.calledWith(connector, transaction) + }) context('when MicroserviceService#updatePortMappingOverConnector() fails', () => { - def('updatePortMappingOverConnectorResponse', () => Promise.reject(error)); + def('updatePortMappingOverConnectorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceService#updatePortMappingOverConnector() succeeds', () => { it('fulfills the promise', () => { @@ -321,11 +320,11 @@ describe('Connector Service', () => { }) }) }) - }); + }) describe('.deleteConnector()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const connectorData = { name: 'testName', @@ -333,87 +332,87 @@ describe('Connector Service', () => { publicIp: 'testPublicIp', cert: 'testCert', isSelfSignedCert: false, - devMode: true - }; + devMode: true, + } const connector = { - id: 15 - }; + id: 15, + } - def('subject', () => $subject.deleteConnector(connectorData, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('findConnectorResponse', () => Promise.resolve(connector)); - def('findConnectorPortsResponse', () => Promise.resolve()); - def('deleteConnectorResponse', () => Promise.resolve()); + def('subject', () => $subject.deleteConnector(connectorData, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('findConnectorResponse', () => Promise.resolve(connector)) + def('findConnectorPortsResponse', () => Promise.resolve()) + def('deleteConnectorResponse', () => Promise.resolve()) const queryConnectorData = { - publicIp: connectorData.publicIp - }; + publicIp: connectorData.publicIp, + } beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(ConnectorManager, 'findOne').returns($findConnectorResponse); - $sandbox.stub(ConnectorPortManager, 'findAll').returns($findConnectorPortsResponse); - $sandbox.stub(ConnectorManager, 'delete').returns($deleteConnectorResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(ConnectorManager, 'findOne').returns($findConnectorResponse) + $sandbox.stub(ConnectorPortManager, 'findAll').returns($findConnectorPortsResponse) + $sandbox.stub(ConnectorManager, 'delete').returns($deleteConnectorResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(connectorData, Validator.schemas.connectorDelete); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(connectorData, Validator.schemas.connectorDelete) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls ConnectorManager#findOne() with correct args', async () => { - await $subject; - expect(ConnectorManager.findOne).to.have.been.calledWith(queryConnectorData, transaction); - }); + await $subject + expect(ConnectorManager.findOne).to.have.been.calledWith(queryConnectorData, transaction) + }) context('when ConnectorManager#findOne() fails', () => { - def('findConnectorResponse', () => error); + def('findConnectorResponse', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when ConnectorManager#findOne() succeeds', () => { it('calls ConnectorPortManager#findAll() with correct args', async () => { - await $subject; + await $subject expect(ConnectorPortManager.findAll).to.have.been.calledWith({ - connectorId: connector.id - }, transaction); - }); + connectorId: connector.id, + }, transaction) + }) context('when ConnectorPortManager#findAll() fails', () => { def('findConnectorPortsResponse', () => { - }); + }) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when ConnectorPortManager#findAll() succeeds', () => { it('calls ConnectorManager#delete() with correct args', async () => { - await $subject; - expect(ConnectorManager.delete).to.have.been.calledWith(queryConnectorData, transaction); - }); + await $subject + expect(ConnectorManager.delete).to.have.been.calledWith(queryConnectorData, transaction) + }) context('when ConnectorManager#delete() fails', () => { - def('deleteConnectorResponse', () => error); + def('deleteConnectorResponse', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when ConnectorManager#delete() succeeds', () => { it('fulfills the promise', () => { @@ -423,36 +422,36 @@ describe('Connector Service', () => { }) }) }) - }); + }) describe('.getConnectorList()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('subject', () => $subject.getConnectorList(transaction)); - def('findConnectorsResponse', () => Promise.resolve()); + def('subject', () => $subject.getConnectorList(transaction)) + def('findConnectorsResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(ConnectorManager, 'findAll').returns($findConnectorsResponse); - }); + $sandbox.stub(ConnectorManager, 'findAll').returns($findConnectorsResponse) + }) it('calls ConnectorManager#findAll() with correct args', async () => { - await $subject; - expect(ConnectorManager.findAll).to.have.been.calledWith({}, transaction); - }); + await $subject + expect(ConnectorManager.findAll).to.have.been.calledWith({}, transaction) + }) context('when ConnectorManager#findAll() fails', () => { - def('findConnectorsResponse', () => Promise.reject(error)); + def('findConnectorsResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ConnectorManager#findAll() succeeds', () => { it('fulfills the promise', () => { return expect($subject).to.eventually.equal(undefined) }) }) - }); -}); \ No newline at end of file + }) +}) diff --git a/test/src/services/controller-service.test.js b/test/src/services/controller-service.test.js index 98650722c..add6e044e 100644 --- a/test/src/services/controller-service.test.js +++ b/test/src/services/controller-service.test.js @@ -1,101 +1,101 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); +const {expect} = require('chai') +const sinon = require('sinon') -const ControllerService = require('../../../src/services/controller-service'); -const ioFogTypesManager = require('../../../src/sequelize/managers/iofog-type-manager'); -const Config = require('../../../src/config'); +const ControllerService = require('../../../src/services/controller-service') +const ioFogTypesManager = require('../../../src/sequelize/managers/iofog-type-manager') +const Config = require('../../../src/config') describe('Controller Service', () => { - def('subject', () => ControllerService); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => ControllerService) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) - const isCLI = false; + const isCLI = false describe('.getFogTypes()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('subject', () => $subject.getFogTypes(isCLI, transaction)); + def('subject', () => $subject.getFogTypes(isCLI, transaction)) def('findResponse', () => Promise.resolve([{ id: 15, name: 'testName', image: 'testImage', - description: 'testDescription' - }])); + description: 'testDescription', + }])) beforeEach(() => { - $sandbox.stub(ioFogTypesManager, 'findAll').returns($findResponse); - }); + $sandbox.stub(ioFogTypesManager, 'findAll').returns($findResponse) + }) it('calls ioFogTypesManager#findAll() with correct args', async () => { - await $subject; - expect(ioFogTypesManager.findAll).to.have.been.calledWith({}, transaction); - }); + await $subject + expect(ioFogTypesManager.findAll).to.have.been.calledWith({}, transaction) + }) context('when ioFogTypesManager#findAll() fails', () => { - def('findResponse', () => Promise.reject(error)); + def('findResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogTypesManager#findAll() succeeds', () => { it('fulfills the promise', () => { return expect($subject).to.eventually.have.property('fogTypes') }) }) - }); + }) describe('.emailActivation()', () => { - const error = 'Error!'; + const error = 'Error!' - def('subject', () => $subject.emailActivation(isCLI)); - def('getResponse', () => Promise.resolve()); + def('subject', () => $subject.emailActivation(isCLI)) + def('getResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Config, 'get').returns($getResponse); - }); + $sandbox.stub(Config, 'get').returns($getResponse) + }) it('calls Config#get() with correct args', async () => { - await $subject; - expect(Config.get).to.have.been.calledWith('Email:ActivationEnabled'); - }); + await $subject + expect(Config.get).to.have.been.calledWith('Email:ActivationEnabled') + }) context('when Config#get() fails', () => { - def('getResponse', () => Promise.reject(error)); + def('getResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Config#get() succeeds', () => { it('fulfills the promise', () => { return expect($subject).to.eventually.have.property('isEmailActivationEnabled') }) }) - }); + }) + /* describe('.statusController()', () => { - const error = 'Error!'; + const error = 'Error!' - def('subject', () => $subject.statusController(isCLI)); - def('getResponse', () => Promise.resolve()); + def('subject', () => $subject.statusController(isCLI)) + def('getResponse', () => Promise.resolve()) beforeEach(() => { // TODO daemon.status - //$sandbox.stub(daemon, 'status').returns($getResponse); - }); + // $sandbox.stub(daemon, 'status').returns($getResponse); + }) // it('Returns valid status', () => { // return expect($subject).to.have.property('status') && // expect($subject).to.have.property('timestamp') // }) - }); - - -}); \ No newline at end of file + }) + */ +}) diff --git a/test/src/services/diagnostic-service.test.js b/test/src/services/diagnostic-service.test.js index daec41fe2..38e882d87 100644 --- a/test/src/services/diagnostic-service.test.js +++ b/test/src/services/diagnostic-service.test.js @@ -1,115 +1,115 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); -const StraceDiagnosticManager = require('../../../src/sequelize/managers/strace-diagnostics-manager'); -const DiagnosticService = require('../../../src/services/diagnostic-service'); -const FtpClient = require('ftp'); -const fs = require('fs'); -const MicroserviceService = require('../../../src/services/microservices-service'); -const ChangeTrackingService = require('../../../src/services/change-tracking-service'); -const Validator = require('../../../src/schemas'); -const MicroserviceManager = require('../../../src/sequelize/managers/microservice-manager'); -const Config = require('../../../src/config'); +const {expect} = require('chai') +const sinon = require('sinon') +const StraceDiagnosticManager = require('../../../src/sequelize/managers/strace-diagnostics-manager') +const DiagnosticService = require('../../../src/services/diagnostic-service') +const FtpClient = require('ftp') +const fs = require('fs') +const MicroserviceService = require('../../../src/services/microservices-service') +const ChangeTrackingService = require('../../../src/services/change-tracking-service') +const Validator = require('../../../src/schemas') +const MicroserviceManager = require('../../../src/sequelize/managers/microservice-manager') +const Config = require('../../../src/config') describe('DiagnosticService Service', () => { - def('subject', () => DiagnosticService); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => DiagnosticService) + def('sandbox', () => sinon.createSandbox()) - const isCLI = true; + const isCLI = true - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.changeMicroserviceStraceState()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - const user = 'user!'; + const user = 'user!' - const uuid = 'testUuid'; + const uuid = 'testUuid' const data = { - enable: true - }; + enable: true, + } const straceObj = { straceRun: data.enable, - microserviceUuid: uuid - }; + microserviceUuid: uuid, + } const microservice = { - iofogUuid: 'testIoFogUuid' - }; + iofogUuid: 'testIoFogUuid', + } - def('subject', () => $subject.changeMicroserviceStraceState(uuid, data, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('getMicroserviceResponse', () => Promise.resolve(microservice)); - def('updateOrCreateDiagnosticResponse', () => Promise.resolve()); - def('updateChangeTrackingResponse', () => Promise.resolve()); + def('subject', () => $subject.changeMicroserviceStraceState(uuid, data, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('getMicroserviceResponse', () => Promise.resolve(microservice)) + def('updateOrCreateDiagnosticResponse', () => Promise.resolve()) + def('updateChangeTrackingResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(MicroserviceService, 'getMicroservice').returns($getMicroserviceResponse); - $sandbox.stub(StraceDiagnosticManager, 'updateOrCreate').returns($updateOrCreateDiagnosticResponse); - $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(MicroserviceService, 'getMicroservice').returns($getMicroserviceResponse) + $sandbox.stub(StraceDiagnosticManager, 'updateOrCreate').returns($updateOrCreateDiagnosticResponse) + $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(data, Validator.schemas.straceStateUpdate); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(data, Validator.schemas.straceStateUpdate) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls MicroserviceService#getMicroservice() with correct args', async () => { - await $subject; - expect(MicroserviceService.getMicroservice).to.have.been.calledWith(uuid, user, isCLI, transaction); - }); + await $subject + expect(MicroserviceService.getMicroservice).to.have.been.calledWith(uuid, user, isCLI, transaction) + }) context('when MicroserviceService#getMicroservice() fails', () => { - def('getMicroserviceResponse', () => Promise.reject(error)); + def('getMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceService#getMicroservice() succeeds', () => { it('calls StraceDiagnosticManager#updateOrCreate() with correct args', async () => { - await $subject; + await $subject expect(StraceDiagnosticManager.updateOrCreate).to.have.been.calledWith({ - microserviceUuid: uuid - }, straceObj, transaction); - }); + microserviceUuid: uuid, + }, straceObj, transaction) + }) context('when StraceDiagnosticManager#updateOrCreate() fails', () => { - def('updateOrCreateDiagnosticResponse', () => Promise.reject(error)); + def('updateOrCreateDiagnosticResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when StraceDiagnosticManager#updateOrCreate() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(microservice.iofogUuid, - ChangeTrackingService.events.diagnostics, transaction); - }); + ChangeTrackingService.events.diagnostics, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('updateChangeTrackingResponse', () => Promise.reject(error)); + def('updateChangeTrackingResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('fulfills the promise', () => { @@ -119,100 +119,100 @@ describe('DiagnosticService Service', () => { }) }) }) - }); + }) describe('.getMicroserviceStraceData()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const uuid = 'testUuid'; + const uuid = 'testUuid' const data = { - format: 'string' - }; + format: 'string', + } const microservice = { - iofogUuid: 'testIoFogUuid' - }; + iofogUuid: 'testIoFogUuid', + } - def('subject', () => $subject.getMicroserviceStraceData(uuid, data, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('getMicroserviceResponse', () => Promise.resolve(microservice)); - def('findStraceResponse', () => Promise.resolve({})); - def('configGetResponse', () => Promise.resolve()); + def('subject', () => $subject.getMicroserviceStraceData(uuid, data, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('getMicroserviceResponse', () => Promise.resolve(microservice)) + def('findStraceResponse', () => Promise.resolve({})) + def('configGetResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(MicroserviceManager, 'findOne').returns($getMicroserviceResponse); - $sandbox.stub(StraceDiagnosticManager, 'findOne').returns($findStraceResponse); - $sandbox.stub(Config, 'get').returns($configGetResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(MicroserviceManager, 'findOne').returns($getMicroserviceResponse) + $sandbox.stub(StraceDiagnosticManager, 'findOne').returns($findStraceResponse) + $sandbox.stub(Config, 'get').returns($configGetResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(data, Validator.schemas.straceGetData); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(data, Validator.schemas.straceGetData) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls MicroserviceManager#findOne() with correct args', async () => { - await $subject; + await $subject const microserviceWhere = isCLI ? {uuid: uuid} - : {uuid: uuid, userId: user.id}; - expect(MicroserviceManager.findOne).to.have.been.calledWith(microserviceWhere, transaction); - }); + : {uuid: uuid, userId: user.id} + expect(MicroserviceManager.findOne).to.have.been.calledWith(microserviceWhere, transaction) + }) context('when MicroserviceManager#findOne() fails', () => { - def('getMicroserviceResponse', () => Promise.reject(error)); + def('getMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#findOne() succeeds', () => { it('calls StraceDiagnosticManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(StraceDiagnosticManager.findOne).to.have.been.calledWith({ - microserviceUuid: uuid - }, transaction); - }); + microserviceUuid: uuid, + }, transaction) + }) context('when StraceDiagnosticManager#findOne() fails', () => { - def('findStraceResponse', () => Promise.reject(error)); + def('findStraceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when StraceDiagnosticManager#findOne() succeeds', () => { it('calls Config#get() with correct args', async () => { - await $subject; - expect(Config.get).to.have.been.calledWith('Diagnostics:DiagnosticDir'); - }); + await $subject + expect(Config.get).to.have.been.calledWith('Diagnostics:DiagnosticDir') + }) context('when Config#get() fails', () => { - def('configGetResponse', () => error); + def('configGetResponse', () => error) it(`fails with ${error}`, () => { return expect($subject).to.be.eventually.have.property('data') }) - }); + }) context('when Config#get() succeeds', () => { it('fulfills the promise', () => { @@ -222,222 +222,221 @@ describe('DiagnosticService Service', () => { }) }) }) - }); + }) describe('.postMicroserviceStraceDatatoFtp()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const uuid = 'testUuid'; + const uuid = 'testUuid' const data = { ftpHost: 'testHost', ftpPort: 5555, ftpUser: 'testUser', ftpPass: 'testPass', - ftpDestDir: 'testDir' - }; + ftpDestDir: 'testDir', + } const connectionData = { host: data.ftpHost, port: data.ftpPort, user: data.ftpUser, password: data.ftpPass, - protocol: 'ftp' - }; + protocol: 'ftp', + } const microservice = { - iofogUuid: 'testIoFogUuid' - }; + iofogUuid: 'testIoFogUuid', + } - const dirPath = '/somewhere/on/the/disk'; - const fPath = dirPath + '/' + uuid; + const dirPath = '/somewhere/on/the/disk' const straceData = { - buffer: 'data' - }; + buffer: 'data', + } - def('subject', () => $subject.postMicroserviceStraceDatatoFtp(uuid, data, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('getMicroserviceResponse', () => Promise.resolve(microservice)); - def('findStraceResponse', () => Promise.resolve(straceData)); - def('configGetResponse', () => dirPath); + def('subject', () => $subject.postMicroserviceStraceDatatoFtp(uuid, data, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('getMicroserviceResponse', () => Promise.resolve(microservice)) + def('findStraceResponse', () => Promise.resolve(straceData)) + def('configGetResponse', () => dirPath) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(MicroserviceManager, 'findOne').returns($getMicroserviceResponse); - $sandbox.stub(StraceDiagnosticManager, 'findOne').returns($findStraceResponse); - $sandbox.stub(Config, 'get').returns($configGetResponse); - $sandbox.stub(fs, 'existsSync').returns(true); - $sandbox.stub(fs, 'mkdirSync').callsFake(function (dir) {}); - $sandbox.stub(fs, 'writeFileSync').callsFake(function (filePath, data, cb) {}); - $sandbox.stub(fs, 'unlink').callsFake(function (filePath) {}); - $sandbox.stub(FtpClient.prototype, 'connect').withArgs(connectionData).callsFake(function (options) { - this.emit('ready'); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(MicroserviceManager, 'findOne').returns($getMicroserviceResponse) + $sandbox.stub(StraceDiagnosticManager, 'findOne').returns($findStraceResponse) + $sandbox.stub(Config, 'get').returns($configGetResponse) + $sandbox.stub(fs, 'existsSync').returns(true) + $sandbox.stub(fs, 'mkdirSync').callsFake(function(dir) {}) + $sandbox.stub(fs, 'writeFileSync').callsFake(function(filePath, data, cb) {}) + $sandbox.stub(fs, 'unlink').callsFake(function(filePath) {}) + $sandbox.stub(FtpClient.prototype, 'connect').withArgs(connectionData).callsFake(function(options) { + this.emit('ready') + }) $sandbox.stub(FtpClient.prototype, 'put').callsFake((filePath, anotherPath, callback) => { callback(undefined) - }); - $sandbox.stub(FtpClient.prototype, 'end').callsFake(function (options) {}); - }); + }) + $sandbox.stub(FtpClient.prototype, 'end').callsFake(function(options) {}) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(data, Validator.schemas.stracePostToFtp); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(data, Validator.schemas.stracePostToFtp) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls MicroserviceManager#findOne() with correct args', async () => { - await $subject; + await $subject const microserviceWhere = isCLI ? {uuid: uuid} - : {uuid: uuid, userId: user.id}; - expect(MicroserviceManager.findOne).to.have.been.calledWith(microserviceWhere, transaction); - }); + : {uuid: uuid, userId: user.id} + expect(MicroserviceManager.findOne).to.have.been.calledWith(microserviceWhere, transaction) + }) context('when MicroserviceManager#findOne() fails', () => { - def('getMicroserviceResponse', () => Promise.reject(error)); + def('getMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#findOne() succeeds', () => { it('calls StraceDiagnosticManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(StraceDiagnosticManager.findOne).to.have.been.calledWith({ - microserviceUuid: uuid - }, transaction); - }); + microserviceUuid: uuid, + }, transaction) + }) context('when StraceDiagnosticManager#findOne() fails', () => { - def('findStraceResponse', () => Promise.reject(error)); + def('findStraceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when StraceDiagnosticManager#findOne() succeeds', () => { it('calls Config#get() with correct args', async () => { - await $subject; - expect(Config.get).to.have.been.calledWith('Diagnostics:DiagnosticDir'); - }); + await $subject + expect(Config.get).to.have.been.calledWith('Diagnostics:DiagnosticDir') + }) context('when Config#get() fails', () => { - def('configGetResponse', () => error); + def('configGetResponse', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.equal(undefined) - }); - }); + }) + }) context('when Config#get() succeeds', () => { it('calls FtpClient#connect() with correct args', async () => { - await $subject; - expect(FtpClient.prototype.connect).to.have.been.calledWith(connectionData); + await $subject + expect(FtpClient.prototype.connect).to.have.been.calledWith(connectionData) }) }) }) }) }) - }); + }) describe('.postMicroserviceImageSnapshotCreate()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - const user = 'user!'; + const user = 'user!' - const microserviceUuid = 'testUuid'; + const microserviceUuid = 'testUuid' const microserviceToUpdate = { - imageSnapshot: 'get_image' - }; + imageSnapshot: 'get_image', + } const microservice = { iofogUuid: 'testIoFogUuid', - uuid: 'testMicroserviceUuid' - }; + uuid: 'testMicroserviceUuid', + } - def('subject', () => $subject.postMicroserviceImageSnapshotCreate(microserviceUuid, user, isCLI, transaction)); - def('findMicroserviceResponse', () => Promise.resolve(microservice)); - def('updateMicroserviceResponse', () => Promise.resolve()); - def('updateChangeTrackingResponse', () => Promise.resolve()); + def('subject', () => $subject.postMicroserviceImageSnapshotCreate(microserviceUuid, user, isCLI, transaction)) + def('findMicroserviceResponse', () => Promise.resolve(microservice)) + def('updateMicroserviceResponse', () => Promise.resolve()) + def('updateChangeTrackingResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(MicroserviceManager, 'findOneWithDependencies').returns($findMicroserviceResponse); - $sandbox.stub(MicroserviceManager, 'update').returns($updateMicroserviceResponse); - $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); - }); + $sandbox.stub(MicroserviceManager, 'findOneWithDependencies').returns($findMicroserviceResponse) + $sandbox.stub(MicroserviceManager, 'update').returns($updateMicroserviceResponse) + $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse) + }) it('calls MicroserviceManager#findOneWithDependencies() with correct args', async () => { - await $subject; + await $subject const where = isCLI ? { - uuid: microserviceUuid + uuid: microserviceUuid, } : { uuid: microserviceUuid, - userId: user.id - }; - expect(MicroserviceManager.findOneWithDependencies).to.have.been.calledWith(where, {}, transaction); - }); + userId: user.id, + } + expect(MicroserviceManager.findOneWithDependencies).to.have.been.calledWith(where, {}, transaction) + }) context('when MicroserviceManager#findOneWithDependencies() fails', () => { - def('findMicroserviceResponse', () => Promise.reject(error)); + def('findMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#findOneWithDependencies() succeeds', () => { it('calls MicroserviceManager#update() with correct args', async () => { - await $subject; + await $subject expect(MicroserviceManager.update).to.have.been.calledWith({ - uuid: microservice.uuid - }, microserviceToUpdate, transaction); - }); + uuid: microservice.uuid, + }, microserviceToUpdate, transaction) + }) context('when MicroserviceManager#update() fails', () => { - def('updateMicroserviceResponse', () => Promise.reject(error)); + def('updateMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#update() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(microservice.iofogUuid, - ChangeTrackingService.events.imageSnapshot, transaction); - }); + ChangeTrackingService.events.imageSnapshot, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('updateChangeTrackingResponse', () => Promise.reject(error)); + def('updateChangeTrackingResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('fulfills the promise', () => { @@ -446,74 +445,74 @@ describe('DiagnosticService Service', () => { }) }) }) - }); + }) describe('.getMicroserviceImageSnapshot()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - const user = 'user!'; + const user = 'user!' - const microserviceUuid = 'testUuid'; + const microserviceUuid = 'testUuid' const microserviceToUpdate = { - imageSnapshot: '' - }; + imageSnapshot: '', + } const microservice = { iofogUuid: 'testIoFogUuid', uuid: 'testMicroserviceUuid', - imageSnapshot: 'testImagePath' - }; + imageSnapshot: 'testImagePath', + } - def('subject', () => $subject.getMicroserviceImageSnapshot(microserviceUuid, user, isCLI, transaction)); - def('findMicroserviceResponse', () => Promise.resolve(microservice)); - def('updateMicroserviceResponse', () => Promise.resolve()); + def('subject', () => $subject.getMicroserviceImageSnapshot(microserviceUuid, user, isCLI, transaction)) + def('findMicroserviceResponse', () => Promise.resolve(microservice)) + def('updateMicroserviceResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(MicroserviceManager, 'findOneWithDependencies').returns($findMicroserviceResponse); - $sandbox.stub(MicroserviceManager, 'update').returns($updateMicroserviceResponse); - }); + $sandbox.stub(MicroserviceManager, 'findOneWithDependencies').returns($findMicroserviceResponse) + $sandbox.stub(MicroserviceManager, 'update').returns($updateMicroserviceResponse) + }) it('calls MicroserviceManager#findOneWithDependencies() with correct args', async () => { - await $subject; + await $subject const where = isCLI ? { - uuid: microserviceUuid + uuid: microserviceUuid, } : { uuid: microserviceUuid, - userId: user.id - }; - expect(MicroserviceManager.findOneWithDependencies).to.have.been.calledWith(where, {}, transaction); - }); + userId: user.id, + } + expect(MicroserviceManager.findOneWithDependencies).to.have.been.calledWith(where, {}, transaction) + }) context('when MicroserviceManager#findOneWithDependencies() fails', () => { - def('findMicroserviceResponse', () => Promise.reject(error)); + def('findMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#findOneWithDependencies() succeeds', () => { it('calls MicroserviceManager#update() with correct args', async () => { - await $subject; + await $subject expect(MicroserviceManager.update).to.have.been.calledWith({ - uuid: microservice.uuid - }, microserviceToUpdate, transaction); - }); + uuid: microservice.uuid, + }, microserviceToUpdate, transaction) + }) context('when MicroserviceManager#update() fails', () => { - def('updateMicroserviceResponse', () => Promise.reject(error)); + def('updateMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#update() succeeds', () => { it('fulfills the promise', () => { @@ -521,7 +520,5 @@ describe('DiagnosticService Service', () => { }) }) }) - }); - - -}); \ No newline at end of file + }) +}) diff --git a/test/src/services/email-activation-code-service.test.js b/test/src/services/email-activation-code-service.test.js index 862007ae5..c55bb49ae 100644 --- a/test/src/services/email-activation-code-service.test.js +++ b/test/src/services/email-activation-code-service.test.js @@ -1,63 +1,63 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); +const {expect} = require('chai') +const sinon = require('sinon') -const EmailActivationCodeManager = require('../../../src/sequelize/managers/email-activation-code-manager'); -const EmailActivationCodeService = require('../../../src/services/email-activation-code-service'); -const AppHelper = require('../../../src/helpers/app-helper'); -const ErrorMessages = require('../../../src/helpers/error-messages'); +const EmailActivationCodeManager = require('../../../src/sequelize/managers/email-activation-code-manager') +const EmailActivationCodeService = require('../../../src/services/email-activation-code-service') +const AppHelper = require('../../../src/helpers/app-helper') +const ErrorMessages = require('../../../src/helpers/error-messages') describe('EmailActivationCode Service', () => { - def('subject', () => EmailActivationCodeService); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => EmailActivationCodeService) + def('sandbox', () => sinon.createSandbox()) - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.generateActivationCode()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const response = { - activationCode: "abcdefgwdwdwdwdwd", - expirationTime: new Date().getTime() + ((60 * 60 * 24 * 3) * 1000) - }; + activationCode: 'abcdefgwdwdwdwdwd', + expirationTime: new Date().getTime() + ((60 * 60 * 24 * 3) * 1000), + } - def('subject', () => $subject.generateActivationCode(transaction)); - def('generateStringResponse', () => response.activationCode); - def('findActivationCodeResponse', () => Promise.resolve()); + def('subject', () => $subject.generateActivationCode(transaction)) + def('generateStringResponse', () => response.activationCode) + def('findActivationCodeResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(AppHelper, 'generateRandomString').returns($generateStringResponse); - $sandbox.stub(EmailActivationCodeManager, 'getByActivationCode').returns($findActivationCodeResponse); - }); + $sandbox.stub(AppHelper, 'generateRandomString').returns($generateStringResponse) + $sandbox.stub(EmailActivationCodeManager, 'getByActivationCode').returns($findActivationCodeResponse) + }) it('calls AppHelper#generateRandomString() with correct args', async () => { - await $subject; - expect(AppHelper.generateRandomString).to.have.been.calledWith(16); - }); + await $subject + expect(AppHelper.generateRandomString).to.have.been.calledWith(16) + }) context('when AppHelper#generateRandomString() fails', () => { - def('generateStringResponse', () => error); + def('generateStringResponse', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.have.property('activationCode') }) - }); + }) context('when AppHelper#generateRandomString() succeeds', () => { it('calls EmailActivationCodeManager#getByActivationCode() with correct args', async () => { - await $subject; + await $subject expect(EmailActivationCodeManager.getByActivationCode).to.have.been.calledWith(response.activationCode, - transaction); - }); + transaction) + }) context('when EmailActivationCodeManager#getByActivationCode() fails', () => { - def('findActivationCodeResponse', () => Promise.reject(error)); + def('findActivationCodeResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when EmailActivationCodeManager#getByActivationCode() succeeds', () => { it('fulfills the promise', () => { @@ -66,114 +66,112 @@ describe('EmailActivationCode Service', () => { }) }) }) - }); + }) describe('.saveActivationCode()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - const userId = 15; + const userId = 15 const activationCodeData = { - activationCode: "abcdefgwdwdwdwdwd", - expirationTime: new Date().getTime() + ((60 * 60 * 24 * 3) * 1000) - }; + activationCode: 'abcdefgwdwdwdwdwd', + expirationTime: new Date().getTime() + ((60 * 60 * 24 * 3) * 1000), + } - def('subject', () => $subject.saveActivationCode(userId, activationCodeData, transaction)); - def('createActivationCodeResponse', () => Promise.resolve()); + def('subject', () => $subject.saveActivationCode(userId, activationCodeData, transaction)) + def('createActivationCodeResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(EmailActivationCodeManager, 'createActivationCode').returns($createActivationCodeResponse); - }); + $sandbox.stub(EmailActivationCodeManager, 'createActivationCode').returns($createActivationCodeResponse) + }) it('calls EmailActivationCodeManager#createActivationCode() with correct args', async () => { - await $subject; + await $subject expect(EmailActivationCodeManager.createActivationCode).to.have.been.calledWith(userId, - activationCodeData.activationCode, activationCodeData.expirationTime, transaction); - }); + activationCodeData.activationCode, activationCodeData.expirationTime, transaction) + }) context('when EmailActivationCodeManager#createActivationCode() fails', () => { - def('createActivationCodeResponse', () => Promise.reject(error)); + def('createActivationCodeResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(ErrorMessages.UNABLE_TO_CREATE_ACTIVATION_CODE); + return expect($subject).to.be.rejectedWith(ErrorMessages.UNABLE_TO_CREATE_ACTIVATION_CODE) }) - }); + }) context('when EmailActivationCodeManager#createActivationCode() succeeds', () => { it('fulfills the promise', () => { return expect($subject).to.eventually.deep.equal(undefined) }) }) - }); + }) describe('.verifyActivationCode()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - const activationCode = "abcdefgwdwdwdwdwd"; + const activationCode = 'abcdefgwdwdwdwdwd' - def('subject', () => $subject.verifyActivationCode(activationCode, transaction)); - def('verifyActivationCodeResponse', () => Promise.resolve()); + def('subject', () => $subject.verifyActivationCode(activationCode, transaction)) + def('verifyActivationCodeResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(EmailActivationCodeManager, 'verifyActivationCode').returns($verifyActivationCodeResponse); - }); + $sandbox.stub(EmailActivationCodeManager, 'verifyActivationCode').returns($verifyActivationCodeResponse) + }) it('calls EmailActivationCodeManager#verifyActivationCode() with correct args', async () => { - await $subject; - expect(EmailActivationCodeManager.verifyActivationCode).to.have.been.calledWith(activationCode, transaction); - }); + await $subject + expect(EmailActivationCodeManager.verifyActivationCode).to.have.been.calledWith(activationCode, transaction) + }) context('when EmailActivationCodeManager#verifyActivationCode() fails', () => { - def('verifyActivationCodeResponse', () => Promise.reject(error)); + def('verifyActivationCodeResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(ErrorMessages.UNABLE_TO_GET_ACTIVATION_CODE); + return expect($subject).to.be.rejectedWith(ErrorMessages.UNABLE_TO_GET_ACTIVATION_CODE) }) - }); + }) context('when EmailActivationCodeManager#verifyActivationCode() succeeds', () => { it('fulfills the promise', () => { return expect($subject).to.eventually.deep.equal(undefined) }) }) - }); + }) describe('.deleteActivationCode()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - const activationCode = "abcdefgwdwdwdwdwd"; + const activationCode = 'abcdefgwdwdwdwdwd' - def('subject', () => $subject.deleteActivationCode(activationCode, transaction)); - def('deleteActivationCodeResponse', () => Promise.resolve()); + def('subject', () => $subject.deleteActivationCode(activationCode, transaction)) + def('deleteActivationCodeResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(EmailActivationCodeManager, 'delete').returns($deleteActivationCodeResponse); - }); + $sandbox.stub(EmailActivationCodeManager, 'delete').returns($deleteActivationCodeResponse) + }) it('calls EmailActivationCodeManager#delete() with correct args', async () => { - await $subject; + await $subject expect(EmailActivationCodeManager.delete).to.have.been.calledWith({ - activationCode: activationCode - }, transaction); - }); + activationCode: activationCode, + }, transaction) + }) context('when EmailActivationCodeManager#delete() fails', () => { - def('deleteActivationCodeResponse', () => Promise.reject(error)); + def('deleteActivationCodeResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when EmailActivationCodeManager#delete() succeeds', () => { it('fulfills the promise', () => { return expect($subject).to.eventually.deep.equal(undefined) }) }) - }); - - -}); \ No newline at end of file + }) +}) diff --git a/test/src/services/flow-service.test.js b/test/src/services/flow-service.test.js index c85a6e7ac..9c049380f 100644 --- a/test/src/services/flow-service.test.js +++ b/test/src/services/flow-service.test.js @@ -1,124 +1,124 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); - -const FlowManager = require('../../../src/sequelize/managers/flow-manager'); -const FlowService = require('../../../src/services/flow-service'); -const AppHelper = require('../../../src/helpers/app-helper'); -const Validator = require('../../../src/schemas'); -const ChangeTrackingService = require('../../../src/services/change-tracking-service'); -const Sequelize = require('sequelize'); -const Op = Sequelize.Op; -const ErrorMessages = require('../../../src/helpers/error-messages'); +const {expect} = require('chai') +const sinon = require('sinon') + +const FlowManager = require('../../../src/sequelize/managers/flow-manager') +const FlowService = require('../../../src/services/flow-service') +const AppHelper = require('../../../src/helpers/app-helper') +const Validator = require('../../../src/schemas') +const ChangeTrackingService = require('../../../src/services/change-tracking-service') +const Sequelize = require('sequelize') +const Op = Sequelize.Op +const ErrorMessages = require('../../../src/helpers/error-messages') describe('Flow Service', () => { - def('subject', () => FlowService); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => FlowService) + def('sandbox', () => sinon.createSandbox()) - const isCLI = false; + const isCLI = false - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.createFlow()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const flowId = null; + const flowId = null const flowData = { name: 'testName', description: 'testDescription', - isActivated: false - }; + isActivated: false, + } const flowToCreate = { name: flowData.name, description: flowData.description, isActivated: flowData.isActivated, - userId: user.id - }; + userId: user.id, + } const response = { - id: 25 - }; + id: 25, + } - def('subject', () => $subject.createFlow(flowData, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('findFlowResponse', () => Promise.resolve()); - def('deleteUndefinedFieldsResponse', () => flowToCreate); - def('createFlowResponse', () => Promise.resolve(response)); + def('subject', () => $subject.createFlow(flowData, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('findFlowResponse', () => Promise.resolve()) + def('deleteUndefinedFieldsResponse', () => flowToCreate) + def('createFlowResponse', () => Promise.resolve(response)) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(FlowManager, 'findOne').returns($findFlowResponse); - $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse); - $sandbox.stub(FlowManager, 'create').returns($createFlowResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(FlowManager, 'findOne').returns($findFlowResponse) + $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse) + $sandbox.stub(FlowManager, 'create').returns($createFlowResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(flowData, Validator.schemas.flowCreate); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(flowData, Validator.schemas.flowCreate) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls FlowManager#findOne() with correct args', async () => { - await $subject; + await $subject const where = flowId ? {name: flowData.name, id: {[Op.ne]: flowId, userId: user.id}} - : {name: flowData.name, userId: user.id}; + : {name: flowData.name, userId: user.id} - expect(FlowManager.findOne).to.have.been.calledWith(where, transaction); - }); + expect(FlowManager.findOne).to.have.been.calledWith(where, transaction) + }) context('when FlowManager#findOne() fails', () => { - def('findFlowResponse', () => Promise.reject(error)); + def('findFlowResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowManager#findOne() succeeds', () => { it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; + await $subject - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(flowToCreate); - }); + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(flowToCreate) + }) context('when AppHelper#deleteUndefinedFields() fails', () => { - def('deleteUndefinedFieldsResponse', () => error); + def('deleteUndefinedFieldsResponse', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.have.property('id') }) - }); + }) context('when AppHelper#deleteUndefinedFields() succeeds', () => { it('calls FlowManager#create() with correct args', async () => { - await $subject; + await $subject - expect(FlowManager.create).to.have.been.calledWith(flowToCreate); - }); + expect(FlowManager.create).to.have.been.calledWith(flowToCreate) + }) context('when FlowManager#create() fails', () => { - def('createFlowResponse', () => error); + def('createFlowResponse', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.have.property('id') }) - }); + }) context('when FlowManager#create() succeeds', () => { it('fulfills the promise', () => { @@ -128,104 +128,104 @@ describe('Flow Service', () => { }) }) }) - }); + }) describe('.deleteFlow()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const flowId = 75; + const flowId = 75 const whereObj = { id: flowId, - userId: user.id - }; + userId: user.id, + } const flowWithMicroservices = { microservices: [ { - iofogUuid: 15 - } - ] - }; + iofogUuid: 15, + }, + ], + } - def('subject', () => $subject.deleteFlow(flowId, user, isCLI, transaction)); - def('deleteUndefinedFieldsResponse', () => whereObj); - def('findFlowMicroservicesResponse', () => Promise.resolve(flowWithMicroservices)); - def('updateChangeTrackingResponse', () => Promise.resolve()); - def('deleteFlowResponse', () => Promise.resolve()); + def('subject', () => $subject.deleteFlow(flowId, user, isCLI, transaction)) + def('deleteUndefinedFieldsResponse', () => whereObj) + def('findFlowMicroservicesResponse', () => Promise.resolve(flowWithMicroservices)) + def('updateChangeTrackingResponse', () => Promise.resolve()) + def('deleteFlowResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse); - $sandbox.stub(FlowManager, 'findFlowMicroservices').returns($findFlowMicroservicesResponse); - $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); - $sandbox.stub(FlowManager, 'delete').returns($deleteFlowResponse); - }); + $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse) + $sandbox.stub(FlowManager, 'findFlowMicroservices').returns($findFlowMicroservicesResponse) + $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse) + $sandbox.stub(FlowManager, 'delete').returns($deleteFlowResponse) + }) it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(whereObj); - }); + await $subject + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(whereObj) + }) context('when AppHelper#deleteUndefinedFields() fails', () => { - def('deleteUndefinedFieldsResponse', () => Promise.reject(error)); + def('deleteUndefinedFieldsResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#deleteUndefinedFields() succeeds', () => { it('calls FlowManager#findFlowMicroservices() with correct args', async () => { - await $subject; + await $subject expect(FlowManager.findFlowMicroservices).to.have.been.calledWith({ - id: flowId - }, transaction); - }); + id: flowId, + }, transaction) + }) context('when FlowManager#findFlowMicroservices() fails', () => { - def('findFlowMicroservicesResponse', () => Promise.reject(error)); + def('findFlowMicroservicesResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowManager#findFlowMicroservices() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(flowWithMicroservices.microservices[0].iofogUuid, - ChangeTrackingService.events.microserviceFull, transaction); - }); + ChangeTrackingService.events.microserviceFull, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('updateChangeTrackingResponse', () => error); + def('updateChangeTrackingResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('calls FlowManager#delete() with correct args', async () => { - await $subject; + await $subject - expect(FlowManager.delete).to.have.been.calledWith(whereObj, transaction); - }); + expect(FlowManager.delete).to.have.been.calledWith(whereObj, transaction) + }) context('when FlowManager#delete() fails', () => { - def('deleteFlowResponse', () => Promise.reject(error)); + def('deleteFlowResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowManager#delete() succeeds', () => { it('fulfills the promise', () => { @@ -235,175 +235,175 @@ describe('Flow Service', () => { }) }) }) - }); + }) describe('.updateFlow()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const flowId = 75; + const flowId = 75 const oldFlowData = { name: 'testName', description: 'testDescription', - isActivated: true - }; + isActivated: true, + } const flowData = { name: 'testName', description: 'testDescription', - isActivated: false - }; + isActivated: false, + } const flowWithMicroservices = { microservices: [ { - iofogUuid: 15 - } - ] - }; - - def('subject', () => $subject.updateFlow(flowData, flowId, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('findExcludedFlowResponse', () => Promise.resolve(oldFlowData)); - def('findFlowResponse', () => Promise.resolve()); - def('deleteUndefinedFieldsResponse', () => flowData); - def('updateFlowResponse', () => Promise.resolve()); - def('findFlowMicroservicesResponse', () => Promise.resolve(flowWithMicroservices)); - def('updateChangeTrackingResponse', () => Promise.resolve()); + iofogUuid: 15, + }, + ], + } + + def('subject', () => $subject.updateFlow(flowData, flowId, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('findExcludedFlowResponse', () => Promise.resolve(oldFlowData)) + def('findFlowResponse', () => Promise.resolve()) + def('deleteUndefinedFieldsResponse', () => flowData) + def('updateFlowResponse', () => Promise.resolve()) + def('findFlowMicroservicesResponse', () => Promise.resolve(flowWithMicroservices)) + def('updateChangeTrackingResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(FlowManager, 'findOneWithAttributes').returns($findExcludedFlowResponse); - $sandbox.stub(FlowManager, 'findOne').returns($findFlowResponse); - $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse); - $sandbox.stub(FlowManager, 'update').returns($updateFlowResponse); - $sandbox.stub(FlowManager, 'findFlowMicroservices').returns($findFlowMicroservicesResponse); - $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(FlowManager, 'findOneWithAttributes').returns($findExcludedFlowResponse) + $sandbox.stub(FlowManager, 'findOne').returns($findFlowResponse) + $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse) + $sandbox.stub(FlowManager, 'update').returns($updateFlowResponse) + $sandbox.stub(FlowManager, 'findFlowMicroservices').returns($findFlowMicroservicesResponse) + $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(flowData, Validator.schemas.flowUpdate); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(flowData, Validator.schemas.flowUpdate) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls FlowManager#findOneWithAttributes() with correct args', async () => { - await $subject; + await $subject const where = isCLI ? {id: flowId} - : {id: flowId, userId: user.id}; - const attributes = {exclude: ["created_at", "updated_at"]}; - expect(FlowManager.findOneWithAttributes).to.have.been.calledWith(where, attributes, transaction); - }); + : {id: flowId, userId: user.id} + const attributes = {exclude: ['created_at', 'updated_at']} + expect(FlowManager.findOneWithAttributes).to.have.been.calledWith(where, attributes, transaction) + }) context('when FlowManager#findOneWithAttributes() fails', () => { - def('findExcludedFlowResponse', () => Promise.reject(error)); + def('findExcludedFlowResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowManager#findOneWithAttributes() succeeds', () => { it('calls FlowManager#findOne() with correct args', async () => { - await $subject; + await $subject const where = flowId ? {name: flowData.name, userId: user.id, id: {[Op.ne]: flowId}} - : {name: flowData.name, userId: user.id}; - expect(FlowManager.findOne).to.have.been.calledWith(where, transaction); - }); + : {name: flowData.name, userId: user.id} + expect(FlowManager.findOne).to.have.been.calledWith(where, transaction) + }) context('when FlowManager#findOne() fails', () => { def('findFlowResponse', () => Promise.reject(AppHelper.formatMessage(ErrorMessages.DUPLICATE_NAME, - flowData.name))); + flowData.name))) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(AppHelper.formatMessage(ErrorMessages.DUPLICATE_NAME, - flowData.name)); + flowData.name)) }) - }); + }) context('when FlowManager#findOne() succeeds', () => { it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; + await $subject - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(flowData); - }); + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(flowData) + }) context('when AppHelper#deleteUndefinedFields() fails', () => { - def('deleteUndefinedFieldsResponse', () => Promise.reject(error)); + def('deleteUndefinedFieldsResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#deleteUndefinedFields() succeeds', () => { it('calls FlowManager#update() with correct args', async () => { - await $subject; + await $subject const where = isCLI ? {id: flowId} - : {id: flowId, userId: user.id}; - expect(FlowManager.update).to.have.been.calledWith(where, flowData, transaction); - }); + : {id: flowId, userId: user.id} + expect(FlowManager.update).to.have.been.calledWith(where, flowData, transaction) + }) context('when FlowManager#update() fails', () => { - def('updateFlowResponse', () => Promise.reject(error)); + def('updateFlowResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowManager#update() succeeds', () => { it('calls FlowManager#findFlowMicroservices() with correct args', async () => { - await $subject; + await $subject expect(FlowManager.findFlowMicroservices).to.have.been.calledWith({ - id: flowId - }, transaction); - }); + id: flowId, + }, transaction) + }) context('when FlowManager#findFlowMicroservices() fails', () => { - def('findFlowMicroservicesResponse', () => Promise.reject(error)); + def('findFlowMicroservicesResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowManager#findFlowMicroservices() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(flowWithMicroservices.microservices[0].iofogUuid, - ChangeTrackingService.events.microserviceFull, transaction); - }); + ChangeTrackingService.events.microserviceFull, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('updateChangeTrackingResponse', () => error); + def('updateChangeTrackingResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('fulfills the promise', () => { @@ -416,120 +416,119 @@ describe('Flow Service', () => { }) }) }) - }); + }) describe('.getUserFlows()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } const flow = { - userId: user.id - }; + userId: user.id, + } - def('subject', () => $subject.getUserFlows(user, isCLI, transaction)); - def('findExcludedFlowResponse', () => Promise.resolve()); + def('subject', () => $subject.getUserFlows(user, isCLI, transaction)) + def('findExcludedFlowResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(FlowManager, 'findAllWithAttributes').returns($findExcludedFlowResponse); - }); + $sandbox.stub(FlowManager, 'findAllWithAttributes').returns($findExcludedFlowResponse) + }) it('calls FlowManager#findAllWithAttributes() with correct args', async () => { - await $subject; - const attributes = {exclude: ["created_at", "updated_at"]}; - expect(FlowManager.findAllWithAttributes).to.have.been.calledWith(flow, attributes, transaction); - }); + await $subject + const attributes = {exclude: ['created_at', 'updated_at']} + expect(FlowManager.findAllWithAttributes).to.have.been.calledWith(flow, attributes, transaction) + }) context('when FlowManager#findAllWithAttributes() fails', () => { - def('findExcludedFlowResponse', () => Promise.reject(error)); + def('findExcludedFlowResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowManager#findAllWithAttributes() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.have.property('flows'); + return expect($subject).to.eventually.have.property('flows') }) }) - }); + }) describe('.getAllFlows()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - def('subject', () => $subject.getAllFlows(isCLI, transaction)); - def('findAllFlowsResponse', () => Promise.resolve()); + def('subject', () => $subject.getAllFlows(isCLI, transaction)) + def('findAllFlowsResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(FlowManager, 'findAllWithAttributes').returns($findAllFlowsResponse); - }); + $sandbox.stub(FlowManager, 'findAllWithAttributes').returns($findAllFlowsResponse) + }) it('calls FlowManager#findAllWithAttributes() with correct args', async () => { - await $subject; - const attributes = {exclude: ['created_at', 'updated_at']}; - expect(FlowManager.findAllWithAttributes).to.have.been.calledWith({}, attributes, transaction); - }); + await $subject + const attributes = {exclude: ['created_at', 'updated_at']} + expect(FlowManager.findAllWithAttributes).to.have.been.calledWith({}, attributes, transaction) + }) context('when FlowManager#findAllWithAttributes() fails', () => { - def('findAllFlowsResponse', () => Promise.reject(error)); + def('findAllFlowsResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowManager#findAllWithAttributes() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.have.property('flows'); + return expect($subject).to.eventually.have.property('flows') }) }) - }); + }) describe('.getFlow()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' - const flowId = 75; + const flowId = 75 const user = { - id: 15 - }; + id: 15, + } - def('subject', () => $subject.getFlow(flowId, user, isCLI, transaction)); - def('findFlowResponse', () => Promise.resolve({})); + def('subject', () => $subject.getFlow(flowId, user, isCLI, transaction)) + def('findFlowResponse', () => Promise.resolve({})) beforeEach(() => { - $sandbox.stub(FlowManager, 'findOneWithAttributes').returns($findFlowResponse); - }); + $sandbox.stub(FlowManager, 'findOneWithAttributes').returns($findFlowResponse) + }) it('calls FlowManager#findOneWithAttributes() with correct args', async () => { - await $subject; + await $subject const where = isCLI ? {id: flowId} - : {id: flowId, userId: user.id}; - const attributes = {exclude: ["created_at", "updated_at"]}; - expect(FlowManager.findOneWithAttributes).to.have.been.calledWith(where, attributes, transaction); - }); + : {id: flowId, userId: user.id} + const attributes = {exclude: ['created_at', 'updated_at']} + expect(FlowManager.findOneWithAttributes).to.have.been.calledWith(where, attributes, transaction) + }) context('when FlowManager#findOneWithAttributes() fails', () => { - def('findFlowResponse', () => Promise.reject(error)); + def('findFlowResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowManager#findOneWithAttributes() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.deep.equal({}); + return expect($subject).to.eventually.deep.equal({}) }) }) - }); - -}); \ No newline at end of file + }) +}) diff --git a/test/src/services/iofog-service.test.js b/test/src/services/iofog-service.test.js index 000979ce8..ef6c2415c 100644 --- a/test/src/services/iofog-service.test.js +++ b/test/src/services/iofog-service.test.js @@ -1,39 +1,39 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); - -const ioFogManager = require('../../../src/sequelize/managers/iofog-manager'); -const ioFogService = require('../../../src/services/iofog-service'); -const AppHelper = require('../../../src/helpers/app-helper'); -const Validator = require('../../../src/schemas'); -const ChangeTrackingService = require('../../../src/services/change-tracking-service'); -const CatalogService = require('../../../src/services/catalog-service'); -const MicroserviceManager = require('../../../src/sequelize/managers/microservice-manager'); -const ioFogProvisionKeyManager = require('../../../src/sequelize/managers/iofog-provision-key-manager'); -const ioFogVersionCommandManager = require('../../../src/sequelize/managers/iofog-version-command-manager'); -const HWInfoManager = require('../../../src/sequelize/managers/hw-info-manager'); -const USBInfoManager = require('../../../src/sequelize/managers/usb-info-manager'); +const {expect} = require('chai') +const sinon = require('sinon') + +const ioFogManager = require('../../../src/sequelize/managers/iofog-manager') +const ioFogService = require('../../../src/services/iofog-service') +const AppHelper = require('../../../src/helpers/app-helper') +const Validator = require('../../../src/schemas') +const ChangeTrackingService = require('../../../src/services/change-tracking-service') +const CatalogService = require('../../../src/services/catalog-service') +const MicroserviceManager = require('../../../src/sequelize/managers/microservice-manager') +const ioFogProvisionKeyManager = require('../../../src/sequelize/managers/iofog-provision-key-manager') +const ioFogVersionCommandManager = require('../../../src/sequelize/managers/iofog-version-command-manager') +const HWInfoManager = require('../../../src/sequelize/managers/hw-info-manager') +const USBInfoManager = require('../../../src/sequelize/managers/usb-info-manager') describe('ioFog Service', () => { - def('subject', () => ioFogService); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => ioFogService) + def('sandbox', () => sinon.createSandbox()) - const isCLI = false; + const isCLI = false - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.createFog()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const date = 155555555; + const date = 155555555 - const uuid = 'testUuid'; - const uuid2 = 'testUuid2'; - const uuid3 = 'testUuid3'; + const uuid = 'testUuid' + const uuid2 = 'testUuid2' + const uuid3 = 'testUuid3' const fogData = { name: 'testName', @@ -55,8 +55,8 @@ describe('ioFog Service', () => { bluetoothEnabled: true, watchdogEnabled: false, abstractedHardwareEnabled: true, - fogType: 1 - }; + fogType: 1, + } const createFogData = { uuid: uuid, @@ -81,14 +81,14 @@ describe('ioFog Service', () => { watchdogEnabled: fogData.watchdogEnabled, abstractedHardwareEnabled: fogData.abstractedHardwareEnabled, fogTypeId: fogData.fogType, - userId: user.id - }; + userId: user.id, + } const halItem = { - id: 10 - }; + id: 10, + } - const oldFog = null; + const oldFog = null const halMicroserviceData = { uuid: uuid2, name: `Hal for Fog ${createFogData.uuid}`, @@ -98,13 +98,13 @@ describe('ioFog Service', () => { rootHostAccess: true, logSize: 50, userId: oldFog ? oldFog.userId : user.id, - configLastUpdated: date - }; + configLastUpdated: date, + } const bluetoothItem = { - id: 10 - }; + id: 10, + } const bluetoothMicroserviceData = { uuid: uuid3, name: `Bluetooth for Fog ${createFogData.uuid}`, @@ -114,227 +114,226 @@ describe('ioFog Service', () => { rootHostAccess: true, logSize: 50, userId: oldFog ? oldFog.userId : user.id, - configLastUpdated: date - }; + configLastUpdated: date, + } const response = { - uuid: uuid - }; - - def('subject', () => $subject.createFog(fogData, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('generateRandomStringResponse', () => uuid); - def('generateRandomStringResponse2', () => uuid2); - def('generateRandomStringResponse3', () => uuid3); - def('deleteUndefinedFieldsResponse', () => createFogData); - def('createIoFogResponse', () => Promise.resolve(response)); - def('createChangeTrackingResponse', () => Promise.resolve()); - def('getHalCatalogItemResponse', () => Promise.resolve(halItem)); - def('createMicroserviceResponse', () => Promise.resolve()); - def('createMicroserviceResponse2', () => Promise.resolve()); - def('getBluetoothCatalogItemResponse', () => Promise.resolve(bluetoothItem)); - def('updateChangeTrackingResponse', () => Promise.resolve()); - - def('dateResponse', () => date); + uuid: uuid, + } + + def('subject', () => $subject.createFog(fogData, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('generateRandomStringResponse', () => uuid) + def('generateRandomStringResponse2', () => uuid2) + def('generateRandomStringResponse3', () => uuid3) + def('deleteUndefinedFieldsResponse', () => createFogData) + def('createIoFogResponse', () => Promise.resolve(response)) + def('createChangeTrackingResponse', () => Promise.resolve()) + def('getHalCatalogItemResponse', () => Promise.resolve(halItem)) + def('createMicroserviceResponse', () => Promise.resolve()) + def('createMicroserviceResponse2', () => Promise.resolve()) + def('getBluetoothCatalogItemResponse', () => Promise.resolve(bluetoothItem)) + def('updateChangeTrackingResponse', () => Promise.resolve()) + + def('dateResponse', () => date) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) $sandbox.stub(AppHelper, 'generateRandomString') - .onFirstCall().returns($generateRandomStringResponse) - .onSecondCall().returns($generateRandomStringResponse2) - .onThirdCall().returns($generateRandomStringResponse3); - $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse); - $sandbox.stub(ioFogManager, 'create').returns($createIoFogResponse); - $sandbox.stub(ChangeTrackingService, 'create').returns($createChangeTrackingResponse); - $sandbox.stub(CatalogService, 'getHalCatalogItem').returns($getHalCatalogItemResponse); + .onFirstCall().returns($generateRandomStringResponse) + .onSecondCall().returns($generateRandomStringResponse2) + .onThirdCall().returns($generateRandomStringResponse3) + $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse) + $sandbox.stub(ioFogManager, 'create').returns($createIoFogResponse) + $sandbox.stub(ChangeTrackingService, 'create').returns($createChangeTrackingResponse) + $sandbox.stub(CatalogService, 'getHalCatalogItem').returns($getHalCatalogItemResponse) $sandbox.stub(MicroserviceManager, 'create') - .onFirstCall().returns($createMicroserviceResponse) - .onSecondCall().returns($createMicroserviceResponse2); - $sandbox.stub(CatalogService, 'getBluetoothCatalogItem').returns($getBluetoothCatalogItemResponse); - $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); - - $sandbox.stub(Date, 'now').returns($dateResponse); + .onFirstCall().returns($createMicroserviceResponse) + .onSecondCall().returns($createMicroserviceResponse2) + $sandbox.stub(CatalogService, 'getBluetoothCatalogItem').returns($getBluetoothCatalogItemResponse) + $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse) - }); + $sandbox.stub(Date, 'now').returns($dateResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(fogData, Validator.schemas.iofogCreate); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(fogData, Validator.schemas.iofogCreate) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls AppHelper#generateRandomString() with correct args', async () => { - await $subject; - expect(AppHelper.generateRandomString).to.have.been.calledWith(32); - }); + await $subject + expect(AppHelper.generateRandomString).to.have.been.calledWith(32) + }) context('when AppHelper#generateRandomString() fails', () => { - def('generateRandomStringResponse', () => error); + def('generateRandomStringResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.have.property('uuid'); + return expect($subject).to.eventually.have.property('uuid') }) - }); + }) context('when AppHelper#generateRandomString() succeeds', () => { it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; + await $subject - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(createFogData); - }); + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(createFogData) + }) context('when AppHelper#deleteUndefinedFields() fails', () => { - def('deleteUndefinedFieldsResponse', () => error); + def('deleteUndefinedFieldsResponse', () => error) it(`fails with ${error}`, () => { return expect($subject).to.eventually.have.property('uuid') }) - }); + }) context('when AppHelper#deleteUndefinedFields() succeeds', () => { it('calls ioFogManager#create() with correct args', async () => { - await $subject; + await $subject - expect(ioFogManager.create).to.have.been.calledWith(createFogData); - }); + expect(ioFogManager.create).to.have.been.calledWith(createFogData) + }) context('when ioFogManager#create() fails', () => { - def('createIoFogResponse', () => Promise.reject(error)); + def('createIoFogResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#create() succeeds', () => { it('calls ChangeTrackingService#create() with correct args', async () => { - await $subject; + await $subject - expect(ChangeTrackingService.create).to.have.been.calledWith(uuid, transaction); - }); + expect(ChangeTrackingService.create).to.have.been.calledWith(uuid, transaction) + }) context('when ChangeTrackingService#create() fails', () => { - def('createIoFogResponse', () => Promise.reject(error)); + def('createIoFogResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#create() succeeds', () => { it('calls CatalogService#getHalCatalogItem() with correct args', async () => { - await $subject; + await $subject - expect(CatalogService.getHalCatalogItem).to.have.been.calledWith(transaction); - }); + expect(CatalogService.getHalCatalogItem).to.have.been.calledWith(transaction) + }) context('when CatalogService#getHalCatalogItem() fails', () => { - def('getHalCatalogItemResponse', () => Promise.reject(error)); + def('getHalCatalogItemResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogService#getHalCatalogItem() succeeds', () => { it('calls AppHelper#generateRandomString() with correct args', async () => { - await $subject; + await $subject - expect(AppHelper.generateRandomString).to.have.been.calledWith(32); - }); + expect(AppHelper.generateRandomString).to.have.been.calledWith(32) + }) context('when AppHelper#generateRandomString() fails', () => { - def('generateRandomStringResponse2', () => error); + def('generateRandomStringResponse2', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.have.property('uuid'); + return expect($subject).to.eventually.have.property('uuid') }) - }); + }) context('when AppHelper#generateRandomString() succeeds', () => { it('calls MicroserviceManager#create() with correct args', async () => { - await $subject; + await $subject - expect(MicroserviceManager.create).to.have.been.calledWith(halMicroserviceData, transaction); - }); + expect(MicroserviceManager.create).to.have.been.calledWith(halMicroserviceData, transaction) + }) context('when MicroserviceManager#create() fails', () => { - def('createMicroserviceResponse', () => Promise.reject(error)); + def('createMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#create() succeeds', () => { it('calls CatalogService#getBluetoothCatalogItem() with correct args', async () => { - await $subject; + await $subject - expect(CatalogService.getBluetoothCatalogItem).to.have.been.calledWith(transaction); - }); + expect(CatalogService.getBluetoothCatalogItem).to.have.been.calledWith(transaction) + }) context('when CatalogService#getBluetoothCatalogItem() fails', () => { - def('getBluetoothCatalogItemResponse', () => Promise.reject(error)); + def('getBluetoothCatalogItemResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogService#getBluetoothCatalogItem() succeeds', () => { it('calls AppHelper#generateRandomString() with correct args', async () => { - await $subject; + await $subject - expect(AppHelper.generateRandomString).to.have.been.calledWith(32); - }); + expect(AppHelper.generateRandomString).to.have.been.calledWith(32) + }) context('when AppHelper#generateRandomString() fails', () => { - def('generateRandomStringResponse3', () => Promise.reject(error)); + def('generateRandomStringResponse3', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.have.property('uuid'); + return expect($subject).to.eventually.have.property('uuid') }) - }); + }) context('when AppHelper#generateRandomString() succeeds', () => { it('calls MicroserviceManager#create() with correct args', async () => { - await $subject; + await $subject - expect(MicroserviceManager.create).to.have.been.calledWith(bluetoothMicroserviceData, transaction); - }); + expect(MicroserviceManager.create).to.have.been.calledWith(bluetoothMicroserviceData, transaction) + }) context('when MicroserviceManager#create() fails', () => { - def('createMicroserviceResponse2', () => Promise.reject(error)); + def('createMicroserviceResponse2', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#create() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(createFogData.uuid, - ChangeTrackingService.events.microserviceCommon, transaction); - }); + ChangeTrackingService.events.microserviceCommon, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('updateChangeTrackingResponse', () => Promise.reject(error)); + def('updateChangeTrackingResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('fulfills the promise', () => { @@ -352,21 +351,21 @@ describe('ioFog Service', () => { }) }) }) - }); + }) describe('.updateFog()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const date = 155555555; + const date = 155555555 - const uuid = 'testUuid'; - const uuid2 = 'testUuid2'; - const uuid3 = 'testUuid3'; + const uuid = 'testUuid' + const uuid2 = 'testUuid2' + const uuid3 = 'testUuid3' const fogData = { uuid: uuid, @@ -389,8 +388,8 @@ describe('ioFog Service', () => { bluetoothEnabled: true, watchdogEnabled: false, abstractedHardwareEnabled: true, - fogType: 1 - }; + fogType: 1, + } const oldFog = { uuid: uuid2, @@ -413,14 +412,14 @@ describe('ioFog Service', () => { bluetoothEnabled: false, watchdogEnabled: false, abstractedHardwareEnabled: false, - fogType: 1 - }; + fogType: 1, + } const queryFogData = isCLI ? {uuid: fogData.uuid} - : {uuid: fogData.uuid, userId: user.id}; + : {uuid: fogData.uuid, userId: user.id} - let updateFogData = { + const updateFogData = { name: fogData.name, location: fogData.location, latitude: fogData.latitude, @@ -442,11 +441,11 @@ describe('ioFog Service', () => { watchdogEnabled: fogData.watchdogEnabled, abstractedHardwareEnabled: fogData.abstractedHardwareEnabled, fogTypeId: fogData.fogType, - }; + } const halItem = { - id: 10 - }; + id: 10, + } const halMicroserviceData = { uuid: uuid2, name: `Hal for Fog ${fogData.uuid}`, @@ -456,13 +455,13 @@ describe('ioFog Service', () => { rootHostAccess: true, logSize: 50, userId: oldFog ? oldFog.userId : user.id, - configLastUpdated: date - }; + configLastUpdated: date, + } const bluetoothItem = { - id: 10 - }; + id: 10, + } const bluetoothMicroserviceData = { uuid: uuid3, name: `Bluetooth for Fog ${fogData.uuid}`, @@ -472,229 +471,229 @@ describe('ioFog Service', () => { rootHostAccess: true, logSize: 50, userId: oldFog ? oldFog.userId : user.id, - configLastUpdated: date - }; - - def('subject', () => $subject.updateFog(fogData, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('deleteUndefinedFieldsResponse', () => updateFogData); - def('findIoFogResponse', () => Promise.resolve(oldFog)); - def('updateIoFogResponse', () => Promise.resolve()); - def('updateChangeTrackingResponse', () => Promise.resolve()); - def('updateChangeTrackingResponse2', () => Promise.resolve()); - def('getHalCatalogItemResponse', () => Promise.resolve(halItem)); - def('generateRandomStringResponse', () => uuid2); - def('generateRandomStringResponse2', () => uuid3); - def('createMicroserviceResponse', () => Promise.resolve()); - def('createMicroserviceResponse2', () => Promise.resolve()); - def('getBluetoothCatalogItemResponse', () => Promise.resolve(bluetoothItem)); - - def('dateResponse', () => date); + configLastUpdated: date, + } + + def('subject', () => $subject.updateFog(fogData, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('deleteUndefinedFieldsResponse', () => updateFogData) + def('findIoFogResponse', () => Promise.resolve(oldFog)) + def('updateIoFogResponse', () => Promise.resolve()) + def('updateChangeTrackingResponse', () => Promise.resolve()) + def('updateChangeTrackingResponse2', () => Promise.resolve()) + def('getHalCatalogItemResponse', () => Promise.resolve(halItem)) + def('generateRandomStringResponse', () => uuid2) + def('generateRandomStringResponse2', () => uuid3) + def('createMicroserviceResponse', () => Promise.resolve()) + def('createMicroserviceResponse2', () => Promise.resolve()) + def('getBluetoothCatalogItemResponse', () => Promise.resolve(bluetoothItem)) + + def('dateResponse', () => date) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse); - $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse); - $sandbox.stub(ioFogManager, 'update').returns($updateIoFogResponse); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse) + $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse) + $sandbox.stub(ioFogManager, 'update').returns($updateIoFogResponse) $sandbox.stub(ChangeTrackingService, 'update') - .onFirstCall().returns($updateChangeTrackingResponse) - .onSecondCall().returns($updateChangeTrackingResponse2); - $sandbox.stub(CatalogService, 'getHalCatalogItem').returns($getHalCatalogItemResponse); + .onFirstCall().returns($updateChangeTrackingResponse) + .onSecondCall().returns($updateChangeTrackingResponse2) + $sandbox.stub(CatalogService, 'getHalCatalogItem').returns($getHalCatalogItemResponse) $sandbox.stub(AppHelper, 'generateRandomString') - .onFirstCall().returns($generateRandomStringResponse) - .onSecondCall().returns($generateRandomStringResponse2); + .onFirstCall().returns($generateRandomStringResponse) + .onSecondCall().returns($generateRandomStringResponse2) $sandbox.stub(MicroserviceManager, 'create') - .onFirstCall().returns($createMicroserviceResponse) - .onSecondCall().returns($createMicroserviceResponse2); - $sandbox.stub(CatalogService, 'getBluetoothCatalogItem').returns($getBluetoothCatalogItemResponse); + .onFirstCall().returns($createMicroserviceResponse) + .onSecondCall().returns($createMicroserviceResponse2) + $sandbox.stub(CatalogService, 'getBluetoothCatalogItem').returns($getBluetoothCatalogItemResponse) - $sandbox.stub(Date, 'now').returns($dateResponse); - }); + $sandbox.stub(Date, 'now').returns($dateResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(fogData, Validator.schemas.iofogUpdate); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(fogData, Validator.schemas.iofogUpdate) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; + await $subject - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(updateFogData); - }); + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(updateFogData) + }) context('when AppHelper#deleteUndefinedFields() fails', () => { - def('deleteUndefinedFieldsResponse', () => error); + def('deleteUndefinedFieldsResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#deleteUndefinedFields() succeeds', () => { it('calls ioFogManager#findOne() with correct args', async () => { - await $subject; + await $subject - expect(ioFogManager.findOne).to.have.been.calledWith(queryFogData, transaction); - }); + expect(ioFogManager.findOne).to.have.been.calledWith(queryFogData, transaction) + }) context('when ioFogManager#findOne() fails', () => { - def('findIoFogResponse', () => Promise.reject(error)); + def('findIoFogResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findOne() succeeds', () => { it('calls ioFogManager#update() with correct args', async () => { - await $subject; + await $subject expect(ioFogManager.update).to.have.been.calledWith(queryFogData, - updateFogData, transaction); - }); + updateFogData, transaction) + }) context('when ioFogManager#update() fails', () => { - def('updateIoFogResponse', () => Promise.reject(error)); + def('updateIoFogResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#update() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(uuid, - ChangeTrackingService.events.config, transaction); - }); + ChangeTrackingService.events.config, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('updateChangeTrackingResponse', () => Promise.reject(error)); + def('updateChangeTrackingResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('calls CatalogService#getHalCatalogItem() with correct args', async () => { - await $subject; + await $subject - expect(CatalogService.getHalCatalogItem).to.have.been.calledWith(transaction); - }); + expect(CatalogService.getHalCatalogItem).to.have.been.calledWith(transaction) + }) context('when CatalogService#getHalCatalogItem() fails', () => { - def('getHalCatalogItemResponse', () => Promise.reject(error)); + def('getHalCatalogItemResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogService#getHalCatalogItem() succeeds', () => { it('calls AppHelper#generateRandomString() with correct args', async () => { - await $subject; + await $subject - expect(AppHelper.generateRandomString).to.have.been.calledWith(32); - }); + expect(AppHelper.generateRandomString).to.have.been.calledWith(32) + }) context('when AppHelper#generateRandomString() fails', () => { - def('generateRandomStringResponse', () => error); + def('generateRandomStringResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#generateRandomString() succeeds', () => { it('calls MicroserviceManager#create() with correct args', async () => { - await $subject; + await $subject - expect(MicroserviceManager.create).to.have.been.calledWith(halMicroserviceData, transaction); - }); + expect(MicroserviceManager.create).to.have.been.calledWith(halMicroserviceData, transaction) + }) context('when MicroserviceManager#create() fails', () => { - def('createMicroserviceResponse', () => Promise.reject(error)); + def('createMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#create() succeeds', () => { it('calls CatalogService#getBluetoothCatalogItem() with correct args', async () => { - await $subject; + await $subject - expect(CatalogService.getBluetoothCatalogItem).to.have.been.calledWith(transaction); - }); + expect(CatalogService.getBluetoothCatalogItem).to.have.been.calledWith(transaction) + }) context('when CatalogService#getBluetoothCatalogItem() fails', () => { - def('getBluetoothCatalogItemResponse', () => Promise.reject(error)); + def('getBluetoothCatalogItemResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogService#getBluetoothCatalogItem() succeeds', () => { it('calls AppHelper#generateRandomString() with correct args', async () => { - await $subject; + await $subject - expect(AppHelper.generateRandomString).to.have.been.calledWith(32); - }); + expect(AppHelper.generateRandomString).to.have.been.calledWith(32) + }) context('when AppHelper#generateRandomString() fails', () => { - def('generateRandomStringResponse2', () => Promise.reject(error)); + def('generateRandomStringResponse2', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#generateRandomString() succeeds', () => { it('calls MicroserviceManager#create() with correct args', async () => { - await $subject; + await $subject - expect(MicroserviceManager.create).to.have.been.calledWith(bluetoothMicroserviceData, transaction); - }); + expect(MicroserviceManager.create).to.have.been.calledWith(bluetoothMicroserviceData, transaction) + }) context('when MicroserviceManager#create() fails', () => { - def('createMicroserviceResponse2', () => Promise.reject(error)); + def('createMicroserviceResponse2', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#create() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(fogData.uuid, - ChangeTrackingService.events.microserviceCommon, transaction); - }); + ChangeTrackingService.events.microserviceCommon, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('updateChangeTrackingResponse2', () => Promise.reject(error)); + def('updateChangeTrackingResponse2', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) }) @@ -708,23 +707,21 @@ describe('ioFog Service', () => { }) }) }) - }); + }) describe('.deleteFog()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const date = 155555555; - - const uuid = 'testUuid'; + const uuid = 'testUuid' const fogData = { - uuid: uuid - }; + uuid: uuid, + } const fog = { uuid: uuid, @@ -750,94 +747,88 @@ describe('ioFog Service', () => { bluetoothEnabled: false, watchdogEnabled: false, abstractedHardwareEnabled: false, - fogType: 1 - }; + fogType: 1, + } const queryFogData = isCLI ? {uuid: fogData.uuid} - : {uuid: fogData.uuid, userId: user.id}; + : {uuid: fogData.uuid, userId: user.id} - const toUpdate = { - daemonStatus: 'UNKNOWN', ipAddress: '0.0.0.0' - }; - - def('subject', () => $subject.deleteFog(fogData, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('findIoFogResponse', () => Promise.resolve(fog)); - def('updateChangeTrackingResponse', () => Promise.resolve()); + def('subject', () => $subject.deleteFog(fogData, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('findIoFogResponse', () => Promise.resolve(fog)) + def('updateChangeTrackingResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse); - $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse) + $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(fogData, Validator.schemas.iofogDelete); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(fogData, Validator.schemas.iofogDelete) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls ioFogManager#findOne() with correct args', async () => { - await $subject; + await $subject - expect(ioFogManager.findOne).to.have.been.calledWith(queryFogData, transaction); - }); + expect(ioFogManager.findOne).to.have.been.calledWith(queryFogData, transaction) + }) context('when ioFogManager#findOne() fails', () => { - def('findIoFogResponse', () => Promise.reject(error)); + def('findIoFogResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findOne() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject - expect(ChangeTrackingService.update).to.have.been.calledWith(uuid, ChangeTrackingService.events.deleteNode, transaction); - }); + expect(ChangeTrackingService.update).to.have.been.calledWith(uuid, ChangeTrackingService.events.deleteNode, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('updateChangeTrackingResponse', () => Promise.reject(error)); + def('updateChangeTrackingResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) }) }) - }); + }) describe('.getFog()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const date = 155555555; - - const uuid = 'testUuid'; + const uuid = 'testUuid' const fogData = { - uuid: uuid - }; + uuid: uuid, + } const fog = { uuid: uuid, @@ -863,16 +854,12 @@ describe('ioFog Service', () => { bluetoothEnabled: false, watchdogEnabled: false, abstractedHardwareEnabled: false, - fogType: 1 - }; + fogType: 1, + } const queryFogData = isCLI ? {uuid: fogData.uuid} - : {uuid: fogData.uuid, userId: user.id}; - - const toUpdate = { - daemonStatus: 'UNKNOWN', ipAddress: '0.0.0.0' - }; + : {uuid: fogData.uuid, userId: user.id} const fogResponse = { uuid: fog.uuid, @@ -922,65 +909,63 @@ describe('ioFog Service', () => { tunnel: fog.tunnel, watchdogEnabled: fog.watchdogEnabled, fogTypeId: fog.fogTypeId, - userId: fog.userId - }; + userId: fog.userId, + } - def('subject', () => $subject.getFog(fogData, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('findIoFogResponse', () => Promise.resolve(fog)); + def('subject', () => $subject.getFog(fogData, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('findIoFogResponse', () => Promise.resolve(fog)) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(fogData, Validator.schemas.iofogGet); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(fogData, Validator.schemas.iofogGet) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls ioFogManager#findOne() with correct args', async () => { - await $subject; + await $subject - expect(ioFogManager.findOne).to.have.been.calledWith(queryFogData, transaction); - }); + expect(ioFogManager.findOne).to.have.been.calledWith(queryFogData, transaction) + }) context('when ioFogManager#findOne() fails', () => { - def('findIoFogResponse', () => Promise.reject(error)); + def('findIoFogResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findOne() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.deep.equal(fogResponse); + return expect($subject).to.eventually.deep.equal(fogResponse) }) }) }) - }); + }) describe('.getFogList()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; - - const date = 155555555; + id: 15, + } - const uuid = 'testUuid'; + const uuid = 'testUuid' const fog = { uuid: uuid, @@ -1006,367 +991,363 @@ describe('ioFog Service', () => { bluetoothEnabled: false, watchdogEnabled: false, abstractedHardwareEnabled: false, - fogType: 1 - }; + fogType: 1, + } - const fogs = [fog]; + const fogs = [fog] const queryFogData = isCLI ? {} - : {userId: user.id}; + : {userId: user.id} - const toUpdate = { - daemonStatus: 'UNKNOWN', ipAddress: '0.0.0.0' - }; + const filters = [] - const filters = []; - - def('subject', () => $subject.getFogList(filters, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('findAllIoFogResponse', () => Promise.resolve(fogs)); + def('subject', () => $subject.getFogList(filters, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('findAllIoFogResponse', () => Promise.resolve(fogs)) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(ioFogManager, 'findAll').returns($findAllIoFogResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(ioFogManager, 'findAll').returns($findAllIoFogResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(filters, Validator.schemas.iofogFilters); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(filters, Validator.schemas.iofogFilters) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls ioFogManager#findAll() with correct args', async () => { - await $subject; + await $subject - expect(ioFogManager.findAll).to.have.been.calledWith(queryFogData, transaction); - }); + expect(ioFogManager.findAll).to.have.been.calledWith(queryFogData, transaction) + }) context('when ioFogManager#findAll() fails', () => { - def('findAllIoFogResponse', () => Promise.reject(error)); + def('findAllIoFogResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findAll() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.have.property('fogs'); + return expect($subject).to.eventually.have.property('fogs') }) }) }) - }); + }) describe('.generateProvisioningKey()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const uuid = 'testUuid'; + const uuid = 'testUuid' - const date = 155555555; + const date = 155555555 const fogData = { - uuid: uuid - }; + uuid: uuid, + } const queryFogData = isCLI ? {uuid: fogData.uuid} - : {uuid: fogData.uuid, userId: user.id}; + : {uuid: fogData.uuid, userId: user.id} - const provisionKey = 'tttttttt'; - const expirationTime = date + (20 * 60 * 1000); + const provisionKey = 'tttttttt' + const expirationTime = date + (20 * 60 * 1000) const newProvision = { iofogUuid: fogData.uuid, provisionKey: provisionKey, expirationTime: expirationTime, - }; + } - def('subject', () => $subject.generateProvisioningKey(fogData, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('generateRandomStringResponse', () => provisionKey); - def('findIoFogResponse', () => Promise.resolve({})); - def('updateOrCreateProvisionKeyResponse', () => Promise.resolve(newProvision)); + def('subject', () => $subject.generateProvisioningKey(fogData, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('generateRandomStringResponse', () => provisionKey) + def('findIoFogResponse', () => Promise.resolve({})) + def('updateOrCreateProvisionKeyResponse', () => Promise.resolve(newProvision)) - def('dateResponse', () => date); + def('dateResponse', () => date) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(AppHelper, 'generateRandomString').returns($generateRandomStringResponse); - $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse); - $sandbox.stub(ioFogProvisionKeyManager, 'updateOrCreate').returns($updateOrCreateProvisionKeyResponse); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(AppHelper, 'generateRandomString').returns($generateRandomStringResponse) + $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse) + $sandbox.stub(ioFogProvisionKeyManager, 'updateOrCreate').returns($updateOrCreateProvisionKeyResponse) - $sandbox.stub(Date.prototype, 'getTime').returns($dateResponse); - }); + $sandbox.stub(Date.prototype, 'getTime').returns($dateResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(fogData, Validator.schemas.iofogGenerateProvision); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(fogData, Validator.schemas.iofogGenerateProvision) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls AppHelper#generateRandomString() with correct args', async () => { - await $subject; + await $subject - expect(AppHelper.generateRandomString).to.have.been.calledWith(8); - }); + expect(AppHelper.generateRandomString).to.have.been.calledWith(8) + }) context('when AppHelper#generateRandomString() fails', () => { - def('generateRandomStringResponse', () => error); + def('generateRandomStringResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.have.property('key'); + return expect($subject).to.eventually.have.property('key') }) - }); + }) context('when AppHelper#generateRandomString() succeeds', () => { it('calls ioFogManager#findOne() with correct args', async () => { - await $subject; - expect(ioFogManager.findOne).to.have.been.calledWith(queryFogData, transaction); - }); + await $subject + expect(ioFogManager.findOne).to.have.been.calledWith(queryFogData, transaction) + }) context('when ioFogManager#findOne() fails', () => { - def('findIoFogResponse', () => Promise.reject(error)); + def('findIoFogResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findOne() succeeds', () => { it('calls ioFogProvisionKeyManager#updateOrCreate() with correct args', async () => { - await $subject; + await $subject expect(ioFogProvisionKeyManager.updateOrCreate).to.have.been.calledWith({ - iofogUuid: fogData.uuid - }, newProvision, transaction); - }); + iofogUuid: fogData.uuid, + }, newProvision, transaction) + }) context('when ioFogProvisionKeyManager#updateOrCreate() fails', () => { - def('updateOrCreateProvisionKeyResponse', () => Promise.reject(error)); + def('updateOrCreateProvisionKeyResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogProvisionKeyManager#updateOrCreate() succeeds', () => { it('fulfills the promise', () => { return expect($subject).to.eventually.deep.equal({ key: provisionKey, - expirationTime: expirationTime + expirationTime: expirationTime, }) }) }) }) }) }) - }); + }) describe('.setFogVersionCommand()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const uuid = 'testUuid'; + const uuid = 'testUuid' - const date = 155555555; + const date = 155555555 const fogVersionData = { uuid: uuid, - versionCommand: 'upgrade' - }; + versionCommand: 'upgrade', + } const queryFogData = isCLI ? {uuid: fogVersionData.uuid} - : {uuid: fogVersionData.uuid, userId: user.id}; + : {uuid: fogVersionData.uuid, userId: user.id} const ioFog = { uuid: uuid, isReadyToUpgrade: true, - isReadyToRollback: true - }; + isReadyToRollback: true, + } const newVersionCommand = { iofogUuid: fogVersionData.uuid, - versionCommand: fogVersionData.versionCommand - }; + versionCommand: fogVersionData.versionCommand, + } - const provisionKey = 'tttttttt'; - const expirationTime = date + (20 * 60 * 1000); + const provisionKey = 'tttttttt' + const expirationTime = date + (20 * 60 * 1000) const newProvision = { iofogUuid: uuid, provisionKey: provisionKey, expirationTime: expirationTime, - }; + } - def('subject', () => $subject.setFogVersionCommand(fogVersionData, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('findIoFogResponse', () => Promise.resolve(ioFog)); - def('generateRandomStringResponse', () => provisionKey); - def('updateOrCreateProvisionKeyResponse', () => Promise.resolve(newProvision)); - def('findIoFogVersionCommandResponse', () => Promise.resolve()); - def('updateChangeTrackingResponse', () => Promise.resolve()); + def('subject', () => $subject.setFogVersionCommand(fogVersionData, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('findIoFogResponse', () => Promise.resolve(ioFog)) + def('generateRandomStringResponse', () => provisionKey) + def('updateOrCreateProvisionKeyResponse', () => Promise.resolve(newProvision)) + def('findIoFogVersionCommandResponse', () => Promise.resolve()) + def('updateChangeTrackingResponse', () => Promise.resolve()) - def('dateResponse', () => date); + def('dateResponse', () => date) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse); - $sandbox.stub(AppHelper, 'generateRandomString').returns($generateRandomStringResponse); - $sandbox.stub(ioFogProvisionKeyManager, 'updateOrCreate').returns($updateOrCreateProvisionKeyResponse); - $sandbox.stub(ioFogVersionCommandManager, 'updateOrCreate').returns($findIoFogVersionCommandResponse); - $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); - - $sandbox.stub(Date.prototype, 'getTime').returns($dateResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse) + $sandbox.stub(AppHelper, 'generateRandomString').returns($generateRandomStringResponse) + $sandbox.stub(ioFogProvisionKeyManager, 'updateOrCreate').returns($updateOrCreateProvisionKeyResponse) + $sandbox.stub(ioFogVersionCommandManager, 'updateOrCreate').returns($findIoFogVersionCommandResponse) + $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse) + + $sandbox.stub(Date.prototype, 'getTime').returns($dateResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(fogVersionData, Validator.schemas.iofogSetVersionCommand); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(fogVersionData, Validator.schemas.iofogSetVersionCommand) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls ioFogManager#findOne() with correct args', async () => { - await $subject; - expect(ioFogManager.findOne).to.have.been.calledWith(queryFogData, transaction); - }); + await $subject + expect(ioFogManager.findOne).to.have.been.calledWith(queryFogData, transaction) + }) context('when ioFogManager#findOne() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findOne() succeeds', () => { it('calls Validator#validate() with correct args', async () => { - await $subject; + await $subject expect(Validator.validate).to.have.been.calledWith({ - uuid: fogVersionData.uuid - }, Validator.schemas.iofogGenerateProvision); - }); + uuid: fogVersionData.uuid, + }, Validator.schemas.iofogGenerateProvision) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls AppHelper#generateRandomString() with correct args', async () => { - await $subject; + await $subject - expect(AppHelper.generateRandomString).to.have.been.calledWith(8); - }); + expect(AppHelper.generateRandomString).to.have.been.calledWith(8) + }) context('when AppHelper#generateRandomString() fails', () => { - def('generateRandomStringResponse', () => error); + def('generateRandomStringResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#generateRandomString() succeeds', () => { it('calls ioFogManager#findOne() with correct args', async () => { - await $subject; - expect(ioFogManager.findOne).to.have.been.calledWith(queryFogData, transaction); - }); + await $subject + expect(ioFogManager.findOne).to.have.been.calledWith(queryFogData, transaction) + }) context('when ioFogManager#findOne() fails', () => { - def('findIoFogResponse', () => Promise.reject(error)); + def('findIoFogResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findOne() succeeds', () => { it('calls ioFogProvisionKeyManager#updateOrCreate() with correct args', async () => { - await $subject; + await $subject expect(ioFogProvisionKeyManager.updateOrCreate).to.have.been.calledWith({ - iofogUuid: uuid - }, newProvision, transaction); - }); + iofogUuid: uuid, + }, newProvision, transaction) + }) context('when ioFogProvisionKeyManager#updateOrCreate() fails', () => { - def('updateOrCreateProvisionKeyResponse', () => Promise.reject(error)); + def('updateOrCreateProvisionKeyResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogProvisionKeyManager#updateOrCreate() succeeds', () => { it('calls ioFogVersionCommandManager#updateOrCreate() with correct args', async () => { - await $subject; + await $subject expect(ioFogVersionCommandManager.updateOrCreate).to.have.been.calledWith({ - iofogUuid: fogVersionData.uuid - }, newVersionCommand, transaction); - }); + iofogUuid: fogVersionData.uuid, + }, newVersionCommand, transaction) + }) context('when ioFogVersionCommandManager#updateOrCreate() fails', () => { - def('updateOrCreateProvisionKeyResponse', () => Promise.reject(error)); + def('updateOrCreateProvisionKeyResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogVersionCommandManager#updateOrCreate() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(fogVersionData.uuid, - ChangeTrackingService.events.version, transaction); - }); + ChangeTrackingService.events.version, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('updateOrCreateProvisionKeyResponse', () => Promise.reject(error)); + def('updateOrCreateProvisionKeyResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) }) @@ -1376,257 +1357,255 @@ describe('ioFog Service', () => { }) }) }) - }); + }) describe('.setFogRebootCommand()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const uuid = 'testUuid'; + const uuid = 'testUuid' - const date = 155555555; + const date = 155555555 const fogData = { - uuid: uuid - }; + uuid: uuid, + } const queryFogData = isCLI ? {uuid: fogData.uuid} - : {uuid: fogData.uuid, userId: user.id}; + : {uuid: fogData.uuid, userId: user.id} - def('subject', () => $subject.setFogRebootCommand(fogData, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('findIoFogResponse', () => Promise.resolve({})); - def('updateChangeTrackingResponse', () => Promise.resolve()); + def('subject', () => $subject.setFogRebootCommand(fogData, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('findIoFogResponse', () => Promise.resolve({})) + def('updateChangeTrackingResponse', () => Promise.resolve()) - def('dateResponse', () => date); + def('dateResponse', () => date) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse); - $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse) + $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(fogData, Validator.schemas.iofogReboot); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(fogData, Validator.schemas.iofogReboot) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls ioFogManager#findOne() with correct args', async () => { - await $subject; - expect(ioFogManager.findOne).to.have.been.calledWith(queryFogData, transaction); - }); + await $subject + expect(ioFogManager.findOne).to.have.been.calledWith(queryFogData, transaction) + }) context('when ioFogManager#findOne() fails', () => { - def('findIoFogResponse', () => Promise.reject(error)); + def('findIoFogResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findOne() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(fogData.uuid, - ChangeTrackingService.events.reboot, transaction); - }); + ChangeTrackingService.events.reboot, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('updateChangeTrackingResponse', () => Promise.reject(error)); + def('updateChangeTrackingResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) }) }) - }); + }) describe('.getHalHardwareInfo()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const uuid = 'testUuid'; + const uuid = 'testUuid' - const date = 155555555; + const date = 155555555 const uuidObj = { - uuid: uuid - }; + uuid: uuid, + } - def('subject', () => $subject.getHalHardwareInfo(uuidObj, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('findIoFogResponse', () => Promise.resolve({})); - def('findHalHardwareResponse', () => Promise.resolve()); + def('subject', () => $subject.getHalHardwareInfo(uuidObj, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('findIoFogResponse', () => Promise.resolve({})) + def('findHalHardwareResponse', () => Promise.resolve()) - def('dateResponse', () => date); + def('dateResponse', () => date) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse); - $sandbox.stub(HWInfoManager, 'findOne').returns($findHalHardwareResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse) + $sandbox.stub(HWInfoManager, 'findOne').returns($findHalHardwareResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(uuidObj, Validator.schemas.halGet); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(uuidObj, Validator.schemas.halGet) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls ioFogManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(ioFogManager.findOne).to.have.been.calledWith({ - uuid: uuidObj.uuid - }, transaction); - }); + uuid: uuidObj.uuid, + }, transaction) + }) context('when ioFogManager#findOne() fails', () => { - def('findIoFogResponse', () => Promise.reject(error)); + def('findIoFogResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findOne() succeeds', () => { it('calls HWInfoManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(HWInfoManager.findOne).to.have.been.calledWith({ - iofogUuid: uuidObj.uuid - }, transaction); - }); + iofogUuid: uuidObj.uuid, + }, transaction) + }) context('when HWInfoManager#findOne() fails', () => { - def('findHalHardwareResponse', () => Promise.reject(error)); + def('findHalHardwareResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when HWInfoManager#findOne() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) }) }) - }); + }) describe('.getHalUsbInfo()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const uuid = 'testUuid'; + const uuid = 'testUuid' - const date = 155555555; + const date = 155555555 const uuidObj = { - uuid: uuid - }; + uuid: uuid, + } - def('subject', () => $subject.getHalUsbInfo(uuidObj, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('findIoFogResponse', () => Promise.resolve({})); - def('findHalUsbResponse', () => Promise.resolve()); + def('subject', () => $subject.getHalUsbInfo(uuidObj, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('findIoFogResponse', () => Promise.resolve({})) + def('findHalUsbResponse', () => Promise.resolve()) - def('dateResponse', () => date); + def('dateResponse', () => date) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse); - $sandbox.stub(USBInfoManager, 'findOne').returns($findHalUsbResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(ioFogManager, 'findOne').returns($findIoFogResponse) + $sandbox.stub(USBInfoManager, 'findOne').returns($findHalUsbResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(uuidObj, Validator.schemas.halGet); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(uuidObj, Validator.schemas.halGet) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls ioFogManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(ioFogManager.findOne).to.have.been.calledWith({ - uuid: uuidObj.uuid - }, transaction); - }); + uuid: uuidObj.uuid, + }, transaction) + }) context('when ioFogManager#findOne() fails', () => { - def('findIoFogResponse', () => Promise.reject(error)); + def('findIoFogResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findOne() succeeds', () => { it('calls USBInfoManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(USBInfoManager.findOne).to.have.been.calledWith({ - iofogUuid: uuidObj.uuid - }, transaction); - }); + iofogUuid: uuidObj.uuid, + }, transaction) + }) context('when USBInfoManager#findOne() fails', () => { - def('findHalUsbResponse', () => Promise.reject(error)); + def('findHalUsbResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when USBInfoManager#findOne() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) }) }) - }); - - -}); \ No newline at end of file + }) +}) diff --git a/test/src/services/microservices-service.test.js b/test/src/services/microservices-service.test.js index 0cc587160..c1dce1bcc 100644 --- a/test/src/services/microservices-service.test.js +++ b/test/src/services/microservices-service.test.js @@ -1,164 +1,164 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); - -const MicroserviceManager = require('../../../src/sequelize/managers/microservice-manager'); -const MicroservicesService = require('../../../src/services/microservices-service'); -const AppHelper = require('../../../src/helpers/app-helper'); -const Validator = require('../../../src/schemas'); -const ChangeTrackingService = require('../../../src/services/change-tracking-service'); -const CatalogService = require('../../../src/services/catalog-service'); -const FlowService = require('../../../src/services/flow-service'); -const ioFogService = require('../../../src/services/iofog-service'); -const MicroservicePortManager = require('../../../src/sequelize/managers/microservice-port-manager'); -const VolumeMappingManager = require('../../../src/sequelize/managers/volume-mapping-manager'); -const MicroserviceStatusManager = require('../../../src/sequelize/managers/microservice-status-manager'); -const RoutingManager = require('../../../src/sequelize/managers/routing-manager'); -const Op = require('sequelize').Op; +const {expect} = require('chai') +const sinon = require('sinon') + +const MicroserviceManager = require('../../../src/sequelize/managers/microservice-manager') +const MicroservicesService = require('../../../src/services/microservices-service') +const AppHelper = require('../../../src/helpers/app-helper') +const Validator = require('../../../src/schemas') +const ChangeTrackingService = require('../../../src/services/change-tracking-service') +const CatalogService = require('../../../src/services/catalog-service') +const FlowService = require('../../../src/services/flow-service') +const ioFogService = require('../../../src/services/iofog-service') +const MicroservicePortManager = require('../../../src/sequelize/managers/microservice-port-manager') +const VolumeMappingManager = require('../../../src/sequelize/managers/volume-mapping-manager') +const MicroserviceStatusManager = require('../../../src/sequelize/managers/microservice-status-manager') +const RoutingManager = require('../../../src/sequelize/managers/routing-manager') +const Op = require('sequelize').Op describe('Microservices Service', () => { - def('subject', () => MicroservicesService); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => MicroservicesService) + def('sandbox', () => sinon.createSandbox()) - const isCLI = true; + const isCLI = true - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.listMicroservices()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const flowId = 10; + const flowId = 10 const response = [ { - uuid: 'testUuid' - } - ]; + uuid: 'testUuid', + }, + ] - def('subject', () => $subject.listMicroservices(flowId, user, isCLI, transaction)); - def('findMicroservicesResponse', () => Promise.resolve(response)); - def('findPortMappingsResponse', () => Promise.resolve([])); - def('findVolumeMappingsResponse', () => Promise.resolve([])); - def('findRoutesResponse', () => Promise.resolve([])); + def('subject', () => $subject.listMicroservices(flowId, user, isCLI, transaction)) + def('findMicroservicesResponse', () => Promise.resolve(response)) + def('findPortMappingsResponse', () => Promise.resolve([])) + def('findVolumeMappingsResponse', () => Promise.resolve([])) + def('findRoutesResponse', () => Promise.resolve([])) beforeEach(() => { - $sandbox.stub(MicroserviceManager, 'findAllExcludeFields').returns($findMicroservicesResponse); - $sandbox.stub(MicroservicePortManager, 'findAll').returns($findPortMappingsResponse); - $sandbox.stub(VolumeMappingManager, 'findAll').returns($findVolumeMappingsResponse); - $sandbox.stub(RoutingManager, 'findAll').returns($findRoutesResponse); - }); + $sandbox.stub(MicroserviceManager, 'findAllExcludeFields').returns($findMicroservicesResponse) + $sandbox.stub(MicroservicePortManager, 'findAll').returns($findPortMappingsResponse) + $sandbox.stub(VolumeMappingManager, 'findAll').returns($findVolumeMappingsResponse) + $sandbox.stub(RoutingManager, 'findAll').returns($findRoutesResponse) + }) it('calls MicroserviceManager#findAllExcludeFields() with correct args', async () => { - await $subject; - const where = isCLI ? {delete: false} : {flowId: flowId, delete: false}; + await $subject + const where = isCLI ? {delete: false} : {flowId: flowId, delete: false} - expect(MicroserviceManager.findAllExcludeFields).to.have.been.calledWith(where, transaction); - }); + expect(MicroserviceManager.findAllExcludeFields).to.have.been.calledWith(where, transaction) + }) context('when MicroserviceManager#findAllExcludeFields() fails', () => { - def('findMicroservicesResponse', () => Promise.reject(error)); + def('findMicroservicesResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#findAllExcludeFields() succeeds', () => { it('fulfills the promise', () => { return expect($subject).to.eventually.have.property('microservices') }) }) - }); + }) describe('.getMicroservice()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const microserviceUuid = 'testMicroserviceUuid'; + const microserviceUuid = 'testMicroserviceUuid' const response = { dataValues: { - uuid: 'testUuid' - } - }; + uuid: 'testUuid', + }, + } - def('subject', () => $subject.getMicroservice(microserviceUuid, user, isCLI, transaction)); - def('findMicroserviceResponse', () => Promise.resolve(response)); - def('findPortMappingsResponse', () => Promise.resolve([])); - def('findVolumeMappingsResponse', () => Promise.resolve([])); - def('findRoutesResponse', () => Promise.resolve([])); + def('subject', () => $subject.getMicroservice(microserviceUuid, user, isCLI, transaction)) + def('findMicroserviceResponse', () => Promise.resolve(response)) + def('findPortMappingsResponse', () => Promise.resolve([])) + def('findVolumeMappingsResponse', () => Promise.resolve([])) + def('findRoutesResponse', () => Promise.resolve([])) beforeEach(() => { - $sandbox.stub(MicroserviceManager, 'findOneExcludeFields').returns($findMicroserviceResponse); - $sandbox.stub(MicroservicePortManager, 'findAll').returns($findPortMappingsResponse); - $sandbox.stub(VolumeMappingManager, 'findAll').returns($findVolumeMappingsResponse); - $sandbox.stub(RoutingManager, 'findAll').returns($findRoutesResponse); - }); + $sandbox.stub(MicroserviceManager, 'findOneExcludeFields').returns($findMicroserviceResponse) + $sandbox.stub(MicroservicePortManager, 'findAll').returns($findPortMappingsResponse) + $sandbox.stub(VolumeMappingManager, 'findAll').returns($findVolumeMappingsResponse) + $sandbox.stub(RoutingManager, 'findAll').returns($findRoutesResponse) + }) it('calls MicroserviceManager#findOneExcludeFields() with correct args', async () => { - await $subject; + await $subject expect(MicroserviceManager.findOneExcludeFields).to.have.been.calledWith({ - uuid: microserviceUuid, delete: false - }, transaction); - }); + uuid: microserviceUuid, delete: false, + }, transaction) + }) context('when MicroserviceManager#findOneExcludeFields() fails', () => { - def('findMicroserviceResponse', () => Promise.reject(error)); + def('findMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#findOneExcludeFields() succeeds', () => { it('fulfills the promise', () => { return expect($subject).to.eventually.have.property('uuid') }) }) - }); + }) describe('.createMicroservice()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } const microserviceData = { - "name": "name2", - "config": "string", - "catalogItemId": 15, - "flowId": 16, - "iofogUuid": 'testIofogUuid', - "rootHostAccess": true, - "logSize": 0, - "volumeMappings": [ + 'name': 'name2', + 'config': 'string', + 'catalogItemId': 15, + 'flowId': 16, + 'iofogUuid': 'testIofogUuid', + 'rootHostAccess': true, + 'logSize': 0, + 'volumeMappings': [ { - "hostDestination": "/var/dest", - "containerDestination": "/var/dest", - "accessMode": "rw" - } + 'hostDestination': '/var/dest', + 'containerDestination': '/var/dest', + 'accessMode': 'rw', + }, ], - "ports": [ + 'ports': [ { - "internal": 1, - "external": 1, - "publicMode": false - } + 'internal': 1, + 'external': 1, + 'publicMode': false, + }, ], - "routes": [] - }; + 'routes': [], + } - const newMicroserviceUuid = 'newMicroserviceUuid'; + const newMicroserviceUuid = 'newMicroserviceUuid' const newMicroservice = { uuid: newMicroserviceUuid, name: microserviceData.name, @@ -168,23 +168,23 @@ describe('Microservices Service', () => { iofogUuid: microserviceData.iofogUuid, rootHostAccess: microserviceData.rootHostAccess, logSize: microserviceData.logLimit, - userId: user.id - }; + userId: user.id, + } - const item = {}; + const item = {} const portMappingData = { - "internal": 1, - "external": 1, - "publicMode": false - }; + 'internal': 1, + 'external': 1, + 'publicMode': false, + } - const mappings = []; + const mappings = [] for (const volumeMapping of microserviceData.volumeMappings) { - const mapping = Object.assign({}, volumeMapping); - mapping.microserviceUuid = microserviceData.uuid; - mappings.push(mapping); + const mapping = Object.assign({}, volumeMapping) + mapping.microserviceUuid = microserviceData.uuid + mappings.push(mapping) } const mappingData = { @@ -192,331 +192,331 @@ describe('Microservices Service', () => { portInternal: portMappingData.internal, portExternal: portMappingData.external, userId: microserviceData.userId, - microserviceUuid: microserviceData.uuid - }; - - def('subject', () => $subject.createMicroservice(microserviceData, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('validatorResponse2', () => Promise.resolve(true)); - def('generateRandomStringResponse', () => newMicroserviceUuid); - def('deleteUndefinedFieldsResponse', () => newMicroservice); - def('findMicroserviceResponse', () => Promise.resolve()); - def('findMicroserviceResponse2', () => Promise.resolve(microserviceData)); - def('getCatalogItemResponse', () => Promise.resolve()); - def('getFlowResponse', () => Promise.resolve()); - def('getIoFogResponse', () => Promise.resolve()); - def('createMicroserviceResponse', () => Promise.resolve(microserviceData)); - def('findMicroservicePortResponse', () => Promise.resolve()); - def('createMicroservicePortResponse', () => Promise.resolve()); - def('updateMicroserviceResponse', () => Promise.resolve()); - def('updateChangeTrackingResponse', () => Promise.resolve()); - def('createVolumeMappingResponse', () => Promise.resolve()); - def('createMicroserviceStatusResponse', () => Promise.resolve()); + microserviceUuid: microserviceData.uuid, + } + + def('subject', () => $subject.createMicroservice(microserviceData, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('validatorResponse2', () => Promise.resolve(true)) + def('generateRandomStringResponse', () => newMicroserviceUuid) + def('deleteUndefinedFieldsResponse', () => newMicroservice) + def('findMicroserviceResponse', () => Promise.resolve()) + def('findMicroserviceResponse2', () => Promise.resolve(microserviceData)) + def('getCatalogItemResponse', () => Promise.resolve()) + def('getFlowResponse', () => Promise.resolve()) + def('getIoFogResponse', () => Promise.resolve()) + def('createMicroserviceResponse', () => Promise.resolve(microserviceData)) + def('findMicroservicePortResponse', () => Promise.resolve()) + def('createMicroservicePortResponse', () => Promise.resolve()) + def('updateMicroserviceResponse', () => Promise.resolve()) + def('updateChangeTrackingResponse', () => Promise.resolve()) + def('createVolumeMappingResponse', () => Promise.resolve()) + def('createMicroserviceStatusResponse', () => Promise.resolve()) beforeEach(() => { $sandbox.stub(Validator, 'validate') - .onFirstCall().returns($validatorResponse) - .onSecondCall().returns($validatorResponse2); - $sandbox.stub(AppHelper, 'generateRandomString').returns($generateRandomStringResponse); - $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse); + .onFirstCall().returns($validatorResponse) + .onSecondCall().returns($validatorResponse2) + $sandbox.stub(AppHelper, 'generateRandomString').returns($generateRandomStringResponse) + $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse) $sandbox.stub(MicroserviceManager, 'findOne') - .onFirstCall().returns($findMicroserviceResponse) - .onSecondCall().returns($findMicroserviceResponse2); - $sandbox.stub(CatalogService, 'getCatalogItem').returns($getCatalogItemResponse); - $sandbox.stub(FlowService, 'getFlow').returns($getFlowResponse); - $sandbox.stub(ioFogService, 'getFog').returns($getIoFogResponse); - $sandbox.stub(MicroserviceManager, 'create').returns($createMicroserviceResponse); - $sandbox.stub(MicroservicePortManager, 'findOne').returns($findMicroservicePortResponse); - $sandbox.stub(MicroservicePortManager, 'create').returns($createMicroservicePortResponse); - $sandbox.stub(MicroserviceManager, 'update').returns($updateMicroserviceResponse); - $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); - $sandbox.stub(VolumeMappingManager, 'bulkCreate').returns($createVolumeMappingResponse); - $sandbox.stub(MicroserviceStatusManager, 'create').returns($createMicroserviceStatusResponse); - }); + .onFirstCall().returns($findMicroserviceResponse) + .onSecondCall().returns($findMicroserviceResponse2) + $sandbox.stub(CatalogService, 'getCatalogItem').returns($getCatalogItemResponse) + $sandbox.stub(FlowService, 'getFlow').returns($getFlowResponse) + $sandbox.stub(ioFogService, 'getFog').returns($getIoFogResponse) + $sandbox.stub(MicroserviceManager, 'create').returns($createMicroserviceResponse) + $sandbox.stub(MicroservicePortManager, 'findOne').returns($findMicroservicePortResponse) + $sandbox.stub(MicroservicePortManager, 'create').returns($createMicroservicePortResponse) + $sandbox.stub(MicroserviceManager, 'update').returns($updateMicroserviceResponse) + $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse) + $sandbox.stub(VolumeMappingManager, 'bulkCreate').returns($createVolumeMappingResponse) + $sandbox.stub(MicroserviceStatusManager, 'create').returns($createMicroserviceStatusResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; + await $subject expect(Validator.validate).to.have.been.calledWith(microserviceData, - Validator.schemas.microserviceCreate); - }); + Validator.schemas.microserviceCreate) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls AppHelper#generateRandomString() with correct args', async () => { - await $subject; - expect(AppHelper.generateRandomString).to.have.been.calledWith(32); - }); + await $subject + expect(AppHelper.generateRandomString).to.have.been.calledWith(32) + }) context('when AppHelper#generateRandomString() fails', () => { - def('generateRandomStringResponse', () => error); + def('generateRandomStringResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.have.property('uuid'); + return expect($subject).to.eventually.have.property('uuid') }) - }); + }) context('when AppHelper#generateRandomString() succeeds', () => { it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(newMicroservice); - }); + await $subject + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(newMicroservice) + }) context('when AppHelper#deleteUndefinedFields() fails', () => { - const err = 'Invalid microservice UUID \'undefined\''; - def('deleteUndefinedFieldsResponse', () => Promise.reject(err)); + const err = 'Invalid microservice UUID \'undefined\'' + def('deleteUndefinedFieldsResponse', () => Promise.reject(err)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(err); + return expect($subject).to.be.rejectedWith(err) }) - }); + }) context('when AppHelper#deleteUndefinedFields() succeeds', () => { it('calls MicroserviceManager#findOne() with correct args', async () => { - await $subject; + await $subject const where = item.id ? { name: microserviceData.name, uuid: {[Op.ne]: item.id}, - userId: user.id + userId: user.id, } : { name: microserviceData.name, - userId: user.id - }; - expect(MicroserviceManager.findOne).to.have.been.calledWith(where, transaction); - }); + userId: user.id, + } + expect(MicroserviceManager.findOne).to.have.been.calledWith(where, transaction) + }) context('when MicroserviceManager#findOne() fails', () => { - def('findMicroserviceResponse', () => Promise.reject(error)); + def('findMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#findOne() succeeds', () => { it('calls CatalogService#getCatalogItem() with correct args', async () => { - await $subject; + await $subject expect(CatalogService.getCatalogItem).to.have.been.calledWith(newMicroservice.catalogItemId, - user, isCLI, transaction); - }); + user, isCLI, transaction) + }) context('when CatalogService#getCatalogItem() fails', () => { - def('getCatalogItemResponse', () => Promise.reject(error)); + def('getCatalogItemResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when CatalogService#getCatalogItem() succeeds', () => { it('calls FlowService#getFlow() with correct args', async () => { - await $subject; + await $subject expect(FlowService.getFlow).to.have.been.calledWith(newMicroservice.flowId, - user, isCLI, transaction); - }); + user, isCLI, transaction) + }) context('when FlowService#getFlow() fails', () => { - def('getFlowResponse', () => Promise.reject(error)); + def('getFlowResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when FlowService#getFlow() succeeds', () => { it('calls IoFogService#getFog() with correct args', async () => { - await $subject; + await $subject expect(ioFogService.getFog).to.have.been.calledWith({ - uuid: newMicroservice.iofogUuid - }, user, isCLI, transaction); - }); + uuid: newMicroservice.iofogUuid, + }, user, isCLI, transaction) + }) context('when IoFogService#getFog() fails', () => { - def('getIoFogResponse', () => Promise.reject(error)); + def('getIoFogResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when IoFogService#getFog() succeeds', () => { it('calls MicroserviceManager#create() with correct args', async () => { - await $subject; + await $subject expect(MicroserviceManager.create).to.have.been.calledWith(newMicroservice, - transaction); - }); + transaction) + }) context('when MicroserviceManager#create() fails', () => { - def('getIoFogResponse', () => Promise.reject(error)); + def('getIoFogResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#create() succeeds', () => { it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(portMappingData, Validator.schemas.portsCreate); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(portMappingData, Validator.schemas.portsCreate) + }) context('when Validator#validate() fails', () => { - def('validatorResponse2', () => Promise.reject(error)); + def('validatorResponse2', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls MicroserviceManager#findOne() with correct args', async () => { - await $subject; + await $subject const where = isCLI ? {uuid: microserviceData.uuid} - : {uuid: microserviceData.uuid, userId: user.id}; - expect(MicroserviceManager.findOne).to.have.been.calledWith(where, transaction); - }); + : {uuid: microserviceData.uuid, userId: user.id} + expect(MicroserviceManager.findOne).to.have.been.calledWith(where, transaction) + }) context('when MicroserviceManager#findOne() fails', () => { - def('findMicroserviceResponse', () => Promise.reject(error)); + def('findMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#findOne() succeeds', () => { it('calls MicroservicePortManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(MicroservicePortManager.findOne).to.have.been.calledWith({ microserviceUuid: microserviceData.uuid, [Op.or]: [ { - portInternal: portMappingData.internal + portInternal: portMappingData.internal, }, { - portExternal: portMappingData.external - } - ] - }, transaction); - }); + portExternal: portMappingData.external, + }, + ], + }, transaction) + }) context('when MicroservicePortManager#findOne() fails', () => { - def('findMicroservicePortResponse', () => Promise.reject(error)); + def('findMicroservicePortResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicePortManager#findOne() succeeds', () => { it('calls MicroservicePortManager#create() with correct args', async () => { - await $subject; - expect(MicroservicePortManager.create).to.have.been.calledWith(mappingData, transaction); - }); + await $subject + expect(MicroservicePortManager.create).to.have.been.calledWith(mappingData, transaction) + }) context('when MicroservicePortManager#create() fails', () => { - def('createMicroservicePortResponse', () => Promise.reject(error)); + def('createMicroservicePortResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicePortManager#create() succeeds', () => { it('calls MicroserviceManager#update() with correct args', async () => { - await $subject; + await $subject const updateRebuildMs = { - rebuild: true - }; + rebuild: true, + } expect(MicroserviceManager.update).to.have.been.calledWith({ - uuid: microserviceData.uuid - }, updateRebuildMs, transaction); - }); + uuid: microserviceData.uuid, + }, updateRebuildMs, transaction) + }) context('when MicroserviceManager#update() fails', () => { - def('updateMicroserviceResponse', () => Promise.reject(error)); + def('updateMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#update() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(microserviceData.iofogUuid, - ChangeTrackingService.events.microserviceConfig, transaction); - }); + ChangeTrackingService.events.microserviceConfig, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('updateChangeTrackingResponse', () => Promise.reject(error)); + def('updateChangeTrackingResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('calls VolumeMappingManager#bulkCreate() with correct args', async () => { - await $subject; + await $subject expect(VolumeMappingManager.bulkCreate).to.have.been.calledWith(mappings, - transaction); - }); + transaction) + }) context('when VolumeMappingManager#bulkCreate() fails', () => { - def('createVolumeMappingResponse', () => Promise.reject(error)); + def('createVolumeMappingResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when VolumeMappingManager#bulkCreate() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(microserviceData.iofogUuid, - ChangeTrackingService.events.microserviceList, transaction); - }); + ChangeTrackingService.events.microserviceList, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('updateChangeTrackingResponse', () => Promise.reject(error)); + def('updateChangeTrackingResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('calls MicroserviceStatusManager#create() with correct args', async () => { - await $subject; + await $subject expect(MicroserviceStatusManager.create).to.have.been.calledWith({ - microserviceUuid: microserviceData.uuid - }, transaction); - }); + microserviceUuid: microserviceData.uuid, + }, transaction) + }) context('when MicroserviceStatusManager#create() fails', () => { - def('createMicroserviceStatusResponse', () => Promise.reject(error)); + def('createMicroserviceStatusResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceStatusManager#create() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.have.property('uuid'); + return expect($subject).to.eventually.have.property('uuid') }) }) }) @@ -535,807 +535,807 @@ describe('Microservices Service', () => { }) }) }) - }); -// -// describe('.updateMicroservice()', () => { -// const transaction = {}; -// const error = 'Error!'; -// -// const user = { -// id: 15 -// }; -// -// const microserviceUuid = 'testMicroserviceUuid'; -// -// const query = isCLI -// ? -// { -// uuid: microserviceUuid -// } -// : -// { -// uuid: microserviceUuid, -// userId: user.id -// }; -// -// const microserviceData = { -// "name": "name2", -// "config": "string", -// "catalogItemId": 15, -// "flowId": 16, -// "iofogUuid": 'testIofogUuid', -// "rootHostAccess": true, -// "logSize": 0, -// "volumeMappings": [ -// { -// "hostDestination": "/var/dest", -// "containerDestination": "/var/dest", -// "accessMode": "rw" -// } -// ], -// "ports": [ -// { -// "internal": 1, -// "external": 1, -// "publicMode": false -// } -// ], -// "routes": [] -// }; -// -// const microserviceToUpdate = { -// name: microserviceData.name, -// config: microserviceData.config, -// rebuild: microserviceData.rebuild, -// iofogUuid: microserviceData.iofogUuid, -// rootHostAccess: microserviceData.rootHostAccess, -// logSize: microserviceData.logLimit, -// volumeMappings: microserviceData.volumeMappings -// }; -// -// const newMicroserviceUuid = 'newMicroserviceUuid'; -// const newMicroservice = { -// uuid: newMicroserviceUuid, -// name: microserviceData.name, -// config: microserviceData.config, -// catalogItemId: microserviceData.catalogItemId, -// flowId: microserviceData.flowId, -// iofogUuid: microserviceData.iofogUuid, -// rootHostAccess: microserviceData.rootHostAccess, -// logSize: microserviceData.logLimit, -// userId: user.id -// }; -// -// const item = {}; -// -// const portMappingData = -// { -// "internal": 1, -// "external": 1, -// "publicMode": false -// }; -// -// const mappings = []; -// for (const volumeMapping of microserviceData.volumeMappings) { -// const mapping = Object.assign({}, volumeMapping); -// mapping.microserviceUuid = microserviceData.uuid; -// mappings.push(mapping); -// } -// -// const mappingData = { -// isPublic: false, -// portInternal: portMappingData.internal, -// portExternal: portMappingData.external, -// userId: microserviceData.userId, -// microserviceUuid: microserviceData.uuid -// }; -// -// def('subject', () => $subject.updateMicroservice(microserviceUuid, microserviceData, user, isCLI, transaction)); -// def('validatorResponse', () => Promise.resolve(true)); -// def('deleteUndefinedFieldsResponse', () => newMicroservice); -// def('findMicroserviceResponse', () => Promise.resolve()); -// def('findMicroserviceResponse2', () => Promise.resolve(microserviceData)); -// def('getIoFogResponse', () => Promise.resolve()); -// def('updateMicroserviceResponse', () => Promise.resolve()); -// def('updateVolumeMappingResponse', () => Promise.resolve()); -// // TODO -// -// def('updateChangeTrackingResponse', () => Promise.resolve()); -// def('updateChangeTrackingResponse2', () => Promise.resolve()); -// def('updateChangeTrackingResponse3', () => Promise.resolve()); -// -// beforeEach(() => { -// $sandbox.stub(Validator, 'validate').returns($validatorResponse); -// $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse); -// $sandbox.stub(MicroserviceManager, 'findOne') -// .onFirstCall().returns($findMicroserviceResponse) -// .onSecondCall().returns($findMicroserviceResponse2); -// $sandbox.stub(ioFogService, 'getFog').returns($getIoFogResponse); -// $sandbox.stub(MicroserviceManager, 'update').returns($updateMicroserviceResponse); -// $sandbox.stub(VolumeMappingManager, 'update').returns($updateVolumeMappingResponse); -// $sandbox.stub(RoutingManager, 'findAll').returns($findAllRoutesResponse); -// -// // TODO -// // delete route endpoint -// // create route endpoint -// $sandbox.stub(ChangeTrackingService, 'update') -// .onFirstCall().returns($updateChangeTrackingResponse) -// .onSecondCall().returns($updateChangeTrackingResponse2) -// .onThirdCall().returns($updateChangeTrackingResponse3); -// }); -// -// it('calls Validator#validate() with correct args', async () => { -// await $subject; -// expect(Validator.validate).to.have.been.calledWith(microserviceData, -// Validator.schemas.microserviceCreate); -// }); -// -// context('when Validator#validate() fails', () => { -// def('validatorResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when Validator#validate() succeeds', () => { -// it('calls AppHelper#generateRandomString() with correct args', async () => { -// await $subject; -// expect(AppHelper.generateRandomString).to.have.been.calledWith(32); -// }); -// -// context('when AppHelper#generateRandomString() fails', () => { -// def('generateRandomStringResponse', () => error); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.eventually.have.property('uuid'); -// }) -// }); -// -// context('when AppHelper#generateRandomString() succeeds', () => { -// it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { -// await $subject; -// expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(newMicroservice); -// }); -// -// context('when AppHelper#deleteUndefinedFields() fails', () => { -// const err = 'Invalid microservice UUID \'undefined\''; -// def('deleteUndefinedFieldsResponse', () => Promise.reject(err)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(err); -// }) -// }); -// -// context('when AppHelper#deleteUndefinedFields() succeeds', () => { -// it('calls MicroserviceManager#findOne() with correct args', async () => { -// await $subject; -// const where = item.id -// ? -// { -// name: microserviceData.name, -// uuid: {[Op.ne]: item.id}, -// userId: user.id -// } -// : -// { -// name: microserviceData.name, -// userId: user.id -// }; -// expect(MicroserviceManager.findOne).to.have.been.calledWith(where, transaction); -// }); -// -// context('when MicroserviceManager#findOne() fails', () => { -// def('findMicroserviceResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when MicroserviceManager#findOne() succeeds', () => { -// it('calls CatalogService#getCatalogItem() with correct args', async () => { -// await $subject; -// expect(CatalogService.getCatalogItem).to.have.been.calledWith(newMicroservice.catalogItemId, -// user, isCLI, transaction); -// }); -// -// context('when CatalogService#getCatalogItem() fails', () => { -// def('getCatalogItemResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when CatalogService#getCatalogItem() succeeds', () => { -// it('calls FlowService#getFlow() with correct args', async () => { -// await $subject; -// expect(FlowService.getFlow).to.have.been.calledWith(newMicroservice.flowId, -// user, isCLI, transaction); -// }); -// -// context('when FlowService#getFlow() fails', () => { -// def('getFlowResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when FlowService#getFlow() succeeds', () => { -// it('calls IoFogService#getFog() with correct args', async () => { -// await $subject; -// expect(ioFogService.getFog).to.have.been.calledWith({ -// uuid: newMicroservice.iofogUuid -// }, user, isCLI, transaction); -// }); -// -// context('when IoFogService#getFog() fails', () => { -// def('getIoFogResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when IoFogService#getFog() succeeds', () => { -// it('calls MicroserviceManager#create() with correct args', async () => { -// await $subject; -// expect(MicroserviceManager.create).to.have.been.calledWith(newMicroservice, -// transaction); -// }); -// -// context('when MicroserviceManager#create() fails', () => { -// def('getIoFogResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when MicroserviceManager#create() succeeds', () => { -// it('calls Validator#validate() with correct args', async () => { -// await $subject; -// expect(Validator.validate).to.have.been.calledWith(portMappingData, Validator.schemas.portsCreate); -// }); -// -// context('when Validator#validate() fails', () => { -// def('validatorResponse2', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when Validator#validate() succeeds', () => { -// it('calls MicroserviceManager#findOne() with correct args', async () => { -// await $subject; -// const where = isCLI -// ? {uuid: microserviceData.uuid} -// : {uuid: microserviceData.uuid, userId: user.id}; -// expect(MicroserviceManager.findOne).to.have.been.calledWith(where, transaction); -// }); -// -// context('when MicroserviceManager#findOne() fails', () => { -// def('findMicroserviceResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when MicroserviceManager#findOne() succeeds', () => { -// it('calls MicroservicePortManager#findOne() with correct args', async () => { -// await $subject; -// expect(MicroservicePortManager.findOne).to.have.been.calledWith({ -// microserviceUuid: microserviceData.uuid, -// [Op.or]: -// [ -// { -// portInternal: portMappingData.internal -// }, -// { -// portExternal: portMappingData.external -// } -// ] -// }, transaction); -// }); -// -// context('when MicroservicePortManager#findOne() fails', () => { -// def('findMicroservicePortResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when MicroservicePortManager#findOne() succeeds', () => { -// it('calls MicroservicePortManager#create() with correct args', async () => { -// await $subject; -// expect(MicroservicePortManager.create).to.have.been.calledWith(mappingData, transaction); -// }); -// -// context('when MicroservicePortManager#create() fails', () => { -// def('createMicroservicePortResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when MicroservicePortManager#create() succeeds', () => { -// it('calls MicroserviceManager#update() with correct args', async () => { -// await $subject; -// const updateRebuildMs = { -// rebuild: true -// }; -// expect(MicroserviceManager.update).to.have.been.calledWith({ -// uuid: microserviceData.uuid -// }, updateRebuildMs, transaction); -// }); -// -// context('when MicroserviceManager#update() fails', () => { -// def('updateMicroserviceResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when MicroserviceManager#update() succeeds', () => { -// it('calls ChangeTrackingService#update() with correct args', async () => { -// await $subject; -// expect(ChangeTrackingService.update).to.have.been.calledWith(microserviceData.iofogUuid, -// ChangeTrackingService.events.microserviceConfig, transaction); -// }); -// -// context('when ChangeTrackingService#update() fails', () => { -// def('updateChangeTrackingResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when ChangeTrackingService#update() succeeds', () => { -// it('calls VolumeMappingManager#bulkCreate() with correct args', async () => { -// await $subject; -// expect(VolumeMappingManager.bulkCreate).to.have.been.calledWith(mappings, -// transaction); -// }); -// -// context('when VolumeMappingManager#bulkCreate() fails', () => { -// def('createVolumeMappingResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when VolumeMappingManager#bulkCreate() succeeds', () => { -// it('calls ChangeTrackingService#update() with correct args', async () => { -// await $subject; -// expect(ChangeTrackingService.update).to.have.been.calledWith(microserviceData.iofogUuid, -// ChangeTrackingService.events.microserviceList, transaction); -// }); -// -// context('when ChangeTrackingService#update() fails', () => { -// def('updateChangeTrackingResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when ChangeTrackingService#update() succeeds', () => { -// it('calls MicroserviceStatusManager#create() with correct args', async () => { -// await $subject; -// expect(MicroserviceStatusManager.create).to.have.been.calledWith({ -// microserviceUuid: microserviceData.uuid -// }, transaction); -// }); -// -// context('when MicroserviceStatusManager#create() fails', () => { -// def('createMicroserviceStatusResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when MicroserviceStatusManager#create() succeeds', () => { -// it('fulfills the promise', () => { -// return expect($subject).to.eventually.have.property('uuid'); -// }) -// }) -// }) -// }) -// }) -// }) -// }) -// }) -// }) -// }) -// }) -// }) -// }) -// }) -// }) -// }) -// }) -// }) -// }); -// -// -// describe('.deleteMicroservice()', () => { -// const transaction = {}; -// const error = 'Error!'; -// -// const user = { -// id: 15 -// }; -// -// const microserviceUuid = 'testMicroserviceUuid'; -// -// const microserviceData = { -// "name": "name2", -// "config": "string", -// "catalogItemId": 15, -// "flowId": 16, -// "iofogUuid": 'testIofogUuid', -// "rootHostAccess": true, -// "logSize": 0, -// "volumeMappings": [ -// { -// "hostDestination": "/var/dest", -// "containerDestination": "/var/dest", -// "accessMode": "rw" -// } -// ], -// "ports": [ -// { -// "internal": 1, -// "external": 1, -// "publicMode": false -// } -// ], -// "routes": [] -// }; -// -// const portMappingData = [ -// { -// "internal": 1, -// "external": 1, -// "publicMode": false -// } -// ]; -// -// -// const where = isCLI -// ? -// { -// uuid: microserviceUuid, -// } -// : -// { -// uuid: microserviceUuid, -// userId: user.id -// }; -// -// const mappingData = { -// isPublic: false, -// portInternal: portMappingData.internal, -// portExternal: portMappingData.external, -// userId: microserviceData.userId, -// microserviceUuid: microserviceData.uuid -// }; -// -// def('subject', () => $subject.deleteMicroservice(microserviceUuid, microserviceData, user, isCLI, transaction)); -// def('findMicroserviceResponse', () => Promise.resolve(microserviceData)); -// def('findMicroservicePortResponse', () => Promise.resolve()); -// def('deleteMicroservicePortResponse', () => Promise.resolve()); -// def('updateMicroserviceResponse', () => Promise.resolve()); -// def('updateChangeTrackingResponse', () => Promise.resolve()); -// -// beforeEach(() => { -// $sandbox.stub(MicroserviceManager, 'findOneWithStatusAndCategory').returns($findMicroserviceResponse); -// $sandbox.stub(MicroservicePortManager, 'findAll').returns($findMicroservicePortResponse); -// $sandbox.stub(MicroservicePortManager, 'delete').returns($deleteMicroservicePortResponse); -// $sandbox.stub(MicroserviceManager, 'update').returns($updateMicroserviceResponse); -// $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); -// }); -// -// it('calls Validator#validate() with correct args', async () => { -// await $subject; -// expect(Validator.validate).to.have.been.calledWith(portMappingData, Validator.schemas.portsCreate); -// }); -// -// context('when Validator#validate() fails', () => { -// def('validatorResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when Validator#validate() succeeds', () => { -// it('calls MicroserviceManager#findOne() with correct args', async () => { -// await $subject; -// expect(MicroserviceManager.findOne).to.have.been.calledWith(where, transaction); -// }); -// -// context('when MicroserviceManager#findOne() fails', () => { -// def('findMicroserviceResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when MicroserviceManager#findOne() succeeds', () => { -// it('calls MicroservicePortManager#findOne() with correct args', async () => { -// await $subject; -// expect(MicroservicePortManager.findOne).to.have.been.calledWith({ -// microserviceUuid: microserviceUuid, -// [Op.or]: -// [ -// { -// portInternal: portMappingData.internal -// }, -// { -// portExternal: portMappingData.external -// } -// ] -// }, transaction); -// }); -// -// context('when MicroservicePortManager#findOne() fails', () => { -// def('findMicroservicePortResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when MicroservicePortManager#findOne() succeeds', () => { -// it('calls MicroservicePortManager#create() with correct args', async () => { -// await $subject; -// expect(MicroservicePortManager.create).to.have.been.calledWith(mappingData, transaction); -// }); -// -// context('when MicroservicePortManager#create() fails', () => { -// def('createMicroservicePortResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when MicroservicePortManager#create() succeeds', () => { -// it('calls MicroserviceManager#update() with correct args', async () => { -// await $subject; -// const updateRebuildMs = { -// rebuild: true -// }; -// expect(MicroserviceManager.update).to.have.been.calledWith({ -// uuid: microserviceData.uuid -// }, updateRebuildMs, transaction); -// }); -// -// context('when MicroserviceManager#update() fails', () => { -// def('updateMicroserviceResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when MicroserviceManager#update() succeeds', () => { -// it('calls ChangeTrackingService#update() with correct args', async () => { -// await $subject; -// expect(ChangeTrackingService.update).to.have.been.calledWith(microserviceData.iofogUuid, -// ChangeTrackingService.events.microserviceConfig, transaction); -// }); -// -// context('when ChangeTrackingService#update() fails', () => { -// def('updateChangeTrackingResponse', () => Promise.reject(error)); -// -// it(`fails with ${error}`, () => { -// return expect($subject).to.be.rejectedWith(error); -// }) -// }); -// -// context('when ChangeTrackingService#update() succeeds', () => { -// it('fulfills the promise', () => { -// return expect($subject).eventually.equals(undefined); -// }) -// }) -// }) -// }) -// }) -// }) -// }) -// }); -// -// }); -// + }) + // + // describe('.updateMicroservice()', () => { + // const transaction = {}; + // const error = 'Error!'; + // + // const user = { + // id: 15 + // }; + // + // const microserviceUuid = 'testMicroserviceUuid'; + // + // const query = isCLI + // ? + // { + // uuid: microserviceUuid + // } + // : + // { + // uuid: microserviceUuid, + // userId: user.id + // }; + // + // const microserviceData = { + // "name": "name2", + // "config": "string", + // "catalogItemId": 15, + // "flowId": 16, + // "iofogUuid": 'testIofogUuid', + // "rootHostAccess": true, + // "logSize": 0, + // "volumeMappings": [ + // { + // "hostDestination": "/var/dest", + // "containerDestination": "/var/dest", + // "accessMode": "rw" + // } + // ], + // "ports": [ + // { + // "internal": 1, + // "external": 1, + // "publicMode": false + // } + // ], + // "routes": [] + // }; + // + // const microserviceToUpdate = { + // name: microserviceData.name, + // config: microserviceData.config, + // rebuild: microserviceData.rebuild, + // iofogUuid: microserviceData.iofogUuid, + // rootHostAccess: microserviceData.rootHostAccess, + // logSize: microserviceData.logLimit, + // volumeMappings: microserviceData.volumeMappings + // }; + // + // const newMicroserviceUuid = 'newMicroserviceUuid'; + // const newMicroservice = { + // uuid: newMicroserviceUuid, + // name: microserviceData.name, + // config: microserviceData.config, + // catalogItemId: microserviceData.catalogItemId, + // flowId: microserviceData.flowId, + // iofogUuid: microserviceData.iofogUuid, + // rootHostAccess: microserviceData.rootHostAccess, + // logSize: microserviceData.logLimit, + // userId: user.id + // }; + // + // const item = {}; + // + // const portMappingData = + // { + // "internal": 1, + // "external": 1, + // "publicMode": false + // }; + // + // const mappings = []; + // for (const volumeMapping of microserviceData.volumeMappings) { + // const mapping = Object.assign({}, volumeMapping); + // mapping.microserviceUuid = microserviceData.uuid; + // mappings.push(mapping); + // } + // + // const mappingData = { + // isPublic: false, + // portInternal: portMappingData.internal, + // portExternal: portMappingData.external, + // userId: microserviceData.userId, + // microserviceUuid: microserviceData.uuid + // }; + // + // def('subject', () => $subject.updateMicroservice(microserviceUuid, microserviceData, user, isCLI, transaction)); + // def('validatorResponse', () => Promise.resolve(true)); + // def('deleteUndefinedFieldsResponse', () => newMicroservice); + // def('findMicroserviceResponse', () => Promise.resolve()); + // def('findMicroserviceResponse2', () => Promise.resolve(microserviceData)); + // def('getIoFogResponse', () => Promise.resolve()); + // def('updateMicroserviceResponse', () => Promise.resolve()); + // def('updateVolumeMappingResponse', () => Promise.resolve()); + // // TODO + // + // def('updateChangeTrackingResponse', () => Promise.resolve()); + // def('updateChangeTrackingResponse2', () => Promise.resolve()); + // def('updateChangeTrackingResponse3', () => Promise.resolve()); + // + // beforeEach(() => { + // $sandbox.stub(Validator, 'validate').returns($validatorResponse); + // $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse); + // $sandbox.stub(MicroserviceManager, 'findOne') + // .onFirstCall().returns($findMicroserviceResponse) + // .onSecondCall().returns($findMicroserviceResponse2); + // $sandbox.stub(ioFogService, 'getFog').returns($getIoFogResponse); + // $sandbox.stub(MicroserviceManager, 'update').returns($updateMicroserviceResponse); + // $sandbox.stub(VolumeMappingManager, 'update').returns($updateVolumeMappingResponse); + // $sandbox.stub(RoutingManager, 'findAll').returns($findAllRoutesResponse); + // + // // TODO + // // delete route endpoint + // // create route endpoint + // $sandbox.stub(ChangeTrackingService, 'update') + // .onFirstCall().returns($updateChangeTrackingResponse) + // .onSecondCall().returns($updateChangeTrackingResponse2) + // .onThirdCall().returns($updateChangeTrackingResponse3); + // }); + // + // it('calls Validator#validate() with correct args', async () => { + // await $subject; + // expect(Validator.validate).to.have.been.calledWith(microserviceData, + // Validator.schemas.microserviceCreate); + // }); + // + // context('when Validator#validate() fails', () => { + // def('validatorResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when Validator#validate() succeeds', () => { + // it('calls AppHelper#generateRandomString() with correct args', async () => { + // await $subject; + // expect(AppHelper.generateRandomString).to.have.been.calledWith(32); + // }); + // + // context('when AppHelper#generateRandomString() fails', () => { + // def('generateRandomStringResponse', () => error); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.eventually.have.property('uuid'); + // }) + // }); + // + // context('when AppHelper#generateRandomString() succeeds', () => { + // it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { + // await $subject; + // expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(newMicroservice); + // }); + // + // context('when AppHelper#deleteUndefinedFields() fails', () => { + // const err = 'Invalid microservice UUID \'undefined\''; + // def('deleteUndefinedFieldsResponse', () => Promise.reject(err)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(err); + // }) + // }); + // + // context('when AppHelper#deleteUndefinedFields() succeeds', () => { + // it('calls MicroserviceManager#findOne() with correct args', async () => { + // await $subject; + // const where = item.id + // ? + // { + // name: microserviceData.name, + // uuid: {[Op.ne]: item.id}, + // userId: user.id + // } + // : + // { + // name: microserviceData.name, + // userId: user.id + // }; + // expect(MicroserviceManager.findOne).to.have.been.calledWith(where, transaction); + // }); + // + // context('when MicroserviceManager#findOne() fails', () => { + // def('findMicroserviceResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when MicroserviceManager#findOne() succeeds', () => { + // it('calls CatalogService#getCatalogItem() with correct args', async () => { + // await $subject; + // expect(CatalogService.getCatalogItem).to.have.been.calledWith(newMicroservice.catalogItemId, + // user, isCLI, transaction); + // }); + // + // context('when CatalogService#getCatalogItem() fails', () => { + // def('getCatalogItemResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when CatalogService#getCatalogItem() succeeds', () => { + // it('calls FlowService#getFlow() with correct args', async () => { + // await $subject; + // expect(FlowService.getFlow).to.have.been.calledWith(newMicroservice.flowId, + // user, isCLI, transaction); + // }); + // + // context('when FlowService#getFlow() fails', () => { + // def('getFlowResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when FlowService#getFlow() succeeds', () => { + // it('calls IoFogService#getFog() with correct args', async () => { + // await $subject; + // expect(ioFogService.getFog).to.have.been.calledWith({ + // uuid: newMicroservice.iofogUuid + // }, user, isCLI, transaction); + // }); + // + // context('when IoFogService#getFog() fails', () => { + // def('getIoFogResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when IoFogService#getFog() succeeds', () => { + // it('calls MicroserviceManager#create() with correct args', async () => { + // await $subject; + // expect(MicroserviceManager.create).to.have.been.calledWith(newMicroservice, + // transaction); + // }); + // + // context('when MicroserviceManager#create() fails', () => { + // def('getIoFogResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when MicroserviceManager#create() succeeds', () => { + // it('calls Validator#validate() with correct args', async () => { + // await $subject; + // expect(Validator.validate).to.have.been.calledWith(portMappingData, Validator.schemas.portsCreate); + // }); + // + // context('when Validator#validate() fails', () => { + // def('validatorResponse2', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when Validator#validate() succeeds', () => { + // it('calls MicroserviceManager#findOne() with correct args', async () => { + // await $subject; + // const where = isCLI + // ? {uuid: microserviceData.uuid} + // : {uuid: microserviceData.uuid, userId: user.id}; + // expect(MicroserviceManager.findOne).to.have.been.calledWith(where, transaction); + // }); + // + // context('when MicroserviceManager#findOne() fails', () => { + // def('findMicroserviceResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when MicroserviceManager#findOne() succeeds', () => { + // it('calls MicroservicePortManager#findOne() with correct args', async () => { + // await $subject; + // expect(MicroservicePortManager.findOne).to.have.been.calledWith({ + // microserviceUuid: microserviceData.uuid, + // [Op.or]: + // [ + // { + // portInternal: portMappingData.internal + // }, + // { + // portExternal: portMappingData.external + // } + // ] + // }, transaction); + // }); + // + // context('when MicroservicePortManager#findOne() fails', () => { + // def('findMicroservicePortResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when MicroservicePortManager#findOne() succeeds', () => { + // it('calls MicroservicePortManager#create() with correct args', async () => { + // await $subject; + // expect(MicroservicePortManager.create).to.have.been.calledWith(mappingData, transaction); + // }); + // + // context('when MicroservicePortManager#create() fails', () => { + // def('createMicroservicePortResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when MicroservicePortManager#create() succeeds', () => { + // it('calls MicroserviceManager#update() with correct args', async () => { + // await $subject; + // const updateRebuildMs = { + // rebuild: true + // }; + // expect(MicroserviceManager.update).to.have.been.calledWith({ + // uuid: microserviceData.uuid + // }, updateRebuildMs, transaction); + // }); + // + // context('when MicroserviceManager#update() fails', () => { + // def('updateMicroserviceResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when MicroserviceManager#update() succeeds', () => { + // it('calls ChangeTrackingService#update() with correct args', async () => { + // await $subject; + // expect(ChangeTrackingService.update).to.have.been.calledWith(microserviceData.iofogUuid, + // ChangeTrackingService.events.microserviceConfig, transaction); + // }); + // + // context('when ChangeTrackingService#update() fails', () => { + // def('updateChangeTrackingResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when ChangeTrackingService#update() succeeds', () => { + // it('calls VolumeMappingManager#bulkCreate() with correct args', async () => { + // await $subject; + // expect(VolumeMappingManager.bulkCreate).to.have.been.calledWith(mappings, + // transaction); + // }); + // + // context('when VolumeMappingManager#bulkCreate() fails', () => { + // def('createVolumeMappingResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when VolumeMappingManager#bulkCreate() succeeds', () => { + // it('calls ChangeTrackingService#update() with correct args', async () => { + // await $subject; + // expect(ChangeTrackingService.update).to.have.been.calledWith(microserviceData.iofogUuid, + // ChangeTrackingService.events.microserviceList, transaction); + // }); + // + // context('when ChangeTrackingService#update() fails', () => { + // def('updateChangeTrackingResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when ChangeTrackingService#update() succeeds', () => { + // it('calls MicroserviceStatusManager#create() with correct args', async () => { + // await $subject; + // expect(MicroserviceStatusManager.create).to.have.been.calledWith({ + // microserviceUuid: microserviceData.uuid + // }, transaction); + // }); + // + // context('when MicroserviceStatusManager#create() fails', () => { + // def('createMicroserviceStatusResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when MicroserviceStatusManager#create() succeeds', () => { + // it('fulfills the promise', () => { + // return expect($subject).to.eventually.have.property('uuid'); + // }) + // }) + // }) + // }) + // }) + // }) + // }) + // }) + // }) + // }) + // }) + // }) + // }) + // }) + // }) + // }) + // }) + // }) + // }); + // + // + // describe('.deleteMicroservice()', () => { + // const transaction = {}; + // const error = 'Error!'; + // + // const user = { + // id: 15 + // }; + // + // const microserviceUuid = 'testMicroserviceUuid'; + // + // const microserviceData = { + // "name": "name2", + // "config": "string", + // "catalogItemId": 15, + // "flowId": 16, + // "iofogUuid": 'testIofogUuid', + // "rootHostAccess": true, + // "logSize": 0, + // "volumeMappings": [ + // { + // "hostDestination": "/var/dest", + // "containerDestination": "/var/dest", + // "accessMode": "rw" + // } + // ], + // "ports": [ + // { + // "internal": 1, + // "external": 1, + // "publicMode": false + // } + // ], + // "routes": [] + // }; + // + // const portMappingData = [ + // { + // "internal": 1, + // "external": 1, + // "publicMode": false + // } + // ]; + // + // + // const where = isCLI + // ? + // { + // uuid: microserviceUuid, + // } + // : + // { + // uuid: microserviceUuid, + // userId: user.id + // }; + // + // const mappingData = { + // isPublic: false, + // portInternal: portMappingData.internal, + // portExternal: portMappingData.external, + // userId: microserviceData.userId, + // microserviceUuid: microserviceData.uuid + // }; + // + // def('subject', () => $subject.deleteMicroservice(microserviceUuid, microserviceData, user, isCLI, transaction)); + // def('findMicroserviceResponse', () => Promise.resolve(microserviceData)); + // def('findMicroservicePortResponse', () => Promise.resolve()); + // def('deleteMicroservicePortResponse', () => Promise.resolve()); + // def('updateMicroserviceResponse', () => Promise.resolve()); + // def('updateChangeTrackingResponse', () => Promise.resolve()); + // + // beforeEach(() => { + // $sandbox.stub(MicroserviceManager, 'findOneWithStatusAndCategory').returns($findMicroserviceResponse); + // $sandbox.stub(MicroservicePortManager, 'findAll').returns($findMicroservicePortResponse); + // $sandbox.stub(MicroservicePortManager, 'delete').returns($deleteMicroservicePortResponse); + // $sandbox.stub(MicroserviceManager, 'update').returns($updateMicroserviceResponse); + // $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); + // }); + // + // it('calls Validator#validate() with correct args', async () => { + // await $subject; + // expect(Validator.validate).to.have.been.calledWith(portMappingData, Validator.schemas.portsCreate); + // }); + // + // context('when Validator#validate() fails', () => { + // def('validatorResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when Validator#validate() succeeds', () => { + // it('calls MicroserviceManager#findOne() with correct args', async () => { + // await $subject; + // expect(MicroserviceManager.findOne).to.have.been.calledWith(where, transaction); + // }); + // + // context('when MicroserviceManager#findOne() fails', () => { + // def('findMicroserviceResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when MicroserviceManager#findOne() succeeds', () => { + // it('calls MicroservicePortManager#findOne() with correct args', async () => { + // await $subject; + // expect(MicroservicePortManager.findOne).to.have.been.calledWith({ + // microserviceUuid: microserviceUuid, + // [Op.or]: + // [ + // { + // portInternal: portMappingData.internal + // }, + // { + // portExternal: portMappingData.external + // } + // ] + // }, transaction); + // }); + // + // context('when MicroservicePortManager#findOne() fails', () => { + // def('findMicroservicePortResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when MicroservicePortManager#findOne() succeeds', () => { + // it('calls MicroservicePortManager#create() with correct args', async () => { + // await $subject; + // expect(MicroservicePortManager.create).to.have.been.calledWith(mappingData, transaction); + // }); + // + // context('when MicroservicePortManager#create() fails', () => { + // def('createMicroservicePortResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when MicroservicePortManager#create() succeeds', () => { + // it('calls MicroserviceManager#update() with correct args', async () => { + // await $subject; + // const updateRebuildMs = { + // rebuild: true + // }; + // expect(MicroserviceManager.update).to.have.been.calledWith({ + // uuid: microserviceData.uuid + // }, updateRebuildMs, transaction); + // }); + // + // context('when MicroserviceManager#update() fails', () => { + // def('updateMicroserviceResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when MicroserviceManager#update() succeeds', () => { + // it('calls ChangeTrackingService#update() with correct args', async () => { + // await $subject; + // expect(ChangeTrackingService.update).to.have.been.calledWith(microserviceData.iofogUuid, + // ChangeTrackingService.events.microserviceConfig, transaction); + // }); + // + // context('when ChangeTrackingService#update() fails', () => { + // def('updateChangeTrackingResponse', () => Promise.reject(error)); + // + // it(`fails with ${error}`, () => { + // return expect($subject).to.be.rejectedWith(error); + // }) + // }); + // + // context('when ChangeTrackingService#update() succeeds', () => { + // it('fulfills the promise', () => { + // return expect($subject).eventually.equals(undefined); + // }) + // }) + // }) + // }) + // }) + // }) + // }) + // }); + // + // }); + // describe('.createPortMapping()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const microserviceUuid = 'testMicroserviceUuid'; + const microserviceUuid = 'testMicroserviceUuid' const microserviceData = { - "name": "name2", - "config": "string", - "catalogItemId": 15, - "flowId": 16, - "iofogUuid": 'testIofogUuid', - "rootHostAccess": true, - "logSize": 0, - "volumeMappings": [ + 'name': 'name2', + 'config': 'string', + 'catalogItemId': 15, + 'flowId': 16, + 'iofogUuid': 'testIofogUuid', + 'rootHostAccess': true, + 'logSize': 0, + 'volumeMappings': [ { - "hostDestination": "/var/dest", - "containerDestination": "/var/dest", - "accessMode": "rw" - } + 'hostDestination': '/var/dest', + 'containerDestination': '/var/dest', + 'accessMode': 'rw', + }, ], - "ports": [ + 'ports': [ { - "internal": 1, - "external": 1, - "publicMode": false - } + 'internal': 1, + 'external': 1, + 'publicMode': false, + }, ], - "routes": [] - }; + 'routes': [], + } const portMappingData = [ { - "internal": 1, - "external": 1, - "publicMode": false - } - ]; + 'internal': 1, + 'external': 1, + 'publicMode': false, + }, + ] const where = isCLI ? {uuid: microserviceUuid} - : {uuid: microserviceUuid, userId: user.id}; + : {uuid: microserviceUuid, userId: user.id} const mappingData = { isPublic: false, portInternal: portMappingData.internal, portExternal: portMappingData.external, userId: microserviceData.userId, - microserviceUuid: microserviceData.uuid - }; + microserviceUuid: microserviceData.uuid, + } - def('subject', () => $subject.createPortMapping(microserviceUuid, portMappingData, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('findMicroserviceResponse', () => Promise.resolve(microserviceData)); - def('findMicroservicePortResponse', () => Promise.resolve()); - def('createMicroservicePortResponse', () => Promise.resolve()); - def('updateMicroserviceResponse', () => Promise.resolve()); - def('updateChangeTrackingResponse', () => Promise.resolve()); + def('subject', () => $subject.createPortMapping(microserviceUuid, portMappingData, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('findMicroserviceResponse', () => Promise.resolve(microserviceData)) + def('findMicroservicePortResponse', () => Promise.resolve()) + def('createMicroservicePortResponse', () => Promise.resolve()) + def('updateMicroserviceResponse', () => Promise.resolve()) + def('updateChangeTrackingResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(MicroserviceManager, 'findOne').returns($findMicroserviceResponse); - $sandbox.stub(MicroservicePortManager, 'findOne').returns($findMicroservicePortResponse); - $sandbox.stub(MicroservicePortManager, 'create').returns($createMicroservicePortResponse); - $sandbox.stub(MicroserviceManager, 'update').returns($updateMicroserviceResponse); - $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(MicroserviceManager, 'findOne').returns($findMicroserviceResponse) + $sandbox.stub(MicroservicePortManager, 'findOne').returns($findMicroservicePortResponse) + $sandbox.stub(MicroservicePortManager, 'create').returns($createMicroservicePortResponse) + $sandbox.stub(MicroserviceManager, 'update').returns($updateMicroserviceResponse) + $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(portMappingData, Validator.schemas.portsCreate); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(portMappingData, Validator.schemas.portsCreate) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls MicroserviceManager#findOne() with correct args', async () => { - await $subject; - expect(MicroserviceManager.findOne).to.have.been.calledWith(where, transaction); - }); + await $subject + expect(MicroserviceManager.findOne).to.have.been.calledWith(where, transaction) + }) context('when MicroserviceManager#findOne() fails', () => { - def('findMicroserviceResponse', () => Promise.reject(error)); + def('findMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#findOne() succeeds', () => { it('calls MicroservicePortManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(MicroservicePortManager.findOne).to.have.been.calledWith({ microserviceUuid: microserviceUuid, [Op.or]: [ { - portInternal: portMappingData.internal + portInternal: portMappingData.internal, }, { - portExternal: portMappingData.external - } - ] - }, transaction); - }); + portExternal: portMappingData.external, + }, + ], + }, transaction) + }) context('when MicroservicePortManager#findOne() fails', () => { - def('findMicroservicePortResponse', () => Promise.reject(error)); + def('findMicroservicePortResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicePortManager#findOne() succeeds', () => { it('calls MicroservicePortManager#create() with correct args', async () => { - await $subject; - expect(MicroservicePortManager.create).to.have.been.calledWith(mappingData, transaction); - }); + await $subject + expect(MicroservicePortManager.create).to.have.been.calledWith(mappingData, transaction) + }) context('when MicroservicePortManager#create() fails', () => { - def('createMicroservicePortResponse', () => Promise.reject(error)); + def('createMicroservicePortResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroservicePortManager#create() succeeds', () => { it('calls MicroserviceManager#update() with correct args', async () => { - await $subject; + await $subject const updateRebuildMs = { - rebuild: true - }; + rebuild: true, + } expect(MicroserviceManager.update).to.have.been.calledWith({ - uuid: microserviceData.uuid - }, updateRebuildMs, transaction); - }); + uuid: microserviceData.uuid, + }, updateRebuildMs, transaction) + }) context('when MicroserviceManager#update() fails', () => { - def('updateMicroserviceResponse', () => Promise.reject(error)); + def('updateMicroserviceResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when MicroserviceManager#update() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(microserviceData.iofogUuid, - ChangeTrackingService.events.microserviceConfig, transaction); - }); + ChangeTrackingService.events.microserviceConfig, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('updateChangeTrackingResponse', () => Promise.reject(error)); + def('updateChangeTrackingResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).eventually.equals(undefined); + return expect($subject).eventually.equals(undefined) }) }) }) @@ -1343,6 +1343,5 @@ describe('Microservices Service', () => { }) }) }) - }); - -}); \ No newline at end of file + }) +}) diff --git a/test/src/services/registry-service.test.js b/test/src/services/registry-service.test.js index 111a99bd0..db5675c9a 100644 --- a/test/src/services/registry-service.test.js +++ b/test/src/services/registry-service.test.js @@ -1,30 +1,30 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); - -const RegistryManager = require('../../../src/sequelize/managers/registry-manager'); -const RegistryService = require('../../../src/services/registry-service'); -const Validator = require('../../../src/schemas'); -const AppHelper = require('../../../src/helpers/app-helper'); -const ioFogManager = require('../../../src/sequelize/managers/iofog-manager'); -const ChangeTrackingService = require('../../../src/services/change-tracking-service'); -const Sequelize = require('sequelize'); -const Op = Sequelize.Op; +const {expect} = require('chai') +const sinon = require('sinon') + +const RegistryManager = require('../../../src/sequelize/managers/registry-manager') +const RegistryService = require('../../../src/services/registry-service') +const Validator = require('../../../src/schemas') +const AppHelper = require('../../../src/helpers/app-helper') +const ioFogManager = require('../../../src/sequelize/managers/iofog-manager') +const ChangeTrackingService = require('../../../src/services/change-tracking-service') +const Sequelize = require('sequelize') +const Op = Sequelize.Op describe('Registry Service', () => { - def('subject', () => RegistryService); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => RegistryService) + def('sandbox', () => sinon.createSandbox()) - const isCLI = false; + const isCLI = false - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.createRegistry()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } const registry = { url: 'testUrl', @@ -34,8 +34,8 @@ describe('Registry Service', () => { userEmail: 'testEmail', requiresCert: false, certificate: 'testCertificate', - userId: user.id - }; + userId: user.id, + } const registryCreate = { url: registry.url, @@ -45,120 +45,120 @@ describe('Registry Service', () => { userEmail: registry.email, requiresCert: registry.requiresCert, certificate: registry.certificate, - userId: user.id - }; + userId: user.id, + } const ioFogs = [{ - uuid: 'testUuid' - }]; + uuid: 'testUuid', + }] - def('subject', () => $subject.createRegistry(registry, user, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('deleteUndefinedFieldsResponse', () => registryCreate); + def('subject', () => $subject.createRegistry(registry, user, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('deleteUndefinedFieldsResponse', () => registryCreate) def('createRegistryResponse', () => Promise.resolve({ - id: 16 - })); - def('findIoFogsResponse', () => Promise.resolve(ioFogs)); - def('updateChangeTrackingResponse', () => Promise.resolve()); + id: 16, + })) + def('findIoFogsResponse', () => Promise.resolve(ioFogs)) + def('updateChangeTrackingResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse); - $sandbox.stub(RegistryManager, 'create').returns($createRegistryResponse); - $sandbox.stub(ioFogManager, 'findAll').returns($findIoFogsResponse); - $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse) + $sandbox.stub(RegistryManager, 'create').returns($createRegistryResponse) + $sandbox.stub(ioFogManager, 'findAll').returns($findIoFogsResponse) + $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(registry, Validator.schemas.registryCreate); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(registry, Validator.schemas.registryCreate) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(registryCreate); - }); + await $subject + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(registryCreate) + }) context('when AppHelper#deleteUndefinedFields() fails', () => { - def('deleteUndefinedFieldsResponse', () => error); + def('deleteUndefinedFieldsResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.have.property('id'); + return expect($subject).to.eventually.have.property('id') }) - }); + }) context('when AppHelper#deleteUndefinedFields() succeeds', () => { it('calls RegistryManager#create() with correct args', async () => { - await $subject; - expect(RegistryManager.create).to.have.been.calledWith(registryCreate, transaction); - }); + await $subject + expect(RegistryManager.create).to.have.been.calledWith(registryCreate, transaction) + }) context('when RegistryManager#create() fails', () => { - def('createRegistryResponse', () => Promise.reject(error)); + def('createRegistryResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when RegistryManager#create() succeeds', () => { it('calls ioFogManager#findAll() with correct args', async () => { - await $subject; + await $subject expect(ioFogManager.findAll).to.have.been.calledWith({ - userId: user.id - }, transaction); - }); + userId: user.id, + }, transaction) + }) context('when ioFogManager#findAll() fails', () => { - def('findIoFogsResponse', () => Promise.reject(error)); + def('findIoFogsResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findAll() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(ioFogs[0].uuid, - ChangeTrackingService.events.registries, transaction); - }); + ChangeTrackingService.events.registries, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('findIoFogsResponse', () => Promise.reject(error)); + def('findIoFogsResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.have.property('id'); + return expect($subject).to.eventually.have.property('id') }) }) }) }) }) }) - }); + }) describe('.findRegistries()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } const queryRegistry = isCLI ? {} @@ -166,170 +166,170 @@ describe('Registry Service', () => { [Op.or]: [ { - userId: user.id + userId: user.id, }, { - isPublic: true - } - ] - }; + isPublic: true, + }, + ], + } - def('subject', () => $subject.findRegistries(user, isCLI, transaction)); - def('findRegistriesResponse', () => Promise.resolve([])); + def('subject', () => $subject.findRegistries(user, isCLI, transaction)) + def('findRegistriesResponse', () => Promise.resolve([])) beforeEach(() => { - $sandbox.stub(RegistryManager, 'findAll').returns($findRegistriesResponse); - }); + $sandbox.stub(RegistryManager, 'findAll').returns($findRegistriesResponse) + }) it('calls RegistryManager#findAll() with correct args', async () => { - await $subject; - expect(RegistryManager.findAll).to.have.been.calledWith(queryRegistry, transaction); - }); + await $subject + expect(RegistryManager.findAll).to.have.been.calledWith(queryRegistry, transaction) + }) context('when RegistryManager#findAll() fails', () => { - def('findRegistriesResponse', () => Promise.reject(error)); + def('findRegistriesResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when RegistryManager#findAll() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.have.property('registries'); + return expect($subject).to.eventually.have.property('registries') }) }) - }); + }) describe('.deleteRegistry()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } const registryData = { - id: 5 - }; + id: 5, + } const queryData = isCLI ? {id: registryData.id} - : {id: registryData.id, userId: user.id}; + : {id: registryData.id, userId: user.id} const ioFogs = [{ - uuid: 'testUuid' - }]; + uuid: 'testUuid', + }] - def('subject', () => $subject.deleteRegistry(registryData, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); + def('subject', () => $subject.deleteRegistry(registryData, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) def('findRegistryResponse', () => Promise.resolve({ - userId: user.id - })); - def('deleteRegistryResponse', () => Promise.resolve()); - def('findIoFogsResponse', () => Promise.resolve(ioFogs)); - def('updateChangeTrackingResponse', () => Promise.resolve()); + userId: user.id, + })) + def('deleteRegistryResponse', () => Promise.resolve()) + def('findIoFogsResponse', () => Promise.resolve(ioFogs)) + def('updateChangeTrackingResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(RegistryManager, 'findOne').returns($findRegistryResponse); - $sandbox.stub(RegistryManager, 'delete').returns($deleteRegistryResponse); - $sandbox.stub(ioFogManager, 'findAll').returns($findIoFogsResponse); - $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(RegistryManager, 'findOne').returns($findRegistryResponse) + $sandbox.stub(RegistryManager, 'delete').returns($deleteRegistryResponse) + $sandbox.stub(ioFogManager, 'findAll').returns($findIoFogsResponse) + $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(registryData, Validator.schemas.registryDelete); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(registryData, Validator.schemas.registryDelete) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls RegistryManager#findOne() with correct args', async () => { - await $subject; - expect(RegistryManager.findOne).to.have.been.calledWith(queryData, transaction); - }); + await $subject + expect(RegistryManager.findOne).to.have.been.calledWith(queryData, transaction) + }) context('when RegistryManager#findOne() fails', () => { - def('findRegistryResponse', () => Promise.reject(error)); + def('findRegistryResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when RegistryManager#findOne() succeeds', () => { it('calls RegistryManager#delete() with correct args', async () => { - await $subject; - expect(RegistryManager.delete).to.have.been.calledWith(queryData, transaction); - }); + await $subject + expect(RegistryManager.delete).to.have.been.calledWith(queryData, transaction) + }) context('when RegistryManager#delete() fails', () => { - def('deleteRegistryResponse', () => Promise.reject(error)); + def('deleteRegistryResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when RegistryManager#delete() succeeds', () => { it('calls ioFogManager#findAll() with correct args', async () => { - await $subject; + await $subject expect(ioFogManager.findAll).to.have.been.calledWith({ - userId: user.id - }, transaction); - }); + userId: user.id, + }, transaction) + }) context('when ioFogManager#findAll() fails', () => { - def('findIoFogsResponse', () => Promise.reject(error)); + def('findIoFogsResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findAll() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(ioFogs[0].uuid, - ChangeTrackingService.events.registries, transaction); - }); + ChangeTrackingService.events.registries, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('findIoFogsResponse', () => Promise.reject(error)); + def('findIoFogsResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) }) }) }) }) - }); + }) describe('.updateRegistry()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - const registryId = 5; + const registryId = 5 const registry = { url: 'testUrl', @@ -339,141 +339,141 @@ describe('Registry Service', () => { userEmail: 'testEmail', requiresCert: false, certificate: 'testCertificate', - userId: user.id - }; + userId: user.id, + } - let registryUpdate = { + const registryUpdate = { url: registry.url, username: registry.username, password: registry.password, isPublic: registry.isPublic, userEmail: registry.email, requiresCert: registry.requiresCert, - certificate: registry.certificate - }; + certificate: registry.certificate, + } const ioFogs = [{ - uuid: 'testUuid' - }]; + uuid: 'testUuid', + }] const where = isCLI ? { - id: registryId + id: registryId, } : { id: registryId, - userId: user.id - }; + userId: user.id, + } - def('subject', () => $subject.updateRegistry(registry, registryId, user, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('findRegistryResponse', () => Promise.resolve({})); - def('deleteUndefinedFieldsResponse', () => registryUpdate); - def('updateRegistryResponse', () => Promise.resolve()); - def('findIoFogsResponse', () => Promise.resolve(ioFogs)); - def('updateChangeTrackingResponse', () => Promise.resolve()); + def('subject', () => $subject.updateRegistry(registry, registryId, user, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('findRegistryResponse', () => Promise.resolve({})) + def('deleteUndefinedFieldsResponse', () => registryUpdate) + def('updateRegistryResponse', () => Promise.resolve()) + def('findIoFogsResponse', () => Promise.resolve(ioFogs)) + def('updateChangeTrackingResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(RegistryManager, 'findOne').returns($findRegistryResponse); - $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse); - $sandbox.stub(RegistryManager, 'update').returns($updateRegistryResponse); - $sandbox.stub(ioFogManager, 'findAll').returns($findIoFogsResponse); - $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(RegistryManager, 'findOne').returns($findRegistryResponse) + $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse) + $sandbox.stub(RegistryManager, 'update').returns($updateRegistryResponse) + $sandbox.stub(ioFogManager, 'findAll').returns($findIoFogsResponse) + $sandbox.stub(ChangeTrackingService, 'update').returns($updateChangeTrackingResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(registry, Validator.schemas.registryUpdate); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(registry, Validator.schemas.registryUpdate) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls RegistryManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(RegistryManager.findOne).to.have.been.calledWith({ - id: registryId - }, transaction); - }); + id: registryId, + }, transaction) + }) context('when RegistryManager#findOne() fails', () => { - def('findRegistryResponse', () => Promise.reject(error)); + def('findRegistryResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when RegistryManager#findOne() succeeds', () => { it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(registryUpdate); - }); + await $subject + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(registryUpdate) + }) context('when AppHelper#deleteUndefinedFields() fails', () => { - def('deleteUndefinedFieldsResponse', () => error); + def('deleteUndefinedFieldsResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when AppHelper#deleteUndefinedFields() succeeds', () => { it('calls RegistryManager#update() with correct args', async () => { - await $subject; - expect(RegistryManager.update).to.have.been.calledWith(where, registryUpdate, transaction); - }); + await $subject + expect(RegistryManager.update).to.have.been.calledWith(where, registryUpdate, transaction) + }) context('when RegistryManager#update() fails', () => { - def('updateRegistryResponse', () => Promise.reject(error)); + def('updateRegistryResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when RegistryManager#update() succeeds', () => { it('calls ioFogManager#findAll() with correct args', async () => { - await $subject; + await $subject expect(ioFogManager.findAll).to.have.been.calledWith({ - userId: user.id - }, transaction); - }); + userId: user.id, + }, transaction) + }) context('when ioFogManager#findAll() fails', () => { - def('findIoFogsResponse', () => Promise.reject(error)); + def('findIoFogsResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findAll() succeeds', () => { it('calls ChangeTrackingService#update() with correct args', async () => { - await $subject; + await $subject expect(ChangeTrackingService.update).to.have.been.calledWith(ioFogs[0].uuid, - ChangeTrackingService.events.registries, transaction); - }); + ChangeTrackingService.events.registries, transaction) + }) context('when ChangeTrackingService#update() fails', () => { - def('findIoFogsResponse', () => Promise.reject(error)); + def('findIoFogsResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ChangeTrackingService#update() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) }) @@ -481,6 +481,5 @@ describe('Registry Service', () => { }) }) }) - }); - -}); \ No newline at end of file + }) +}) diff --git a/test/src/services/tunnel-service.test.js b/test/src/services/tunnel-service.test.js index 4d17726eb..43574866e 100644 --- a/test/src/services/tunnel-service.test.js +++ b/test/src/services/tunnel-service.test.js @@ -1,4 +1,4 @@ -const { expect } = require('chai') +const {expect} = require('chai') const sinon = require('sinon') const AppHelper = require('../../../src/helpers/app-helper') @@ -30,7 +30,7 @@ describe('Tunnel Service', () => { })) def('user', () => 'user') def('cli', () => false) - def('fog', () => ({ uuid })) + def('fog', () => ({uuid})) def('fogResponse', () => Promise.resolve($fog)) def('portResponse', () => Promise.resolve(port)) def('validatorResponse', () => Promise.resolve(true)) @@ -48,7 +48,7 @@ describe('Tunnel Service', () => { it('calls FogManager#findOne() with correct args', async () => { await $subject - expect(FogManager.findOne).to.have.been.calledWith({ uuid }, transaction) + expect(FogManager.findOne).to.have.been.calledWith({uuid}, transaction) }) context('when FogManager#findOne() fails', () => { @@ -64,26 +64,26 @@ describe('Tunnel Service', () => { def('fog', () => null) it('fails with error', () => { - return expect($subject).to.be.rejectedWith("Invalid ioFog UUID 'abcd'") + return expect($subject).to.be.rejectedWith('Invalid ioFog UUID \'abcd\'') }) }) context('when FogManager#findOne() returns a Fog instance', () => { - const testOpenTunnel = function (cli) { + const testOpenTunnel = function(cli) { const tunnel = cli ? { host: tunnelHost, iofogUuid: uuid, rport: port, } : { - closed: false, - host: config, - iofogUuid: uuid, - lport: config, - password: config, - rport: port, - rsakey: config, - username: config, - } + closed: false, + host: config, + iofogUuid: uuid, + lport: config, + password: config, + rport: port, + rsakey: config, + username: config, + } it('calls Validator#validate() with correct args', async () => { await $subject @@ -251,7 +251,7 @@ describe('Tunnel Service', () => { context('when tunnelManagerResponse#findAll() succeeds', () => { it('resolves with tunnel info', () => { - return expect($subject).to.eventually.eql({ tunnels: tunnel }) + return expect($subject).to.eventually.eql({tunnels: tunnel}) }) }) }) @@ -295,7 +295,7 @@ describe('Tunnel Service', () => { context('when TunnelService#findTunnel() succeeds', () => { it('calls TunnelManager#update() with correct args', async () => { await $subject - expect(TunnelManager.update).to.have.been.calledWith($tunnelData, { closed: true }, transaction) + expect(TunnelManager.update).to.have.been.calledWith($tunnelData, {closed: true}, transaction) }) context('when TunnelManager#updateOrCreate() fails', () => { @@ -328,4 +328,4 @@ describe('Tunnel Service', () => { }) }) }) -}) \ No newline at end of file +}) diff --git a/test/src/services/user-service.test.js b/test/src/services/user-service.test.js index 0832dc893..5ead92dde 100644 --- a/test/src/services/user-service.test.js +++ b/test/src/services/user-service.test.js @@ -1,256 +1,255 @@ -const {expect} = require('chai'); -const sinon = require('sinon'); - -const UserManager = require('../../../src/sequelize/managers/user-manager'); -const UserService = require('../../../src/services/user-service'); -const Config = require('../../../src/config'); -const AccessTokenService = require('../../../src/services/access-token-service'); -const Validator = require('../../../src/schemas'); -const AppHelper = require('../../../src/helpers/app-helper'); -const ioFogManager = require('../../../src/sequelize/managers/iofog-manager'); -const EmailActivationCodeService = require('../../../src/services/email-activation-code-service'); -const Sequelize = require('sequelize'); -const nodemailer = require('nodemailer'); +const {expect} = require('chai') +const sinon = require('sinon') + +const UserManager = require('../../../src/sequelize/managers/user-manager') +const UserService = require('../../../src/services/user-service') +const Config = require('../../../src/config') +const AccessTokenService = require('../../../src/services/access-token-service') +const Validator = require('../../../src/schemas') +const AppHelper = require('../../../src/helpers/app-helper') +const ioFogManager = require('../../../src/sequelize/managers/iofog-manager') +const EmailActivationCodeService = require('../../../src/services/email-activation-code-service') +const nodemailer = require('nodemailer') describe('User Service', () => { - def('subject', () => UserService); - def('sandbox', () => sinon.createSandbox()); + def('subject', () => UserService) + def('sandbox', () => sinon.createSandbox()) - const isCLI = false; + const isCLI = false - afterEach(() => $sandbox.restore()); + afterEach(() => $sandbox.restore()) describe('.signUp()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const newUser = { id: 16, firstName: 'testFirstName', lastName: 'testLastName', email: 'testEmail', - emailActivated: true - }; + emailActivated: true, + } const response = { userId: 16, firstName: newUser.firstName, lastName: newUser.lastName, email: newUser.email, - emailActivated: newUser.emailActivated - }; + emailActivated: newUser.emailActivated, + } - def('subject', () => $subject.signUp(newUser, isCLI, transaction)); - def('configGetResponse', () => false); - def('findUserResponse', () => Promise.resolve()); - def('createUserResponse', () => Promise.resolve(newUser)); + def('subject', () => $subject.signUp(newUser, isCLI, transaction)) + def('configGetResponse', () => false) + def('findUserResponse', () => Promise.resolve()) + def('createUserResponse', () => Promise.resolve(newUser)) beforeEach(() => { - $sandbox.stub(Config, 'get').returns($configGetResponse); - $sandbox.stub(UserManager, 'findOne').returns($findUserResponse); - $sandbox.stub(UserManager, 'create').returns($createUserResponse); - }); + $sandbox.stub(Config, 'get').returns($configGetResponse) + $sandbox.stub(UserManager, 'findOne').returns($findUserResponse) + $sandbox.stub(UserManager, 'create').returns($createUserResponse) + }) it('calls Config#get() with correct args', async () => { - await $subject; - expect(Config.get).to.have.been.calledWith("Email:ActivationEnabled"); - }); + await $subject + expect(Config.get).to.have.been.calledWith('Email:ActivationEnabled') + }) context('when Config#get() succeeds', () => { it('calls UserManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(UserManager.findOne).to.have.been.calledWith({ - email: newUser.email - }, transaction); - }); + email: newUser.email, + }, transaction) + }) context('when UserManager#findOne() fails', () => { - def('findUserResponse', () => Promise.reject(error)); + def('findUserResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserManager#findOne() succeeds', () => { it('calls UserManager#create() with correct args', async () => { - await $subject; - expect(UserManager.create).to.have.been.calledWith(newUser, transaction); - }); + await $subject + expect(UserManager.create).to.have.been.calledWith(newUser, transaction) + }) context('when UserManager#create() fails', () => { - def('createUserResponse', () => Promise.reject(error)); + def('createUserResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserManager#create() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.deep.equal(response); + return expect($subject).to.eventually.deep.equal(response) }) }) }) }) - }); + }) describe('.login()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const credentials = { email: 'testEmail', - password: 'testPassword' - }; + password: 'testPassword', + } const user = { email: 'testEmail', password: 'testPassword', - id: 15 - }; + id: 15, + } - const testAccessToken = 'testAccessToken'; + const testAccessToken = 'testAccessToken' - const configGet2 = 155; - const date = 1555; - const tokenExpireTime = date + (configGet2 * 1000); + const configGet2 = 155 + const date = 1555 + const tokenExpireTime = date + (configGet2 * 1000) const createToken = { token: testAccessToken, expirationTime: tokenExpireTime, - userId: user.id - }; + userId: user.id, + } - def('subject', () => $subject.login(credentials, isCLI, transaction)); - def('findUserResponse', () => Promise.resolve(user)); - def('decryptTextResponse', () => credentials.password); - def('getConfigResponse', () => false); - def('getConfigResponse2', () => configGet2); - def('generateAccessTokenResponse', () => 'testAccessToken'); - def('findByAccessTokenResponse', () => false); + def('subject', () => $subject.login(credentials, isCLI, transaction)) + def('findUserResponse', () => Promise.resolve(user)) + def('decryptTextResponse', () => credentials.password) + def('getConfigResponse', () => false) + def('getConfigResponse2', () => configGet2) + def('generateAccessTokenResponse', () => 'testAccessToken') + def('findByAccessTokenResponse', () => false) def('createAccessTokenResponse', () => Promise.resolve({ - token: 'token' - })); - def('dateResponse', () => date); + token: 'token', + })) + def('dateResponse', () => date) beforeEach(() => { - $sandbox.stub(UserManager, 'findOne').returns($findUserResponse); - $sandbox.stub(AppHelper, 'decryptText').returns($decryptTextResponse); + $sandbox.stub(UserManager, 'findOne').returns($findUserResponse) + $sandbox.stub(AppHelper, 'decryptText').returns($decryptTextResponse) $sandbox.stub(Config, 'get') - .onFirstCall().returns($getConfigResponse) - .onSecondCall().returns($getConfigResponse2); - $sandbox.stub(AppHelper, 'generateAccessToken').returns($generateAccessTokenResponse); - $sandbox.stub(UserManager, 'findByAccessToken').returns($findByAccessTokenResponse); - $sandbox.stub(AccessTokenService, 'createAccessToken').returns($createAccessTokenResponse); - $sandbox.stub(Date.prototype, 'getTime').returns($dateResponse); - }); + .onFirstCall().returns($getConfigResponse) + .onSecondCall().returns($getConfigResponse2) + $sandbox.stub(AppHelper, 'generateAccessToken').returns($generateAccessTokenResponse) + $sandbox.stub(UserManager, 'findByAccessToken').returns($findByAccessTokenResponse) + $sandbox.stub(AccessTokenService, 'createAccessToken').returns($createAccessTokenResponse) + $sandbox.stub(Date.prototype, 'getTime').returns($dateResponse) + }) it('calls UserManager#findOne() with correct args', async () => { - await $subject; + await $subject expect(UserManager.findOne).to.have.been.calledWith({ - email: credentials.email - }, transaction); - }); + email: credentials.email, + }, transaction) + }) context('when UserManager#findOne() fails', () => { - def('findUserResponse', () => Promise.reject(error)); + def('findUserResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserManager#findOne() succeeds', () => { it('calls AppHelper#decryptText() with correct args', async () => { - await $subject; - expect(AppHelper.decryptText).to.have.been.calledWith(user.password, user.email); - }); + await $subject + expect(AppHelper.decryptText).to.have.been.calledWith(user.password, user.email) + }) context('when AppHelper#decryptText() fails', () => { - const err = 'Invalid credentials'; - def('decryptTextResponse', () => Promise.reject(err)); + const err = 'Invalid credentials' + def('decryptTextResponse', () => Promise.reject(err)) it(`fails with ${err}`, () => { - return expect($subject).to.be.rejectedWith(err); + return expect($subject).to.be.rejectedWith(err) }) - }); + }) context('when AppHelper#decryptText() succeeds', () => { it('calls Config#get() with correct args', async () => { - await $subject; - expect(Config.get).to.have.been.calledWith("Email:ActivationEnabled"); - }); + await $subject + expect(Config.get).to.have.been.calledWith('Email:ActivationEnabled') + }) context('when Config#get() fails', () => { - const err = 'Email is not activated. Please activate your account first.'; - def('getConfigResponse', () => Promise.reject(err)); + const err = 'Email is not activated. Please activate your account first.' + def('getConfigResponse', () => Promise.reject(err)) it(`fails with ${err}`, () => { - return expect($subject).to.be.rejectedWith(err); + return expect($subject).to.be.rejectedWith(err) }) - }); + }) context('when Config#get() succeeds', () => { it('calls AppHelper#generateAccessToken() with correct args', async () => { - await $subject; - expect(AppHelper.generateAccessToken).to.have.been.calledWith(); - }); + await $subject + expect(AppHelper.generateAccessToken).to.have.been.calledWith() + }) context('when AppHelper#generateAccessToken() fails', () => { - def('generateAccessTokenResponse', () => error); + def('generateAccessTokenResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.have.property('accessToken'); + return expect($subject).to.eventually.have.property('accessToken') }) - }); + }) context('when AppHelper#generateAccessToken() succeeds', () => { it('calls UserManager#findByAccessToken() with correct args', async () => { - await $subject; - expect(UserManager.findByAccessToken).to.have.been.calledWith(testAccessToken, transaction); - }); + await $subject + expect(UserManager.findByAccessToken).to.have.been.calledWith(testAccessToken, transaction) + }) context('when UserManager#findByAccessToken() fails', () => { - def('findByAccessTokenResponse', () => Promise.reject(error)); + def('findByAccessTokenResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserManager#findByAccessToken() succeeds', () => { it('calls Config#get() with correct args', async () => { - await $subject; - expect(Config.get).to.have.been.calledWith('Settings:UserTokenExpirationIntervalSeconds'); - }); + await $subject + expect(Config.get).to.have.been.calledWith('Settings:UserTokenExpirationIntervalSeconds') + }) context('when Config#get() fails', () => { - def('getConfigResponse2', () => error); + def('getConfigResponse2', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.have.property('accessToken'); + return expect($subject).to.eventually.have.property('accessToken') }) - }); + }) context('when Config#get() succeeds', () => { it('calls AccessTokenService#createAccessToken() with correct args', async () => { - await $subject; - expect(AccessTokenService.createAccessToken).to.have.been.calledWith(createToken, transaction); - }); + await $subject + expect(AccessTokenService.createAccessToken).to.have.been.calledWith(createToken, transaction) + }) context('when AccessTokenService#createAccessToken() fails', () => { - def('createAccessTokenResponse', () => Promise.reject(error)); + def('createAccessTokenResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AccessTokenService#createAccessToken() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.have.property('accessToken'); + return expect($subject).to.eventually.have.property('accessToken') }) }) }) @@ -259,556 +258,555 @@ describe('User Service', () => { }) }) }) - }); + }) describe('.resendActivation()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { email: 'testEmail', password: 'testPassword', - id: 15 - }; + id: 15, + } const emailObj = { - email: 'testEmail' - }; + email: 'testEmail', + } - const activationCodeData = {}; + const activationCodeData = {} const mailer = { - sendMail: function (options) { - } - }; - - def('subject', () => $subject.resendActivation(emailObj, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('findUserResponse', () => Promise.resolve(user)); - def('generateActivationCodeResponse', () => Promise.resolve({})); - def('saveActivationCodeResponse', () => Promise.resolve()); - def('getEmailAddressResponse', () => "test@test.com"); - def('getEmailPasswordResponse', () => "test"); - def('getEmailServiceResponse', () => "SendGrid"); - def('getEmailHomeUrlResponse', () => "test"); - def('decryptTextResponse', () => 'test'); - def('createTransportResponse', () => mailer); - def('sendMailResponse', () => Promise.resolve()); + sendMail: function(options) { + }, + } + + def('subject', () => $subject.resendActivation(emailObj, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('findUserResponse', () => Promise.resolve(user)) + def('generateActivationCodeResponse', () => Promise.resolve({})) + def('saveActivationCodeResponse', () => Promise.resolve()) + def('getEmailAddressResponse', () => 'test@test.com') + def('getEmailPasswordResponse', () => 'test') + def('getEmailServiceResponse', () => 'SendGrid') + def('getEmailHomeUrlResponse', () => 'test') + def('decryptTextResponse', () => 'test') + def('createTransportResponse', () => mailer) + def('sendMailResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(UserManager, 'findOne').returns($findUserResponse); - $sandbox.stub(EmailActivationCodeService, 'generateActivationCode').returns($generateActivationCodeResponse); - $sandbox.stub(EmailActivationCodeService, 'saveActivationCode').returns($saveActivationCodeResponse); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(UserManager, 'findOne').returns($findUserResponse) + $sandbox.stub(EmailActivationCodeService, 'generateActivationCode').returns($generateActivationCodeResponse) + $sandbox.stub(EmailActivationCodeService, 'saveActivationCode').returns($saveActivationCodeResponse) $sandbox.stub(Config, 'get') - .onCall(0).returns($getEmailAddressResponse) - .onCall(1).returns($getEmailPasswordResponse) - .onCall(2).returns($getEmailAddressResponse) - .onCall(3).returns($getEmailServiceResponse) - .onCall(4).returns($getEmailHomeUrlResponse); - $sandbox.stub(AppHelper, 'decryptText').returns($decryptTextResponse); - $sandbox.stub(nodemailer, 'createTransport').returns($createTransportResponse); - }); + .onCall(0).returns($getEmailAddressResponse) + .onCall(1).returns($getEmailPasswordResponse) + .onCall(2).returns($getEmailAddressResponse) + .onCall(3).returns($getEmailServiceResponse) + .onCall(4).returns($getEmailHomeUrlResponse) + $sandbox.stub(AppHelper, 'decryptText').returns($decryptTextResponse) + $sandbox.stub(nodemailer, 'createTransport').returns($createTransportResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(emailObj, Validator.schemas.resendActivation); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(emailObj, Validator.schemas.resendActivation) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls UserManager#findOne() with correct args', async () => { - await $subject; - expect(UserManager.findOne).to.have.been.calledWith(emailObj, transaction); - }); + await $subject + expect(UserManager.findOne).to.have.been.calledWith(emailObj, transaction) + }) context('when UserManager#findOne() fails', () => { - def('findUserResponse', () => Promise.reject(error)); + def('findUserResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserManager#findOne() succeeds', () => { it('calls EmailActivationCodeService#generateActivationCode() with correct args', async () => { - await $subject; - expect(EmailActivationCodeService.generateActivationCode).to.have.been.calledWith(transaction); - }); + await $subject + expect(EmailActivationCodeService.generateActivationCode).to.have.been.calledWith(transaction) + }) context('when EmailActivationCodeService#generateActivationCode() fails', () => { - def('generateActivationCodeResponse', () => Promise.reject(error)); + def('generateActivationCodeResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when EmailActivationCodeService#generateActivationCode() succeeds', () => { it('calls EmailActivationCodeService#saveActivationCode() with correct args', async () => { - await $subject; + await $subject expect(EmailActivationCodeService.saveActivationCode).to.have.been.calledWith( - user.id, - activationCodeData, - transaction); - }); + user.id, + activationCodeData, + transaction) + }) context('when EmailActivationCodeService#saveActivationCode() fails', () => { - def('saveActivationCodeResponse', () => Promise.reject(error)); + def('saveActivationCodeResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when EmailActivationCodeService#saveActivationCode() succeeds', () => { it('calls Config#get() with correct args', async () => { - await $subject; - expect(Config.get).to.have.been.calledWith("Email:Address"); - }); + await $subject + expect(Config.get).to.have.been.calledWith('Email:Address') + }) context('when Config#get() fails', () => { - def('getEmailAddressResponse', Promise.reject(error)); + def('getEmailAddressResponse', Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when Config#get() succeeds', () => { it('calls Config#get() with correct args', async () => { - await $subject; - expect(Config.get).to.have.been.calledWith("Email:Password"); - }); + await $subject + expect(Config.get).to.have.been.calledWith('Email:Password') + }) context('when Config#get() fails', () => { - def('getEmailPasswordResponse', () => error); + def('getEmailPasswordResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when Config#get() succeeds', () => { it('calls Config#get() with correct args', async () => { - await $subject; - expect(Config.get).to.have.been.calledWith("Email:Address"); - }); + await $subject + expect(Config.get).to.have.been.calledWith('Email:Address') + }) context('when Config#get() fails', () => { - def('getEmailAddressResponse', () => error); + def('getEmailAddressResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when Config#get() succeeds', () => { it('calls Config#get() with correct args', async () => { - await $subject; - expect(Config.get).to.have.been.calledWith("Email:Service"); - }); + await $subject + expect(Config.get).to.have.been.calledWith('Email:Service') + }) context('when Config#get() fails', () => { - def('getEmailServiceResponse', () => error); + def('getEmailServiceResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when Config#get() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); - }); - }); - }); + }) + }) + }) + }) }) }) }) }) - }); + }) describe('.activateUser()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { email: 'testEmail', password: 'testPassword', - id: 15 - }; + id: 15, + } const updatedObj = { - emailActivated: true - }; + emailActivated: true, + } const codeData = { - activationCode: 'testActivationCode' - }; + activationCode: 'testActivationCode', + } - def('subject', () => $subject.activateUser(codeData, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); + def('subject', () => $subject.activateUser(codeData, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) def('verifyActivationCodeResponse', () => Promise.resolve({ - userId: user.id - })); - def('updateUserResponse', () => Promise.resolve()); - def('deleteActivationCodeResponse', () => Promise.resolve()); + userId: user.id, + })) + def('updateUserResponse', () => Promise.resolve()) + def('deleteActivationCodeResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(EmailActivationCodeService, 'verifyActivationCode').returns($verifyActivationCodeResponse); - $sandbox.stub(UserManager, 'update').returns($updateUserResponse); - $sandbox.stub(EmailActivationCodeService, 'deleteActivationCode').returns($deleteActivationCodeResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(EmailActivationCodeService, 'verifyActivationCode').returns($verifyActivationCodeResponse) + $sandbox.stub(UserManager, 'update').returns($updateUserResponse) + $sandbox.stub(EmailActivationCodeService, 'deleteActivationCode').returns($deleteActivationCodeResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(codeData, Validator.schemas.activateUser); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(codeData, Validator.schemas.activateUser) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls EmailActivationCodeService#verifyActivationCode() with correct args', async () => { - await $subject; - expect(EmailActivationCodeService.verifyActivationCode).to.have.been.calledWith(codeData.activationCode, transaction); - }); + await $subject + expect(EmailActivationCodeService.verifyActivationCode).to.have.been.calledWith(codeData.activationCode, transaction) + }) context('when EmailActivationCodeService#verifyActivationCode() fails', () => { - def('verifyActivationCodeResponse', () => Promise.reject(error)); + def('verifyActivationCodeResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when EmailActivationCodeService#verifyActivationCode() succeeds', () => { it('calls UserManager#update() with correct args', async () => { - await $subject; + await $subject expect(UserManager.update).to.have.been.calledWith({ - id: user.id - }, updatedObj, transaction); - }); + id: user.id, + }, updatedObj, transaction) + }) context('when UserManager#update() fails', () => { - const err = 'User not updated'; - def('updateUserResponse', () => Promise.reject(err)); + const err = 'User not updated' + def('updateUserResponse', () => Promise.reject(err)) it(`fails with ${err}`, () => { - return expect($subject).to.be.rejectedWith(err); + return expect($subject).to.be.rejectedWith(err) }) - }); + }) context('when UserManager#update() succeeds', () => { it('calls EmailActivationCodeService#deleteActivationCode() with correct args', async () => { - await $subject; + await $subject expect(EmailActivationCodeService.deleteActivationCode).to.have.been.calledWith(codeData.activationCode, - transaction); - }); + transaction) + }) context('when EmailActivationCodeService#deleteActivationCode() fails', () => { - def('deleteActivationCodeResponse', () => error); + def('deleteActivationCodeResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when EmailActivationCodeService#deleteActivationCode() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) }) }) }) - }); + }) describe('.logout()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } - def('subject', () => $subject.logout(user, isCLI, transaction)); - def('removeAccessTokenResponse', () => Promise.resolve()); + def('subject', () => $subject.logout(user, isCLI, transaction)) + def('removeAccessTokenResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(AccessTokenService, 'removeAccessTokenByUserId').returns($removeAccessTokenResponse); - }); + $sandbox.stub(AccessTokenService, 'removeAccessTokenByUserId').returns($removeAccessTokenResponse) + }) it('calls AccessTokenService#removeAccessTokenByUserId() with correct args', async () => { - await $subject; - expect(AccessTokenService.removeAccessTokenByUserId).to.have.been.calledWith(user.id, transaction); - }); + await $subject + expect(AccessTokenService.removeAccessTokenByUserId).to.have.been.calledWith(user.id, transaction) + }) context('when AccessTokenService#removeAccessTokenByUserId() fails', () => { - def('removeAccessTokenResponse', () => Promise.reject(error)); + def('removeAccessTokenResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AccessTokenService#removeAccessTokenByUserId() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) - }); + }) describe('.updateUserDetails()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { email: 'testEmail', password: 'testPassword', - id: 15 - }; + id: 15, + } const profileData = { firstName: 'testFirstName', - lastName: 'testLastName' - }; + lastName: 'testLastName', + } - def('subject', () => $subject.updateUserDetails(user, profileData, isCLI, transaction)); - def('validatorResponse', () => Promise.resolve(true)); - def('deleteUndefinedFieldsResponse', () => profileData); - def('updateDetailsResponse', () => Promise.resolve()); + def('subject', () => $subject.updateUserDetails(user, profileData, isCLI, transaction)) + def('validatorResponse', () => Promise.resolve(true)) + def('deleteUndefinedFieldsResponse', () => profileData) + def('updateDetailsResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(Validator, 'validate').returns($validatorResponse); - $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse); - $sandbox.stub(UserManager, 'updateDetails').returns($updateDetailsResponse); - }); + $sandbox.stub(Validator, 'validate').returns($validatorResponse) + $sandbox.stub(AppHelper, 'deleteUndefinedFields').returns($deleteUndefinedFieldsResponse) + $sandbox.stub(UserManager, 'updateDetails').returns($updateDetailsResponse) + }) it('calls Validator#validate() with correct args', async () => { - await $subject; - expect(Validator.validate).to.have.been.calledWith(profileData, Validator.schemas.updateUserProfile); - }); + await $subject + expect(Validator.validate).to.have.been.calledWith(profileData, Validator.schemas.updateUserProfile) + }) context('when Validator#validate() fails', () => { - def('validatorResponse', () => Promise.reject(error)); + def('validatorResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when Validator#validate() succeeds', () => { it('calls AppHelper#deleteUndefinedFields() with correct args', async () => { - await $subject; - expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(profileData); - }); + await $subject + expect(AppHelper.deleteUndefinedFields).to.have.been.calledWith(profileData) + }) context('when AppHelper#deleteUndefinedFields() fails', () => { - def('deleteUndefinedFieldsResponse', () => error); + def('deleteUndefinedFieldsResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.have.property('firstName'); + return expect($subject).to.eventually.have.property('firstName') }) - }); + }) context('when AppHelper#deleteUndefinedFields() succeeds', () => { it('calls UserManager#updateDetails() with correct args', async () => { - await $subject; - expect(UserManager.updateDetails).to.have.been.calledWith(user, profileData, transaction); - }); + await $subject + expect(UserManager.updateDetails).to.have.been.calledWith(user, profileData, transaction) + }) context('when UserManager#updateDetails() fails', () => { - def('updateUserResponse', () => Promise.reject(error)); + def('updateUserResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.have.property('firstName'); + return expect($subject).to.eventually.have.property('firstName') }) - }); + }) context('when UserManager#updateDetails() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.have.property('firstName'); + return expect($subject).to.eventually.have.property('firstName') }) }) }) }) - }); + }) describe('.deleteUser()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { email: 'testEmail', password: 'testPassword', - id: 15 - }; + id: 15, + } const profileData = { firstName: 'testFirstName', - lastName: 'testLastName' - }; + lastName: 'testLastName', + } - const force = false; + const force = false - def('subject', () => $subject.deleteUser(force, user, isCLI, transaction)); - def('findAllResponse', () => Promise.resolve([{}])); - def('deleteUserResponse', () => profileData); + def('subject', () => $subject.deleteUser(force, user, isCLI, transaction)) + def('findAllResponse', () => Promise.resolve([{}])) + def('deleteUserResponse', () => profileData) beforeEach(() => { - $sandbox.stub(ioFogManager, 'findAll').returns($findAllResponse); - $sandbox.stub(UserManager, 'delete').returns($deleteUserResponse); - }); + $sandbox.stub(ioFogManager, 'findAll').returns($findAllResponse) + $sandbox.stub(UserManager, 'delete').returns($deleteUserResponse) + }) it('calls ioFogManager#findAll() with correct args', async () => { - await $subject; + await $subject expect(ioFogManager.findAll).to.have.been.calledWith({ - userId: user.id - }, transaction); - }); + userId: user.id, + }, transaction) + }) context('when ioFogManager#findAll() fails', () => { - def('findAllResponse', () => Promise.reject(error)); + def('findAllResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when ioFogManager#findAll() succeeds', () => { it('calls UserManager#delete() with correct args', async () => { - await $subject; + await $subject expect(UserManager.delete).to.have.been.calledWith({ - id: user.id - }, transaction); - }); + id: user.id, + }, transaction) + }) context('when UserManager#delete() fails', () => { - def('deleteUserResponse', () => error); + def('deleteUserResponse', () => error) it(`fails with ${error}`, () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) - }); + }) context('when UserManager#delete() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) }) - }); + }) // TODO updateUserPassword, resetUserPassword with rewire describe('.list()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } const response = [{ - id: user.id - }]; + id: user.id, + }] - def('subject', () => $subject.list(isCLI, transaction)); - def('findAllResponse', () => Promise.resolve(response)); + def('subject', () => $subject.list(isCLI, transaction)) + def('findAllResponse', () => Promise.resolve(response)) beforeEach(() => { - $sandbox.stub(UserManager, 'findAll').returns($findAllResponse); - }); + $sandbox.stub(UserManager, 'findAll').returns($findAllResponse) + }) it('calls UserManager#findAll() with correct args', async () => { - await $subject; - expect(UserManager.findAll).to.have.been.calledWith({}, transaction); - }); + await $subject + expect(UserManager.findAll).to.have.been.calledWith({}, transaction) + }) context('when UserManager#findAll() fails', () => { - def('findAllResponse', () => Promise.reject(error)); + def('findAllResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserManager#findAll() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.equal(response); + return expect($subject).to.eventually.equal(response) }) }) - }); + }) describe('.suspendUser()', () => { - const transaction = {}; - const error = 'Error!'; + const transaction = {} + const error = 'Error!' const user = { - id: 15 - }; + id: 15, + } const updatedObj = { - emailActivated: false - }; + emailActivated: false, + } - def('subject', () => $subject.suspendUser(user, isCLI, transaction)); - def('removeAccessTokenResponse', () => Promise.resolve()); - def('updateUserResponse', () => Promise.resolve()); + def('subject', () => $subject.suspendUser(user, isCLI, transaction)) + def('removeAccessTokenResponse', () => Promise.resolve()) + def('updateUserResponse', () => Promise.resolve()) beforeEach(() => { - $sandbox.stub(AccessTokenService, 'removeAccessTokenByUserId').returns($removeAccessTokenResponse); - $sandbox.stub(UserManager, 'update').returns($updateUserResponse); - }); + $sandbox.stub(AccessTokenService, 'removeAccessTokenByUserId').returns($removeAccessTokenResponse) + $sandbox.stub(UserManager, 'update').returns($updateUserResponse) + }) it('calls AccessTokenService#removeAccessTokenByUserId() with correct args', async () => { - await $subject; - expect(AccessTokenService.removeAccessTokenByUserId).to.have.been.calledWith(user.id, transaction); - }); + await $subject + expect(AccessTokenService.removeAccessTokenByUserId).to.have.been.calledWith(user.id, transaction) + }) context('when AccessTokenService#removeAccessTokenByUserId() fails', () => { - def('removeAccessTokenResponse', () => Promise.reject(error)); + def('removeAccessTokenResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when AccessTokenService#removeAccessTokenByUserId() succeeds', () => { it('calls UserManager#update() with correct args', async () => { - await $subject; + await $subject expect(UserManager.update).to.have.been.calledWith({ - id: user.id - }, updatedObj, transaction); - }); + id: user.id, + }, updatedObj, transaction) + }) context('when UserManager#update() fails', () => { - def('removeAccessTokenResponse', () => Promise.reject(error)); + def('removeAccessTokenResponse', () => Promise.reject(error)) it(`fails with ${error}`, () => { - return expect($subject).to.be.rejectedWith(error); + return expect($subject).to.be.rejectedWith(error) }) - }); + }) context('when UserManager#update() succeeds', () => { it('fulfills the promise', () => { - return expect($subject).to.eventually.equal(undefined); + return expect($subject).to.eventually.equal(undefined) }) }) }) - }); - -}); \ No newline at end of file + }) +}) diff --git a/test/support/setup.js b/test/support/setup.js index 114cd9089..142712256 100644 --- a/test/support/setup.js +++ b/test/support/setup.js @@ -1,7 +1,7 @@ const chai = require('chai') const chaiAsPromised = require('chai-as-promised') const chaiHttp = require('chai-http') -const sinonChai = require("sinon-chai"); +const sinonChai = require('sinon-chai') process.env.NODE_ENV = 'test' process.on('unhandledRejection', () => {}) From b7d0ec341c858f157901e16e394037070c0e13e1 Mon Sep 17 00:00:00 2001 From: dbusel <10116634+dbusel@users.noreply.github.com> Date: Mon, 25 Feb 2019 13:00:15 +0300 Subject: [PATCH 12/17] hot fix --- src/logger/index.js | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/src/logger/index.js b/src/logger/index.js index c3312e6c2..fa5e67990 100644 --- a/src/logger/index.js +++ b/src/logger/index.js @@ -28,17 +28,6 @@ try { // can't initialize log folder } -const dirname = config.get('Service:LogsDirectory') - -// Create the log directory if it does not exist -try { - if (!fs.existsSync(dirname)) { - fs.mkdirSync(dirname); - } -} catch (e) { - // can't initialize log folder -} - const levels = { error: 0, warn: 1, @@ -92,7 +81,8 @@ const logger = winston.createLogger({ ), filename: 'iofog-controller.0.log', dirname: dirname, - maxsize: maxsize, + + : maxsize, rotationFormat: function() { return getFormattedLogName() }, From d7a3ccfe6b0bc7e19db92f5b1545e133396f4221 Mon Sep 17 00:00:00 2001 From: dbusel <10116634+dbusel@users.noreply.github.com> Date: Mon, 25 Feb 2019 13:07:50 +0300 Subject: [PATCH 13/17] Update index.js --- src/logger/index.js | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/logger/index.js b/src/logger/index.js index fa5e67990..ab7a6d56f 100644 --- a/src/logger/index.js +++ b/src/logger/index.js @@ -81,8 +81,7 @@ const logger = winston.createLogger({ ), filename: 'iofog-controller.0.log', dirname: dirname, - - : maxsize, + maxsize: maxsize, rotationFormat: function() { return getFormattedLogName() }, From dbdc888f3d7f9327d7ccd51582438f0f9c11163e Mon Sep 17 00:00:00 2001 From: dbusel <10116634+dbusel@users.noreply.github.com> Date: Mon, 25 Feb 2019 13:18:15 +0300 Subject: [PATCH 14/17] Update index.js --- src/logger/index.js | 15 --------------- 1 file changed, 15 deletions(-) diff --git a/src/logger/index.js b/src/logger/index.js index ab7a6d56f..c5a9f9020 100644 --- a/src/logger/index.js +++ b/src/logger/index.js @@ -111,21 +111,6 @@ function getFormattedLogName() { return '' } -// logFileName pattern similar to agent -function getFormattedLogName() { - if (fs.existsSync(dirname)) { - fs.readdirSync(dirname).reverse().forEach(file => { - const path = dirname + '/' + file - if (fs.existsSync(path)) { - const strNumber = file.replace('iofog-controller.', '').replace('.log', '') - const number = parseInt(strNumber) + 1 - fs.renameSync(path, path.replace(strNumber, number)) - } - }); - } - return '' -} - logger.add(new winston.transports.Console({ level: 'info', format: winston.format((log) => { From 28572f17386be9386fe9a261873ac535ba85c148 Mon Sep 17 00:00:00 2001 From: dbusel <10116634+dbusel@users.noreply.github.com> Date: Mon, 25 Feb 2019 13:19:01 +0300 Subject: [PATCH 15/17] Update postinstall.js --- scripts/postinstall.js | 18 ------------------ 1 file changed, 18 deletions(-) diff --git a/scripts/postinstall.js b/scripts/postinstall.js index d1d818333..d37f5ada9 100644 --- a/scripts/postinstall.js +++ b/scripts/postinstall.js @@ -177,24 +177,6 @@ function updateLogName() { } } -function updateLogName() { - console.log(' updating log name in '); - const dirname = config.get('Service:LogsDirectory') - - if (fs.existsSync(dirname)) { - fs.readdirSync(dirname).forEach(file => { - const path = dirname + '/' + file - if (fs.existsSync(path)) { - fs.unlinkSync(path, function(err) { - if (err) return console.log(err); - console.log('log deleted successfully'); - }) - } - }); - } - -} - module.exports = { postinstall: postinstall, } From c45b7f0ed20a48dc688f7b46a202e0c4669c11b6 Mon Sep 17 00:00:00 2001 From: dbusel Date: Mon, 25 Feb 2019 13:23:53 +0300 Subject: [PATCH 16/17] fix lint errors --- scripts/postinstall.js | 4 ---- 1 file changed, 4 deletions(-) diff --git a/scripts/postinstall.js b/scripts/postinstall.js index d37f5ada9..a7723b45c 100644 --- a/scripts/postinstall.js +++ b/scripts/postinstall.js @@ -46,10 +46,6 @@ function postinstall() { console.log('upgrading from version <= 1.0.37 :') updateLogName() } - if (semver.satisfies(prevVersion, '<=1.0.37')) { - console.log('upgrading from version <= 1.0.37 :'); - updateLogName(); - } fs.unlinkSync(INSTALLATION_VARIABLES_FILE) } catch (e) { From e69570a1658781750d31f0541bd86061fa9c95d5 Mon Sep 17 00:00:00 2001 From: dbusel <10116634+dbusel@users.noreply.github.com> Date: Mon, 25 Feb 2019 13:36:53 +0300 Subject: [PATCH 17/17] update version --- package.json | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/package.json b/package.json index 75387ebf2..29476f21a 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "iofogcontroller", - "version": "1.0.37-prerelease.0", + "version": "1.0.36", "description": "ioFog Controller project for Eclipse IoFog @ iofog.org \\nCopyright (c) 2018 Edgeworx, Inc.", "main": "./src/main.js", "author": "Saeid Baghbidi",