From 95df3522a15631abc51a4295cae0ea401a8d4e1e Mon Sep 17 00:00:00 2001 From: Markus Hatvan Date: Tue, 14 Sep 2021 19:58:52 +0200 Subject: feat: add eslint-plugin-unicorn (#1936) --- .../app/Controllers/Http/RecipeController.js | 51 +++--- .../app/Controllers/Http/ServiceController.js | 16 +- .../app/Controllers/Http/UserController.js | 176 +++++++++++---------- 3 files changed, 125 insertions(+), 118 deletions(-) (limited to 'src/internal-server/app/Controllers') diff --git a/src/internal-server/app/Controllers/Http/RecipeController.js b/src/internal-server/app/Controllers/Http/RecipeController.js index 1a7595a9d..2c7baf2a4 100644 --- a/src/internal-server/app/Controllers/Http/RecipeController.js +++ b/src/internal-server/app/Controllers/Http/RecipeController.js @@ -1,8 +1,6 @@ const Recipe = use('App/Models/Recipe'); const Drive = use('Drive'); -const { - validateAll, -} = use('Validator'); +const { validateAll } = use('Validator'); const Env = use('Env'); const fetch = require('node-fetch'); @@ -14,9 +12,7 @@ const RECIPES_URL = `${LIVE_FERDI_API}/${API_VERSION}/recipes`; class RecipeController { // List official and custom recipes - async list({ - response, - }) { + async list({ response }) { const officialRecipes = JSON.parse(await (await fetch(RECIPES_URL)).text()); const customRecipesArray = (await Recipe.all()).rows; const customRecipes = customRecipesArray.map(recipe => ({ @@ -25,19 +21,13 @@ class RecipeController { ...JSON.parse(recipe.data), })); - const recipes = [ - ...officialRecipes, - ...customRecipes, - ]; + const recipes = [...officialRecipes, ...customRecipes]; return response.send(recipes); } // Search official and custom recipes - async search({ - request, - response, - }) { + async search({ request, response }) { // Validate user input const validation = await validateAll(request.all(), { needle: 'required', @@ -64,13 +54,23 @@ class RecipeController { })); } else { let remoteResults = []; - if (Env.get('CONNECT_WITH_FRANZ') == 'true') { // eslint-disable-line eqeqeq - remoteResults = JSON.parse(await (await fetch(`${RECIPES_URL}/search?needle=${encodeURIComponent(needle)}`)).text()); + // eslint-disable-next-line eqeqeq + if (Env.get('CONNECT_WITH_FRANZ') == 'true') { + // eslint-disable-line eqeqeq + remoteResults = JSON.parse( + await ( + await fetch( + `${RECIPES_URL}/search?needle=${encodeURIComponent(needle)}`, + ) + ).text(), + ); } debug('remoteResults:', remoteResults); - const localResultsArray = (await Recipe.query().where('name', 'LIKE', `%${needle}%`).fetch()).toJSON(); + const localResultsArray = ( + await Recipe.query().where('name', 'LIKE', `%${needle}%`).fetch() + ).toJSON(); const localResults = localResultsArray.map(recipe => ({ id: recipe.recipeId, name: recipe.name, @@ -79,20 +79,14 @@ class RecipeController { debug('localResults:', localResults); - results = [ - ...localResults, - ...remoteResults || [], - ]; + results = [...localResults, ...(remoteResults || [])]; } return response.send(results); } // Download a recipe - async download({ - response, - params, - }) { + async download({ response, params }) { // Validate user input const validation = await validateAll(params, { recipe: 'required|accepted', @@ -108,14 +102,17 @@ class RecipeController { const service = params.recipe; // Check for invalid characters - if (/\.{1,}/.test(service) || /\/{1,}/.test(service)) { + if (/\.+/.test(service) || /\/+/.test(service)) { return response.send('Invalid recipe name'); } // Check if recipe exists in recipes folder if (await Drive.exists(`${service}.tar.gz`)) { return response.send(await Drive.get(`${service}.tar.gz`)); - } if (Env.get('CONNECT_WITH_FRANZ') == 'true') { // eslint-disable-line eqeqeq + } + // eslint-disable-next-line eqeqeq + if (Env.get('CONNECT_WITH_FRANZ') == 'true') { + // eslint-disable-line eqeqeq return response.redirect(`${RECIPES_URL}/download/${service}`); } return response.status(400).send({ diff --git a/src/internal-server/app/Controllers/Http/ServiceController.js b/src/internal-server/app/Controllers/Http/ServiceController.js index f2af9d411..ae463617d 100644 --- a/src/internal-server/app/Controllers/Http/ServiceController.js +++ b/src/internal-server/app/Controllers/Http/ServiceController.js @@ -135,13 +135,11 @@ class ServiceController { const newSettings = { ...settings, - ...{ - iconId, - customIconVersion: - settings && settings.customIconVersion - ? settings.customIconVersion + 1 - : 1, - }, + iconId, + customIconVersion: + settings && settings.customIconVersion + ? settings.customIconVersion + 1 + : 1, }; // Update data in database @@ -157,9 +155,7 @@ class ServiceController { id, name: service.name, ...newSettings, - iconUrl: `http://${hostname}:${port}/${API_VERSION}/icon/${ - newSettings.iconId - }`, + iconUrl: `http://${hostname}:${port}/${API_VERSION}/icon/${newSettings.iconId}`, userId: 1, }, status: ['updated'], diff --git a/src/internal-server/app/Controllers/Http/UserController.js b/src/internal-server/app/Controllers/Http/UserController.js index 994dcc0dc..7b71aac14 100644 --- a/src/internal-server/app/Controllers/Http/UserController.js +++ b/src/internal-server/app/Controllers/Http/UserController.js @@ -1,34 +1,37 @@ const User = use('App/Models/User'); const Service = use('App/Models/Service'); const Workspace = use('App/Models/Workspace'); -const { - validateAll, -} = use('Validator'); +const { validateAll } = use('Validator'); const btoa = require('btoa'); const fetch = require('node-fetch'); const uuid = require('uuid/v4'); const crypto = require('crypto'); -const { DEFAULT_APP_SETTINGS, API_VERSION } = require('../../../../environment'); +const { + DEFAULT_APP_SETTINGS, + API_VERSION, +} = require('../../../../environment'); const { default: userAgent } = require('../../../../helpers/userAgent-helpers'); -const apiRequest = (url, route, method, auth) => new Promise((resolve, reject) => { - try { - fetch(`${url}/${API_VERSION}/${route}`, { - method, - headers: { - Authorization: `Bearer ${auth}`, - 'User-Agent': userAgent(), - }, - }) - .then(data => data.json()) - .then(json => resolve(json)); - } catch (e) { - reject(); - } -}); +const apiRequest = (url, route, method, auth) => + new Promise((resolve, reject) => { + try { + fetch(`${url}/${API_VERSION}/${route}`, { + method, + headers: { + Authorization: `Bearer ${auth}`, + 'User-Agent': userAgent(), + }, + }) + .then(data => data.json()) + .then(json => resolve(json)); + } catch { + reject(); + } + }); -const LOGIN_SUCCESS_TOKEN = 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJGZXJkaSBJbnRlcm5hbCBTZXJ2ZXIiLCJpYXQiOjE1NzEwNDAyMTUsImV4cCI6MjUzMzk1NDE3ODQ0LCJhdWQiOiJnZXRmZXJkaS5jb20iLCJzdWIiOiJmZXJkaUBsb2NhbGhvc3QiLCJ1c2VySWQiOiIxIn0.9_TWFGp6HROv8Yg82Rt6i1-95jqWym40a-HmgrdMC6M'; +const LOGIN_SUCCESS_TOKEN = + 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJpc3MiOiJGZXJkaSBJbnRlcm5hbCBTZXJ2ZXIiLCJpYXQiOjE1NzEwNDAyMTUsImV4cCI6MjUzMzk1NDE3ODQ0LCJhdWQiOiJnZXRmZXJkaS5jb20iLCJzdWIiOiJmZXJkaUBsb2NhbGhvc3QiLCJ1c2VySWQiOiIxIn0.9_TWFGp6HROv8Yg82Rt6i1-95jqWym40a-HmgrdMC6M'; const DEFAULT_USER_DATA = { accountType: 'individual', @@ -45,10 +48,7 @@ const DEFAULT_USER_DATA = { class UserController { // Register a new user - async signup({ - request, - response, - }) { + async signup({ request, response }) { // Validate user input const validation = await validateAll(request.all(), { firstname: 'required', @@ -70,10 +70,7 @@ class UserController { } // Login using an existing user - async login({ - request, - response, - }) { + async login({ request, response }) { if (!request.header('Authorization')) { return response.status(401).send({ message: 'Please provide authorization', @@ -88,23 +85,21 @@ class UserController { } // Return information about the current user - async me({ - response, - }) { + async me({ response }) { const user = await User.find(1); - const settings = typeof user.settings === 'string' ? JSON.parse(user.settings) : user.settings; + const settings = + typeof user.settings === 'string' + ? JSON.parse(user.settings) + : user.settings; return response.send({ ...DEFAULT_USER_DATA, - ...settings || {}, + ...settings, }); } - async updateMe({ - request, - response, - }) { + async updateMe({ request, response }) { const user = await User.find(1); let settings = user.settings || {}; @@ -125,16 +120,11 @@ class UserController { ...DEFAULT_USER_DATA, ...newSettings, }, - status: [ - 'data-updated', - ], + status: ['data-updated'], }); } - async import({ - request, - response, - }) { + async import({ request, response }) { // Validate user input const validation = await validateAll(request.all(), { email: 'required|email', @@ -142,7 +132,8 @@ class UserController { server: 'required', }); if (validation.fails()) { - let errorMessage = 'There was an error while trying to import your account:\n'; + let errorMessage = + 'There was an error while trying to import your account:\n'; for (const message of validation.messages()) { if (message.validation === 'required') { errorMessage += `- Please make sure to supply your ${message.field}\n`; @@ -155,13 +146,12 @@ class UserController { return response.status(401).send(errorMessage); } - const { - email, - password, - server, - } = request.all(); + const { email, password, server } = request.all(); - const hashedPassword = crypto.createHash('sha256').update(password).digest('base64'); + const hashedPassword = crypto + .createHash('sha256') + .update(password) + .digest('base64'); // Try to get an authentication token let token; @@ -178,16 +168,17 @@ class UserController { const content = await rawResponse.json(); if (!content.message || content.message !== 'Successfully logged in') { - const errorMessage = 'Could not login into Franz with your supplied credentials. Please check and try again'; + const errorMessage = + 'Could not login into Franz with your supplied credentials. Please check and try again'; return response.status(401).send(errorMessage); } // eslint-disable-next-line prefer-destructuring token = content.token; - } catch (e) { + } catch (error) { return response.status(401).send({ message: 'Cannot login to Franz', - error: e, + error, }); } @@ -195,12 +186,13 @@ class UserController { let userInf = false; try { userInf = await apiRequest(server, 'me', 'GET', token); - } catch (e) { - const errorMessage = `Could not get your user info from Franz. Please check your credentials or try again later.\nError: ${e}`; + } catch (error) { + const errorMessage = `Could not get your user info from Franz. Please check your credentials or try again later.\nError: ${error}`; return response.status(401).send(errorMessage); } if (!userInf) { - const errorMessage = 'Could not get your user info from Franz. Please check your credentials or try again later'; + const errorMessage = + 'Could not get your user info from Franz. Please check your credentials or try again later'; return response.status(401).send(errorMessage); } @@ -213,8 +205,8 @@ class UserController { for (const service of services) { await this._createAndCacheService(service, serviceIdTranslation); // eslint-disable-line no-await-in-loop } - } catch (e) { - const errorMessage = `Could not import your services into our system.\nError: ${e}`; + } catch (error) { + const errorMessage = `Could not import your services into our system.\nError: ${error}`; return response.status(401).send(errorMessage); } @@ -225,12 +217,14 @@ class UserController { for (const workspace of workspaces) { await this._createWorkspace(workspace, serviceIdTranslation); // eslint-disable-line no-await-in-loop } - } catch (e) { - const errorMessage = `Could not import your workspaces into our system.\nError: ${e}`; + } catch (error) { + const errorMessage = `Could not import your workspaces into our system.\nError: ${error}`; return response.status(401).send(errorMessage); } - return response.send('Your account has been imported. You can now use your Franz account in Ferdi.'); + return response.send( + 'Your account has been imported. You can now use your Franz account in Ferdi.', + ); } // Account import/export @@ -255,10 +249,7 @@ class UserController { .send(exportData); } - async importFerdi({ - request, - response, - }) { + async importFerdi({ request, response }) { const validation = await validateAll(request.all(), { file: 'required', }); @@ -269,8 +260,10 @@ class UserController { let file; try { file = JSON.parse(request.input('file')); - } catch (e) { - return response.send('Could not import: Invalid file, could not read file'); + } catch { + return response.send( + 'Could not import: Invalid file, could not read file', + ); } if (!file || !file.services || !file.workspaces) { @@ -284,8 +277,8 @@ class UserController { for (const service of file.services) { await this._createAndCacheService(service, serviceIdTranslation); // eslint-disable-line no-await-in-loop } - } catch (e) { - const errorMessage = `Could not import your services into our system.\nError: ${e}`; + } catch (error) { + const errorMessage = `Could not import your services into our system.\nError: ${error}`; return response.send(errorMessage); } @@ -294,8 +287,8 @@ class UserController { for (const workspace of file.workspaces) { await this._createWorkspace(workspace, serviceIdTranslation); // eslint-disable-line no-await-in-loop } - } catch (e) { - const errorMessage = `Could not import your workspaces into our system.\nError: ${e}`; + } catch (error) { + const errorMessage = `Could not import your workspaces into our system.\nError: ${error}`; return response.status(401).send(errorMessage); } @@ -306,15 +299,29 @@ class UserController { let newWorkspaceId; do { newWorkspaceId = uuid(); - } while ((await Workspace.query().where('workspaceId', newWorkspaceId).fetch()).rows.length > 0); // eslint-disable-line no-await-in-loop - - if (workspace.services && typeof (workspace.services) === 'string' && workspace.services.length > 0) { + } while ( + (await Workspace.query().where('workspaceId', newWorkspaceId).fetch()) + .rows.length > 0 + ); // eslint-disable-line no-await-in-loop + + if ( + workspace.services && + typeof workspace.services === 'string' && + workspace.services.length > 0 + ) { workspace.services = JSON.parse(workspace.services); } - const services = (workspace.services && typeof (workspace.services) === 'object') ? - workspace.services.map(oldServiceId => serviceIdTranslation[oldServiceId]) : - []; - if (workspace.data && typeof (workspace.data) === 'string' && workspace.data.length > 0) { + const services = + workspace.services && typeof workspace.services === 'object' + ? workspace.services.map( + oldServiceId => serviceIdTranslation[oldServiceId], + ) + : []; + if ( + workspace.data && + typeof workspace.data === 'string' && + workspace.data.length > 0 + ) { workspace.data = JSON.parse(workspace.data); } @@ -332,12 +339,19 @@ class UserController { let newServiceId; do { newServiceId = uuid(); - } while ((await Service.query().where('serviceId', newServiceId).fetch()).rows.length > 0); // eslint-disable-line no-await-in-loop + } while ( + (await Service.query().where('serviceId', newServiceId).fetch()).rows + .length > 0 + ); // eslint-disable-line no-await-in-loop // store the old serviceId as the key for future lookup serviceIdTranslation[service.serviceId] = newServiceId; - if (service.settings && typeof (service.settings) === 'string' && service.settings.length > 0) { + if ( + service.settings && + typeof service.settings === 'string' && + service.settings.length > 0 + ) { service.settings = JSON.parse(service.settings); } -- cgit v1.2.3-54-g00ecf