From bfc5ac0ff3db9a528faf6007c52590a1f998f27b Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Wed, 29 Sep 2021 18:19:24 +0000 Subject: [PATCH 1/2] Adds the appropriate return type for the method or function --- .../src/shared/cron/index.ts | 2 +- .../api-catalog-spa/src/reportWebVitals.ts | 2 +- .../src/utils/unique-id-from-path.ts | 2 +- .../src/hooks/useAppAPI.ts | 5 ++++- .../src/hooks/useFeedbackConfig.ts | 5 ++++- .../src/hooks/useLighthouseConfig.ts | 5 ++++- .../src/hooks/useMyAppsAPI.ts | 4 +++- .../src/reportWebVitals.ts | 2 +- .../src/audit-manager/resolver.ts | 2 +- .../pages/analysis/analysis.component.ts | 6 +++--- .../app/dashboard/pages/home/home.component.ts | 8 ++++---- .../pages/leaderboard/leaderboard.component.ts | 16 ++++++++-------- .../components/home/home.component.ts | 18 +++++++++--------- .../components/avatar/avatar.component.ts | 2 +- .../context-selector.component.ts | 6 +++--- .../outlined-pie-graph.component.ts | 2 +- .../layouts/app-layout/app-layout.component.ts | 2 +- .../notification-spa/src/app/graphql.module.ts | 4 +++- .../spa-notifications-list.component.ts | 4 ++-- .../manage-notification.component.ts | 8 ++++---- .../src/components/opc-loader/opc-loader.ts | 2 +- .../keycloakAuthProvider.ts | 8 ++++---- .../src/opc-provider/opc-provider.helper.ts | 2 +- .../opc-base/src/opc-provider/opc-provider.ts | 4 ++-- .../src/couchdb/resolver.ts | 2 +- .../src/middleware/jwtAuth.ts | 2 +- .../src/utils/setupJest.ts | 2 +- .../src/search-mapping/resolver.ts | 2 +- .../src/app/search/search.component.ts | 8 ++++---- .../src/api-keys/resolver.ts | 2 +- packages/user-group-service/src/users/cron.ts | 2 +- 31 files changed, 77 insertions(+), 64 deletions(-) diff --git a/packages/api-catalog-service/src/shared/cron/index.ts b/packages/api-catalog-service/src/shared/cron/index.ts index 972b3f48a..cf403f662 100644 --- a/packages/api-catalog-service/src/shared/cron/index.ts +++ b/packages/api-catalog-service/src/shared/cron/index.ts @@ -4,7 +4,7 @@ import { MONGO_URL } from '../../setup/env'; import { checkAPIHash } from './cron'; export let agenda: Agenda; -export default function initializeAgenda () { +export default function initializeAgenda (): void { console.info( 'SETUP - Agenda for cron scripts..' ); agenda = new Agenda( { db: { diff --git a/packages/api-catalog-spa/src/reportWebVitals.ts b/packages/api-catalog-spa/src/reportWebVitals.ts index 49a2a16e0..d22630b84 100644 --- a/packages/api-catalog-spa/src/reportWebVitals.ts +++ b/packages/api-catalog-spa/src/reportWebVitals.ts @@ -1,6 +1,6 @@ import { ReportHandler } from 'web-vitals'; -const reportWebVitals = (onPerfEntry?: ReportHandler) => { +const reportWebVitals = (onPerfEntry?: ReportHandler): void => { if (onPerfEntry && onPerfEntry instanceof Function) { import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { getCLS(onPerfEntry); diff --git a/packages/apps-service/src/utils/unique-id-from-path.ts b/packages/apps-service/src/utils/unique-id-from-path.ts index 5bde3224c..b635781b4 100644 --- a/packages/apps-service/src/utils/unique-id-from-path.ts +++ b/packages/apps-service/src/utils/unique-id-from-path.ts @@ -1,4 +1,4 @@ -export default function uniqueIdFromPath ( path: string ) { +export default function uniqueIdFromPath ( path: string ): string { return path.toLowerCase() /* Replace any special characters with `-` */ .replace( /[\ \-\/\:\@\[\]\`\{\~\.]+/g, '-' ) diff --git a/packages/developer-console-spa/src/hooks/useAppAPI.ts b/packages/developer-console-spa/src/hooks/useAppAPI.ts index 4d0771318..3215177a1 100644 --- a/packages/developer-console-spa/src/hooks/useAppAPI.ts +++ b/packages/developer-console-spa/src/hooks/useAppAPI.ts @@ -2,7 +2,10 @@ import { useEffect, useState } from 'react'; import { appByAppId } from '../utils/gql-queries/app-by-appid'; import gqlClient from '../utils/gqlClient'; -export default function useAppAPI ( appId: string ) { +export default function useAppAPI ( appId: string ): {app: error; +loading: error; +setApp: error; +} { const [ app, setApp ] = useState( {} ); const [ loading, setLoading ] = useState( true ); diff --git a/packages/developer-console-spa/src/hooks/useFeedbackConfig.ts b/packages/developer-console-spa/src/hooks/useFeedbackConfig.ts index c98db4f6e..33922b182 100644 --- a/packages/developer-console-spa/src/hooks/useFeedbackConfig.ts +++ b/packages/developer-console-spa/src/hooks/useFeedbackConfig.ts @@ -2,7 +2,10 @@ import { useEffect, useState } from 'react'; import { appFeedbackConfig } from '../utils/gql-queries'; import gqlClient from '../utils/gqlClient'; -export default function useFeedbackConfig ( appId: string ) { +export default function useFeedbackConfig ( appId: string ): {feedbackConfig: error; +setFeedbackConfig: error; +loading: error; +} { const [ feedbackConfig, setFeedbackConfig ] = useState( {} ); const [ loading, setLoading ] = useState( true ); diff --git a/packages/developer-console-spa/src/hooks/useLighthouseConfig.ts b/packages/developer-console-spa/src/hooks/useLighthouseConfig.ts index c4082f880..e2c178a66 100644 --- a/packages/developer-console-spa/src/hooks/useLighthouseConfig.ts +++ b/packages/developer-console-spa/src/hooks/useLighthouseConfig.ts @@ -1,7 +1,10 @@ import { useEffect, useState } from 'react'; import { getLHSpaConfigByAppId } from '../services/lighthouse'; -export default function useLighthouseConfig ( id: string ) { +export default function useLighthouseConfig ( id: string ): {lighthouseConfig: error; +setLighthouseConfig: error; +loading: error; +} { const [ lighthouseConfig, setLighthouseConfig ] = useState( {} ); const [ loading, setLoading ] = useState( true ); diff --git a/packages/developer-console-spa/src/hooks/useMyAppsAPI.ts b/packages/developer-console-spa/src/hooks/useMyAppsAPI.ts index 4370a7634..52c5d801c 100644 --- a/packages/developer-console-spa/src/hooks/useMyAppsAPI.ts +++ b/packages/developer-console-spa/src/hooks/useMyAppsAPI.ts @@ -2,7 +2,9 @@ import { useEffect, useState } from 'react'; import { myApps } from '../utils/gql-queries'; import gqlClient from '../utils/gqlClient'; -export default function useMyAppsAPI () { +export default function useMyAppsAPI (): {apps: error; +loading: error; +} { const [ apps, setApps ] = useState( [] ); const [ loading, setLoading ] = useState( true ); diff --git a/packages/developer-console-spa/src/reportWebVitals.ts b/packages/developer-console-spa/src/reportWebVitals.ts index 49a2a16e0..d22630b84 100644 --- a/packages/developer-console-spa/src/reportWebVitals.ts +++ b/packages/developer-console-spa/src/reportWebVitals.ts @@ -1,6 +1,6 @@ import { ReportHandler } from 'web-vitals'; -const reportWebVitals = (onPerfEntry?: ReportHandler) => { +const reportWebVitals = (onPerfEntry?: ReportHandler): void => { if (onPerfEntry && onPerfEntry instanceof Function) { import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { getCLS(onPerfEntry); diff --git a/packages/lighthouse-service/src/audit-manager/resolver.ts b/packages/lighthouse-service/src/audit-manager/resolver.ts index 8dd2ed311..fb920f167 100644 --- a/packages/lighthouse-service/src/audit-manager/resolver.ts +++ b/packages/lighthouse-service/src/audit-manager/resolver.ts @@ -102,7 +102,7 @@ export const LighthouseAuditResolver = { }, }, Mutation: { - auditWebsite(root: any, args: any, ctx: any) { + auditWebsite(root: any, args: any, ctx: any): string { const LHCI_BUILD_CONTEXT__CURRENT_HASH = new Date() .getTime() .toString(16) diff --git a/packages/lighthouse-spa/src/app/dashboard/pages/analysis/analysis.component.ts b/packages/lighthouse-spa/src/app/dashboard/pages/analysis/analysis.component.ts index e9cbd4629..3343f31df 100644 --- a/packages/lighthouse-spa/src/app/dashboard/pages/analysis/analysis.component.ts +++ b/packages/lighthouse-spa/src/app/dashboard/pages/analysis/analysis.component.ts @@ -124,15 +124,15 @@ export class AnalysisComponent implements OnInit { } // context selector functions - onToggleBranchSelector(isOpen: boolean) { + onToggleBranchSelector(isOpen: boolean): void { this.isBranchContextSelectorOpen = isOpen; } - onBranchSelectorSearchChange(searchValue: string) { + onBranchSelectorSearchChange(searchValue: string): void { this.branchContextSelectorSearchValue = searchValue; } - onBranchSelect(branch: string) { + onBranchSelect(branch: string): void { this.selectedBranch = branch; this.isBranchContextSelectorOpen = false; this.branchContextSelectorSearchValue = ''; diff --git a/packages/lighthouse-spa/src/app/dashboard/pages/home/home.component.ts b/packages/lighthouse-spa/src/app/dashboard/pages/home/home.component.ts index 07d4cfbef..ccf523537 100644 --- a/packages/lighthouse-spa/src/app/dashboard/pages/home/home.component.ts +++ b/packages/lighthouse-spa/src/app/dashboard/pages/home/home.component.ts @@ -78,15 +78,15 @@ export class HomeComponent implements OnInit { }); } - ngOnDestroy() { + ngOnDestroy(): void { this.searchControl.unsubscribe(); } - validateUrl(url: string) { + validateUrl(url: string): void { this.validUrl = url.indexOf('http://') == 0 || url.indexOf('https://') == 0; } - navigateToReportGeneration() { + navigateToReportGeneration(): void { this.router.navigate(['/playground'], { queryParams: { siteUrl: this.sites, @@ -95,7 +95,7 @@ export class HomeComponent implements OnInit { }); } - onSearchChange(event: Event) { + onSearchChange(event: Event): void { const searchTerm = (event.target as HTMLInputElement).value; this.searchProject = searchTerm; this.searchControl.next(searchTerm); diff --git a/packages/lighthouse-spa/src/app/leaderboard/pages/leaderboard/leaderboard.component.ts b/packages/lighthouse-spa/src/app/leaderboard/pages/leaderboard/leaderboard.component.ts index 1051277d3..a13ab31da 100644 --- a/packages/lighthouse-spa/src/app/leaderboard/pages/leaderboard/leaderboard.component.ts +++ b/packages/lighthouse-spa/src/app/leaderboard/pages/leaderboard/leaderboard.component.ts @@ -38,7 +38,7 @@ export class LeaderboardComponent implements OnInit { this.fetchLHLeaderboard(); } - fetchLHLeaderboard() { + fetchLHLeaderboard(): void { this.isPageLoading = true; try { @@ -62,7 +62,7 @@ export class LeaderboardComponent implements OnInit { } } - handleLeaderboardOptionChange(type: LeaderboardCategory) { + handleLeaderboardOptionChange(type: LeaderboardCategory): void { if (!this.isPageLoading) { this.pageOffset = 0; this.leaderbooardSelectedCategory = type; @@ -70,32 +70,32 @@ export class LeaderboardComponent implements OnInit { } } - handleToggleOption() { + handleToggleOption(): void { this.isPageLimitOptionOpen = !this.isPageLimitOptionOpen; } - handleToggleSortOption() { + handleToggleSortOption(): void { this.isPageSortOptionOpen = !this.isPageSortOptionOpen; } - handlePageLimitChange(limit: number) { + handlePageLimitChange(limit: number): void { this.pageLimit = limit; this.pageOffset = 0; this.fetchLHLeaderboard(); this.handleToggleOption(); } - handleNextPageClick() { + handleNextPageClick(): void { this.pageOffset += this.pageLimit; this.fetchLHLeaderboard(); } - handlePrevPageClick() { + handlePrevPageClick(): void { this.pageOffset -= this.pageLimit; this.fetchLHLeaderboard(); } - handleSortDirChange(dir: Sort) { + handleSortDirChange(dir: Sort): void { this.pageOffset = 0; this.leaderboardSelectedSortOrder = dir; this.fetchLHLeaderboard(); diff --git a/packages/lighthouse-spa/src/app/playground/components/home/home.component.ts b/packages/lighthouse-spa/src/app/playground/components/home/home.component.ts index f0713cc79..bd5ccce47 100644 --- a/packages/lighthouse-spa/src/app/playground/components/home/home.component.ts +++ b/packages/lighthouse-spa/src/app/playground/components/home/home.component.ts @@ -96,17 +96,17 @@ export class HomeComponent implements OnInit { return window?.OpAuthHelper?.getUserInfo(); } - scrollBottom = () => { + scrollBottom = (): void => { document .querySelector('#codeBlock') .scrollTo(0, document.querySelector('#codeBlock').scrollHeight); }; - validateUrl = (url: string) => { + validateUrl = (url: string): void => { this.validUrl = url.indexOf('http://') == 0 || url.indexOf('https://') == 0; }; - fetchProjectDetails = () => { + fetchProjectDetails = (): void => { if (this.property.buildToken) { this.appService .fetchProjectDetails( @@ -131,7 +131,7 @@ export class HomeComponent implements OnInit { } }; - updateProgress = () => { + updateProgress = (): void => { this.appService.autorun().subscribe((progress: string) => { if (progress.substr(0, this.auditId.length) === this.auditId) { if (progress.replace(this.auditId, '')) { @@ -167,7 +167,7 @@ export class HomeComponent implements OnInit { return replacedText; }; - auditWebsite = () => { + auditWebsite = (): void => { this.auditProgress = ``; this.loading = true; this.showScore = false; @@ -183,7 +183,7 @@ export class HomeComponent implements OnInit { }); }; - fetchScore = (auditId) => { + fetchScore = (auditId): void => { this.appService.fetchScore(auditId).then((responses) => { this.showScore = true; const scores = responses.reduce((acc, val) => { @@ -215,13 +215,13 @@ export class HomeComponent implements OnInit { }); }; - fetchProjects = () => { + fetchProjects = (): void => { this.appService.fetchProjects().then((responses) => { this.projects = responses.listLHProjects.rows; }); }; - fetchProjectBranches = () => { + fetchProjectBranches = (): void => { if (this.projectID) { this.appService.fetchProjectBranches(this.projectID).then((responses) => { this.projectBranches = responses.listLHProjectBranches.rows; @@ -229,7 +229,7 @@ export class HomeComponent implements OnInit { } }; - upload = (property) => { + upload = (property): void => { const uploadProperty = { auditId: this.auditId, serverBaseUrl: environment.LH_SERVER_URL, diff --git a/packages/lighthouse-spa/src/app/shared/components/avatar/avatar.component.ts b/packages/lighthouse-spa/src/app/shared/components/avatar/avatar.component.ts index 3f7dbaa6d..cedc387dd 100644 --- a/packages/lighthouse-spa/src/app/shared/components/avatar/avatar.component.ts +++ b/packages/lighthouse-spa/src/app/shared/components/avatar/avatar.component.ts @@ -19,7 +19,7 @@ export class AvatarComponent implements OnInit { /** * Ref: https://medium.com/@pppped/compute-an-arbitrary-color-for-user-avatar-starting-from-his-username-with-javascript-cd0675943b66 */ - generatorFillColor(str: string, s: number, l: number) { + generatorFillColor(str: string, s: number, l: number): string { let hash = 0; for (var i = 0; i < str.length; i++) { hash = str.charCodeAt(i) + ((hash << 5) - hash); diff --git a/packages/lighthouse-spa/src/app/shared/components/context-selector/context-selector.component.ts b/packages/lighthouse-spa/src/app/shared/components/context-selector/context-selector.component.ts index 19cc8b4c4..b070fc0a5 100644 --- a/packages/lighthouse-spa/src/app/shared/components/context-selector/context-selector.component.ts +++ b/packages/lighthouse-spa/src/app/shared/components/context-selector/context-selector.component.ts @@ -20,15 +20,15 @@ export class ContextSelectorComponent implements OnInit { ngOnInit(): void {} - onToggle() { + onToggle(): void { this.onToggleEvent.emit(!this.isOpen); } - onSearchButtonClick() { + onSearchButtonClick(): void { this.onSearchButtonClickEvent.emit(this.searchInputValue); } - onSearchInputChange(event: Event) { + onSearchInputChange(event: Event): void { const inputElementValue = (event.target as HTMLInputElement).value; this.onSearchInputChangeEvent.emit(inputElementValue); } diff --git a/packages/lighthouse-spa/src/app/shared/components/outlined-pie-graph/outlined-pie-graph.component.ts b/packages/lighthouse-spa/src/app/shared/components/outlined-pie-graph/outlined-pie-graph.component.ts index f3b2a0575..d787a6c1c 100644 --- a/packages/lighthouse-spa/src/app/shared/components/outlined-pie-graph/outlined-pie-graph.component.ts +++ b/packages/lighthouse-spa/src/app/shared/components/outlined-pie-graph/outlined-pie-graph.component.ts @@ -11,7 +11,7 @@ export class OutlinedPieGraphComponent implements OnInit { @Input() name = ''; ngOnInit(): void {} - getType() { + getType(): string | string | string { if (this.score >= 0 && this.score <= 49) { return 'low'; } else if (this.score >= 50 && this.score <= 89) { diff --git a/packages/lighthouse-spa/src/app/shared/layouts/app-layout/app-layout.component.ts b/packages/lighthouse-spa/src/app/shared/layouts/app-layout/app-layout.component.ts index 6443c7f98..65960f609 100644 --- a/packages/lighthouse-spa/src/app/shared/layouts/app-layout/app-layout.component.ts +++ b/packages/lighthouse-spa/src/app/shared/layouts/app-layout/app-layout.component.ts @@ -35,7 +35,7 @@ export class AppLayoutComponent implements OnInit { return baseUrl === url; } - handleComingSoon() { + handleComingSoon(): void { window.OpNotification?.info({ subject: 'Coming soon...' }); } } diff --git a/packages/notification-spa/src/app/graphql.module.ts b/packages/notification-spa/src/app/graphql.module.ts index 8385683e5..9131d6418 100644 --- a/packages/notification-spa/src/app/graphql.module.ts +++ b/packages/notification-spa/src/app/graphql.module.ts @@ -8,7 +8,9 @@ import { environment } from 'src/environments/environment'; const uri = environment.API_URL; -export function provideApollo(httpLink: HttpLink) { +export function provideApollo(httpLink: HttpLink): {link: error; +cache: error; +} { const basic = setContext((operation, context) => ({ headers: { Accept: 'charset=utf-8' diff --git a/packages/notification-spa/src/app/index/spa-notifications-list/spa-notifications-list.component.ts b/packages/notification-spa/src/app/index/spa-notifications-list/spa-notifications-list.component.ts index a62780ce8..cff1e9ff4 100644 --- a/packages/notification-spa/src/app/index/spa-notifications-list/spa-notifications-list.component.ts +++ b/packages/notification-spa/src/app/index/spa-notifications-list/spa-notifications-list.component.ts @@ -25,7 +25,7 @@ export class SpaNotificationsListComponent implements OnInit { }); } - deleteConfig(config) { + deleteConfig(config): void { this.appService.deleteNotificationConfig(config?.id).subscribe(data => { this.notificationInformation = { ...this.notificationInformation, @@ -35,7 +35,7 @@ export class SpaNotificationsListComponent implements OnInit { }); } - viewMore(index) { + viewMore(index): void { if (this.visibleIndex === index) { this.visibleIndex = -1; } else { diff --git a/packages/notification-spa/src/app/manage-notification/manage-notification.component.ts b/packages/notification-spa/src/app/manage-notification/manage-notification.component.ts index d20ab6cb9..a9f3d430e 100644 --- a/packages/notification-spa/src/app/manage-notification/manage-notification.component.ts +++ b/packages/notification-spa/src/app/manage-notification/manage-notification.component.ts @@ -47,7 +47,7 @@ export class ManageNotificationComponent implements OnInit { * This is a on Submit handler to create or update notification config * @param formData Form data */ - onSubmit(formData) { + onSubmit(formData): void { this.notificationFormData = { source: this.applicationName, channel: formData.channel, @@ -89,17 +89,17 @@ export class ManageNotificationComponent implements OnInit { } } - addRoverGroup(roverGroup) { + addRoverGroup(roverGroup): void { if (roverGroup !== '') { this.targets.push(roverGroup.trim().replace(/ /g, '-')); } } - removeTarget(roverGroup) { + removeTarget(roverGroup): void { this.targets = this.targets.filter(group => group !== roverGroup); } - editConfig(id) { + editConfig(id): void { this.appService.getNotificationConfigBy({ id }).then((data: NotificationConfig[]) => { this.notificationID = data[0].id; this.channel = data[0].channel; diff --git a/packages/opc-base/src/components/opc-loader/opc-loader.ts b/packages/opc-base/src/components/opc-loader/opc-loader.ts index ea50d0fbf..1c06f4c90 100644 --- a/packages/opc-base/src/components/opc-loader/opc-loader.ts +++ b/packages/opc-base/src/components/opc-loader/opc-loader.ts @@ -10,7 +10,7 @@ export class OpcLoader extends LitElement { @property({ type: Boolean }) hidden = false; // to avoid overflow scroll - willUpdate(changedProperties: Map) { + willUpdate(changedProperties: Map): void { if (changedProperties.has("hidden")) { document.body.style.overflowY = this.hidden ? "auto" : "hidden"; } diff --git a/packages/opc-base/src/keycloakAuthProvider/keycloakAuthProvider.ts b/packages/opc-base/src/keycloakAuthProvider/keycloakAuthProvider.ts index 869cbcb3d..a86efc79a 100644 --- a/packages/opc-base/src/keycloakAuthProvider/keycloakAuthProvider.ts +++ b/packages/opc-base/src/keycloakAuthProvider/keycloakAuthProvider.ts @@ -66,7 +66,7 @@ export class OpKeycloakAuthProvider { * * @param {(user) => void} callback */ - onLogin(callback: UserInfoFn) { + onLogin(callback: UserInfoFn): void { /* If the user is already authenticated, then call the callback immediately */ if (this.isAuthenticated) { callback(this.getUserInfo()); @@ -78,7 +78,7 @@ export class OpKeycloakAuthProvider { /** * Logs the user out, and removes all user and token data from the localStorage and cookies */ - logout() { + logout(): void { this._keycloak.logout(); } @@ -89,7 +89,7 @@ export class OpKeycloakAuthProvider { return this._keycloak.authenticated; } - saveTokens() { + saveTokens(): void { localStorage.setItem( LocalStorageCreds.LoginToken, this._keycloak.token || "" @@ -143,7 +143,7 @@ export class OpKeycloakAuthProvider { /** * Removes any garbage hashes from the page URL */ - _removeHashes() { + _removeHashes(): void { window.location.hash = window.location.hash.replace( "#not-before-policy=0", "" diff --git a/packages/opc-base/src/opc-provider/opc-provider.helper.ts b/packages/opc-base/src/opc-provider/opc-provider.helper.ts index f2ea1b1ac..67ccc2910 100644 --- a/packages/opc-base/src/opc-provider/opc-provider.helper.ts +++ b/packages/opc-base/src/opc-provider/opc-provider.helper.ts @@ -1,6 +1,6 @@ import { Notification } from "./types"; -export const getNotificationAppCount = (notifications: Notification[]) => { +export const getNotificationAppCount = (notifications: Notification[]): Record => { return notifications.reduce>((prev, current) => { if (current?.app) { prev[current.app] = (prev?.[current.app] || 0) + 1; diff --git a/packages/opc-base/src/opc-provider/opc-provider.ts b/packages/opc-base/src/opc-provider/opc-provider.ts index 14418a971..7f5579b40 100644 --- a/packages/opc-base/src/opc-provider/opc-provider.ts +++ b/packages/opc-base/src/opc-provider/opc-provider.ts @@ -341,7 +341,7 @@ export class OpcProvider extends LitElement { showToast( notification: Notification, options: ToastOptions = { variant: "info" } - ) { + ): void { if (!notification.sentOn) { notification.sentOn = dayjs().toISOString(); } @@ -453,7 +453,7 @@ export class OpcProvider extends LitElement { * Will update is used for derived propery calculation * notification -> app count is recomputed on notification state change */ - willUpdate(changedProperties: any) { + willUpdate(changedProperties: any): void { // only need to check changed properties for an expensive computation. if ( changedProperties.has("notifications") || diff --git a/packages/reverse-proxy-service/src/couchdb/resolver.ts b/packages/reverse-proxy-service/src/couchdb/resolver.ts index f2946ba9e..fb551afb7 100644 --- a/packages/reverse-proxy-service/src/couchdb/resolver.ts +++ b/packages/reverse-proxy-service/src/couchdb/resolver.ts @@ -5,7 +5,7 @@ import { COUCHDB_HOST, COUCHDB_SECRET } from '../config/env'; const useSecureSSL = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0'; -export default function resolver ( req: Request, res: Response, next: NextFunction ) { +export default function resolver ( req: Request, res: Response, next: NextFunction ): void { const { uid, role, rhatUUID } = res.locals.user; /* Adding additional roles */ diff --git a/packages/reverse-proxy-service/src/middleware/jwtAuth.ts b/packages/reverse-proxy-service/src/middleware/jwtAuth.ts index b4b401767..5f84c36f2 100644 --- a/packages/reverse-proxy-service/src/middleware/jwtAuth.ts +++ b/packages/reverse-proxy-service/src/middleware/jwtAuth.ts @@ -1,7 +1,7 @@ import { NextFunction, Request, Response } from 'express'; import { verifyJwtToken } from '../utils/verifyJwtToken'; -const jwtAuth = ( req: Request, res: Response, next: NextFunction ) => { +const jwtAuth = ( req: Request, res: Response, next: NextFunction ): void => { try { if ( !req.headers?.authorization ) { throw new Error( 'Request is not authenticated' ); diff --git a/packages/reverse-proxy-service/src/utils/setupJest.ts b/packages/reverse-proxy-service/src/utils/setupJest.ts index 7295dbd28..d9677fda9 100644 --- a/packages/reverse-proxy-service/src/utils/setupJest.ts +++ b/packages/reverse-proxy-service/src/utils/setupJest.ts @@ -9,7 +9,7 @@ export function startServer () { return server; } -export function stopServer () { +export function stopServer (): void { if ( server ) { server.close(); } diff --git a/packages/search-service/src/search-mapping/resolver.ts b/packages/search-service/src/search-mapping/resolver.ts index a8c5992d9..5aafc0f37 100644 --- a/packages/search-service/src/search-mapping/resolver.ts +++ b/packages/search-service/src/search-mapping/resolver.ts @@ -9,7 +9,7 @@ export const SearchMapResolver = { getSearchMap(root: any, args: any, ctx: any) { return SearchMap.findById(args._id).exec(); }, - triggerSearchMap ( root: any, args: any, ctx: any ) { + triggerSearchMap ( root: any, args: any, ctx: any ): string { const searchMapCron = new SearchMapCron(); searchMapCron.searchMapTrigger(); return 'Indexing Search Maps has been triggered.'; diff --git a/packages/search-spa/src/app/search/search.component.ts b/packages/search-spa/src/app/search/search.component.ts index e50788920..72113fbcf 100644 --- a/packages/search-spa/src/app/search/search.component.ts +++ b/packages/search-spa/src/app/search/search.component.ts @@ -59,7 +59,7 @@ export class SearchComponent implements OnInit { } ); } - generateAppFilter = () => { + generateAppFilter = (): void => { this.appsStats = []; this.searchResults?.response?.docs?.map( res => { this.appsStats.push( res.content_type ); @@ -82,7 +82,7 @@ export class SearchComponent implements OnInit { await this.generateAppFilter(); } - selectedApps = () => { + selectedApps = (): void => { this.filteredApps = _.compact( this.appsList.map( app => { if ( app.selected ) { return app.content_type; @@ -90,7 +90,7 @@ export class SearchComponent implements OnInit { } ) ); } - orderFilter = ( orderType: string, orderName: string ) => { + orderFilter = ( orderType: string, orderName: string ): void => { this.selectedOrderName = orderName; if ( orderType === 'desc' ) { this.sortOrder = '-createdDate'; @@ -99,7 +99,7 @@ export class SearchComponent implements OnInit { } } - openFeedbackPanel = () => { + openFeedbackPanel = (): void => { ( document as any ).querySelector( 'opc-feedback' ).toggle(); } } diff --git a/packages/user-group-service/src/api-keys/resolver.ts b/packages/user-group-service/src/api-keys/resolver.ts index acc170ea1..5fe30ebb3 100644 --- a/packages/user-group-service/src/api-keys/resolver.ts +++ b/packages/user-group-service/src/api-keys/resolver.ts @@ -89,7 +89,7 @@ export const APIKeysResolver = { } }, APIKeyOwner: { - __resolveType ( owner: any ) { + __resolveType ( owner: any ): string | string { /* WKRD: Find a better identifier to differentiate UserType and Group */ if ( !owner.rhatUUID ) { return 'Group'; diff --git a/packages/user-group-service/src/users/cron.ts b/packages/user-group-service/src/users/cron.ts index 63b0b4a9c..7d904bb83 100644 --- a/packages/user-group-service/src/users/cron.ts +++ b/packages/user-group-service/src/users/cron.ts @@ -7,7 +7,7 @@ import { isEmpty } from 'lodash'; * @class UserSyncCron */ export class UserSyncCron { - public syncUsers() { + public syncUsers(): void { Users.find().then((userInfo: any) => { if ( userInfo.length ) { const rhatUuids = userInfo.map( ( user: any ) => user.rhatUuid ); From 6947417275dadbc3afb191d3d0f5f6e8db375f8a Mon Sep 17 00:00:00 2001 From: "deepsource-autofix[bot]" <62050782+deepsource-autofix[bot]@users.noreply.github.com> Date: Wed, 29 Sep 2021 18:19:52 +0000 Subject: [PATCH 2/2] Format code with black, yapf, autopep8, isort, standardjs, prettier and google-java-format --- .../src/shared/cron/index.ts | 56 ++++----- .../api-catalog-spa/src/reportWebVitals.ts | 6 +- .../src/utils/unique-id-from-path.ts | 19 +-- .../src/hooks/useAppAPI.ts | 40 ++++--- .../src/hooks/useFeedbackConfig.ts | 51 ++++---- .../src/hooks/useLighthouseConfig.ts | 47 ++++---- .../src/hooks/useMyAppsAPI.ts | 35 +++--- .../src/reportWebVitals.ts | 6 +- .../src/audit-manager/resolver.ts | 56 ++++----- .../pages/analysis/analysis.component.ts | 6 +- .../dashboard/pages/home/home.component.ts | 8 +- .../leaderboard/leaderboard.component.ts | 16 +-- .../components/home/home.component.ts | 18 +-- .../components/avatar/avatar.component.ts | 2 +- .../context-selector.component.ts | 6 +- .../outlined-pie-graph.component.ts | 2 +- .../app-layout/app-layout.component.ts | 2 +- .../src/app/graphql.module.ts | 47 ++++---- .../spa-notifications-list.component.ts | 34 +++--- .../manage-notification.component.ts | 103 +++++++++------- .../src/components/opc-loader/opc-loader.ts | 2 +- .../keycloakAuthProvider.ts | 8 +- .../src/opc-provider/opc-provider.helper.ts | 4 +- .../opc-base/src/opc-provider/opc-provider.ts | 4 +- .../src/couchdb/resolver.ts | 44 +++---- .../src/middleware/jwtAuth.ts | 28 ++--- .../src/utils/setupJest.ts | 14 +-- .../src/search-mapping/resolver.ts | 62 +++++----- .../src/app/search/search.component.ts | 112 ++++++++++-------- .../src/api-keys/resolver.ts | 109 ++++++++--------- packages/user-group-service/src/users/cron.ts | 57 +++++---- 31 files changed, 520 insertions(+), 484 deletions(-) diff --git a/packages/api-catalog-service/src/shared/cron/index.ts b/packages/api-catalog-service/src/shared/cron/index.ts index cf403f662..a200b2938 100644 --- a/packages/api-catalog-service/src/shared/cron/index.ts +++ b/packages/api-catalog-service/src/shared/cron/index.ts @@ -1,35 +1,35 @@ -import { Agenda } from 'agenda'; -import database from '../../setup/database'; -import { MONGO_URL } from '../../setup/env'; -import { checkAPIHash } from './cron'; +import { Agenda } from "agenda"; +import database from "../../setup/database"; +import { MONGO_URL } from "../../setup/env"; +import { checkAPIHash } from "./cron"; export let agenda: Agenda; -export default function initializeAgenda (): void { - console.info( 'SETUP - Agenda for cron scripts..' ); - agenda = new Agenda( { - db: { - address: MONGO_URL - }, - defaultConcurrency: 1 - } ); +export default function initializeAgenda(): void { + console.info("SETUP - Agenda for cron scripts.."); + agenda = new Agenda({ + db: { + address: MONGO_URL, + }, + defaultConcurrency: 1, + }); - agenda.define( 'api-sync-hash', async ( job: any ) => { - await checkAPIHash(); - } ); + agenda.define("api-sync-hash", async (job: any) => { + await checkAPIHash(); + }); - agenda.on( 'ready', () => { - /* Start the agenda */ - agenda.start(); - /* Schedule the jobs */ - agenda.every( '6 hours', 'api-sync-hash' ); - } ); + agenda.on("ready", () => { + /* Start the agenda */ + agenda.start(); + /* Schedule the jobs */ + agenda.every("6 hours", "api-sync-hash"); + }); } -if ( require.main === module ) { - ( async () => { - /* Setup database connection */ - await database(); - /* Setup agenda */ - initializeAgenda(); - } )(); +if (require.main === module) { + (async () => { + /* Setup database connection */ + await database(); + /* Setup agenda */ + initializeAgenda(); + })(); } diff --git a/packages/api-catalog-spa/src/reportWebVitals.ts b/packages/api-catalog-spa/src/reportWebVitals.ts index d22630b84..41784a366 100644 --- a/packages/api-catalog-spa/src/reportWebVitals.ts +++ b/packages/api-catalog-spa/src/reportWebVitals.ts @@ -1,8 +1,8 @@ -import { ReportHandler } from 'web-vitals'; +import { ReportHandler } from "web-vitals"; -const reportWebVitals = (onPerfEntry?: ReportHandler): void => { +const reportWebVitals = (onPerfEntry?: ReportHandler): void => { if (onPerfEntry && onPerfEntry instanceof Function) { - import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { + import("web-vitals").then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { getCLS(onPerfEntry); getFID(onPerfEntry); getFCP(onPerfEntry); diff --git a/packages/apps-service/src/utils/unique-id-from-path.ts b/packages/apps-service/src/utils/unique-id-from-path.ts index b635781b4..a5695901f 100644 --- a/packages/apps-service/src/utils/unique-id-from-path.ts +++ b/packages/apps-service/src/utils/unique-id-from-path.ts @@ -1,9 +1,12 @@ -export default function uniqueIdFromPath ( path: string ): string { - return path.toLowerCase() - /* Replace any special characters with `-` */ - .replace( /[\ \-\/\:\@\[\]\`\{\~\.]+/g, '-' ) - /* Remove any starting or ending `-` */ - .replace( /^-+|-+$/g, '' ) - /* Removing multiple consecutive `-`s */ - .replace( /--+/g, '-' ); +export default function uniqueIdFromPath(path: string): string { + return ( + path + .toLowerCase() + /* Replace any special characters with `-` */ + .replace(/[\ \-\/\:\@\[\]\`\{\~\.]+/g, "-") + /* Remove any starting or ending `-` */ + .replace(/^-+|-+$/g, "") + /* Removing multiple consecutive `-`s */ + .replace(/--+/g, "-") + ); } diff --git a/packages/developer-console-spa/src/hooks/useAppAPI.ts b/packages/developer-console-spa/src/hooks/useAppAPI.ts index 3215177a1..4c9fb6d28 100644 --- a/packages/developer-console-spa/src/hooks/useAppAPI.ts +++ b/packages/developer-console-spa/src/hooks/useAppAPI.ts @@ -1,32 +1,34 @@ -import { useEffect, useState } from 'react'; -import { appByAppId } from '../utils/gql-queries/app-by-appid'; -import gqlClient from '../utils/gqlClient'; +import { useEffect, useState } from "react"; +import { appByAppId } from "../utils/gql-queries/app-by-appid"; +import gqlClient from "../utils/gqlClient"; -export default function useAppAPI ( appId: string ): {app: error; -loading: error; -setApp: error; -} { - const [ app, setApp ] = useState( {} ); - const [ loading, setLoading ] = useState( true ); +export default function useAppAPI(appId: string): { + app: error; + loading: error; + setApp: error; +} { + const [app, setApp] = useState({}); + const [loading, setLoading] = useState(true); - useEffect( () => { + useEffect(() => { const abortController = new AbortController(); const signal = abortController.signal; - setLoading( true ); + setLoading(true); - gqlClient( { query: appByAppId, variables: { appId } }, signal ) - .then( res => { - if ( !res?.data?.app ) { - setLoading( false ); + gqlClient({ query: appByAppId, variables: { appId } }, signal).then( + (res) => { + if (!res?.data?.app) { + setLoading(false); return; } - setApp( res.data.app ); - setLoading( false ); - } ); + setApp(res.data.app); + setLoading(false); + } + ); return () => abortController.abort(); - }, [ appId ] ); + }, [appId]); return { app, loading, setApp }; } diff --git a/packages/developer-console-spa/src/hooks/useFeedbackConfig.ts b/packages/developer-console-spa/src/hooks/useFeedbackConfig.ts index 33922b182..ed7fa49e2 100644 --- a/packages/developer-console-spa/src/hooks/useFeedbackConfig.ts +++ b/packages/developer-console-spa/src/hooks/useFeedbackConfig.ts @@ -1,41 +1,42 @@ -import { useEffect, useState } from 'react'; -import { appFeedbackConfig } from '../utils/gql-queries'; -import gqlClient from '../utils/gqlClient'; +import { useEffect, useState } from "react"; +import { appFeedbackConfig } from "../utils/gql-queries"; +import gqlClient from "../utils/gqlClient"; -export default function useFeedbackConfig ( appId: string ): {feedbackConfig: error; -setFeedbackConfig: error; -loading: error; -} { - const [ feedbackConfig, setFeedbackConfig ] = useState( {} ); - const [ loading, setLoading ] = useState( true ); +export default function useFeedbackConfig(appId: string): { + feedbackConfig: error; + setFeedbackConfig: error; + loading: error; +} { + const [feedbackConfig, setFeedbackConfig] = useState({}); + const [loading, setLoading] = useState(true); - useEffect( () => { - if ( !appId ) { + useEffect(() => { + if (!appId) { return; } const abortController = new AbortController(); const signal = abortController.signal; - setLoading( true ); + setLoading(true); - gqlClient( { query: appFeedbackConfig, variables: { appId } }, signal ) - .then( res => { - if ( !res || !res.data ) { - setLoading( false ); + gqlClient({ query: appFeedbackConfig, variables: { appId } }, signal) + .then((res) => { + if (!res || !res.data) { + setLoading(false); return; } - setFeedbackConfig( res.data.app?.feedback ?? {} ); - setLoading( false ); - } ) - .catch( err => { - window.OpNotification?.danger( { - subject: 'There was some error fetching feedback configuration.', - body: 'Please try again later.' - } ); + setFeedbackConfig(res.data.app?.feedback ?? {}); + setLoading(false); + }) + .catch((err) => { + window.OpNotification?.danger({ + subject: "There was some error fetching feedback configuration.", + body: "Please try again later.", + }); }); return () => abortController.abort(); - }, [ appId ] ); + }, [appId]); return { feedbackConfig, setFeedbackConfig, loading }; } diff --git a/packages/developer-console-spa/src/hooks/useLighthouseConfig.ts b/packages/developer-console-spa/src/hooks/useLighthouseConfig.ts index e2c178a66..96e3ad76c 100644 --- a/packages/developer-console-spa/src/hooks/useLighthouseConfig.ts +++ b/packages/developer-console-spa/src/hooks/useLighthouseConfig.ts @@ -1,37 +1,38 @@ -import { useEffect, useState } from 'react'; -import { getLHSpaConfigByAppId } from '../services/lighthouse'; +import { useEffect, useState } from "react"; +import { getLHSpaConfigByAppId } from "../services/lighthouse"; -export default function useLighthouseConfig ( id: string ): {lighthouseConfig: error; -setLighthouseConfig: error; -loading: error; -} { - const [ lighthouseConfig, setLighthouseConfig ] = useState( {} ); - const [ loading, setLoading ] = useState( true ); +export default function useLighthouseConfig(id: string): { + lighthouseConfig: error; + setLighthouseConfig: error; + loading: error; +} { + const [lighthouseConfig, setLighthouseConfig] = useState({}); + const [loading, setLoading] = useState(true); - useEffect( () => { - if ( !id ) { + useEffect(() => { + if (!id) { return; } const abortController = new AbortController(); const signal = abortController.signal; - setLoading( true ); + setLoading(true); - getLHSpaConfigByAppId( id, signal ) - .then( res => { - setLighthouseConfig( res || {} ); - setLoading( false ); - } ) - .catch( err => { - setLoading( false ); - window.OpNotification?.danger( { - subject: 'There was some error fetching lighthouse configuration.', - body: 'Please try again later.' - } ); + getLHSpaConfigByAppId(id, signal) + .then((res) => { + setLighthouseConfig(res || {}); + setLoading(false); + }) + .catch((err) => { + setLoading(false); + window.OpNotification?.danger({ + subject: "There was some error fetching lighthouse configuration.", + body: "Please try again later.", + }); }); return () => abortController.abort(); - }, [ id ] ); + }, [id]); return { lighthouseConfig, setLighthouseConfig, loading }; } diff --git a/packages/developer-console-spa/src/hooks/useMyAppsAPI.ts b/packages/developer-console-spa/src/hooks/useMyAppsAPI.ts index 52c5d801c..c414b2e7f 100644 --- a/packages/developer-console-spa/src/hooks/useMyAppsAPI.ts +++ b/packages/developer-console-spa/src/hooks/useMyAppsAPI.ts @@ -1,29 +1,26 @@ -import { useEffect, useState } from 'react'; -import { myApps } from '../utils/gql-queries'; -import gqlClient from '../utils/gqlClient'; +import { useEffect, useState } from "react"; +import { myApps } from "../utils/gql-queries"; +import gqlClient from "../utils/gqlClient"; -export default function useMyAppsAPI (): {apps: error; -loading: error; -} { - const [ apps, setApps ] = useState( [] ); - const [ loading, setLoading ] = useState( true ); +export default function useMyAppsAPI(): { apps: error; loading: error } { + const [apps, setApps] = useState([]); + const [loading, setLoading] = useState(true); - useEffect( () => { + useEffect(() => { const abortController = new AbortController(); const signal = abortController.signal; - gqlClient( { query: myApps }, signal ) - .then( res => { - if ( !res || !res.data ) { - setLoading( false ); - return; - } - setApps( res.data.myApps ); - setLoading( false ); - } ); + gqlClient({ query: myApps }, signal).then((res) => { + if (!res || !res.data) { + setLoading(false); + return; + } + setApps(res.data.myApps); + setLoading(false); + }); return () => abortController.abort(); - }, [] ); + }, []); return { apps, loading }; } diff --git a/packages/developer-console-spa/src/reportWebVitals.ts b/packages/developer-console-spa/src/reportWebVitals.ts index d22630b84..41784a366 100644 --- a/packages/developer-console-spa/src/reportWebVitals.ts +++ b/packages/developer-console-spa/src/reportWebVitals.ts @@ -1,8 +1,8 @@ -import { ReportHandler } from 'web-vitals'; +import { ReportHandler } from "web-vitals"; -const reportWebVitals = (onPerfEntry?: ReportHandler): void => { +const reportWebVitals = (onPerfEntry?: ReportHandler): void => { if (onPerfEntry && onPerfEntry instanceof Function) { - import('web-vitals').then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { + import("web-vitals").then(({ getCLS, getFID, getFCP, getLCP, getTTFB }) => { getCLS(onPerfEntry); getFID(onPerfEntry); getFCP(onPerfEntry); diff --git a/packages/lighthouse-service/src/audit-manager/resolver.ts b/packages/lighthouse-service/src/audit-manager/resolver.ts index fb920f167..5210fc29e 100644 --- a/packages/lighthouse-service/src/audit-manager/resolver.ts +++ b/packages/lighthouse-service/src/audit-manager/resolver.ts @@ -1,16 +1,16 @@ -import { spawn } from 'child_process'; -import { pubsub, lhci } from '../helpers'; -import * as fs from 'fs'; -import { camelCase } from 'lodash'; -import { lhDbManager } from '../lighthouse-db-manager'; +import { spawn } from "child_process"; +import { pubsub, lhci } from "../helpers"; +import * as fs from "fs"; +import { camelCase } from "lodash"; +import { lhDbManager } from "../lighthouse-db-manager"; export const LighthouseAuditResolver = { LHLeaderBoardCategory: { - PWA: 'category_pwa_median', - SEO: 'category_seo_median', - BEST_PRACTICES: 'category_performance_median', - ACCESSIBILITY: 'category_accessibility_median', - PERFORMANCE: 'category_best-practices_median', + PWA: "category_pwa_median", + SEO: "category_seo_median", + BEST_PRACTICES: "category_performance_median", + ACCESSIBILITY: "category_accessibility_median", + PERFORMANCE: "category_best-practices_median", }, Query: { async listLHProjects(root: any, args: any, ctx: any) { @@ -57,7 +57,7 @@ export const LighthouseAuditResolver = { const fileListPromise = new Promise(async (resolve, reject) => { fs.readdir(`/tmp/${args.auditId}/.lighthouseci`, (err, files) => { files.map((file, index) => { - if (file.startsWith('lhr-') && file.endsWith('.json')) { + if (file.startsWith("lhr-") && file.endsWith(".json")) { filePaths.push(`/tmp/${args.auditId}/.lighthouseci/${file}`); } if (files.length - 1 === index) { @@ -75,7 +75,7 @@ export const LighthouseAuditResolver = { )) as any; const fileDataPromise = await new Promise(async (resolve, reject) => { paths.forEach((path, index) => { - fs.readFile(path, 'utf8', (err, data) => { + fs.readFile(path, "utf8", (err, data) => { lhrReports.push(data); if (index === paths.length - 1) { resolve(lhrReports); @@ -102,13 +102,13 @@ export const LighthouseAuditResolver = { }, }, Mutation: { - auditWebsite(root: any, args: any, ctx: any): string { + auditWebsite(root: any, args: any, ctx: any): string { const LHCI_BUILD_CONTEXT__CURRENT_HASH = new Date() .getTime() .toString(16) - .split('') + .split("") .reverse() - .join(''); + .join(""); const lhciScript = spawn( ` cd /tmp && mkdir ${LHCI_BUILD_CONTEXT__CURRENT_HASH} && cd ${LHCI_BUILD_CONTEXT__CURRENT_HASH} && lhci healthcheck && lhci collect --settings.chromeFlags='--no-sandbox --ignore-certificate-errors' --url=${ @@ -120,28 +120,28 @@ export const LighthouseAuditResolver = { shell: true, } ); - lhciScript.stdout.on('data', async (data) => { + lhciScript.stdout.on("data", async (data) => { console.log(data.toString()); pubsub - .publish('AUTORUN', { + .publish("AUTORUN", { autorun: LHCI_BUILD_CONTEXT__CURRENT_HASH + data.toString(), }) .catch((err) => console.error(err)); }); - lhciScript.stderr.on('data', (data) => { + lhciScript.stderr.on("data", (data) => { console.error(data.toString()); pubsub - .publish('AUTORUN', { + .publish("AUTORUN", { autorun: LHCI_BUILD_CONTEXT__CURRENT_HASH + data.toString(), }) .catch((err) => console.error(err)); }); - lhciScript.on('exit', (code) => { + lhciScript.on("exit", (code) => { console.log(`Process exited with code ${code}`); pubsub - .publish('AUTORUN', { + .publish("AUTORUN", { autorun: LHCI_BUILD_CONTEXT__CURRENT_HASH + code, }) .catch((err) => console.error(err)); @@ -173,28 +173,28 @@ export const LighthouseAuditResolver = { shell: true, } ); - lhciScript.stdout.on('data', async (data) => { + lhciScript.stdout.on("data", async (data) => { console.log(data.toString()); pubsub - .publish('AUTORUN', { + .publish("AUTORUN", { autorun: args.property.auditId + data.toString(), }) .catch((err) => console.error(err)); }); - lhciScript.stderr.on('data', (data) => { + lhciScript.stderr.on("data", (data) => { console.error(data.toString()); pubsub - .publish('AUTORUN', { + .publish("AUTORUN", { autorun: args.property.auditId + data.toString(), }) .catch((err) => console.error(err)); }); - lhciScript.on('exit', (code) => { + lhciScript.on("exit", (code) => { console.log(`Process exited with code ${code}`); pubsub - .publish('AUTORUN', { autorun: args.property.auditId + code }) + .publish("AUTORUN", { autorun: args.property.auditId + code }) .catch((err) => console.error(err)); }); return args.property.auditId; @@ -202,7 +202,7 @@ export const LighthouseAuditResolver = { }, Subscription: { autorun: { - subscribe: () => pubsub.asyncIterator('AUTORUN'), + subscribe: () => pubsub.asyncIterator("AUTORUN"), }, }, }; diff --git a/packages/lighthouse-spa/src/app/dashboard/pages/analysis/analysis.component.ts b/packages/lighthouse-spa/src/app/dashboard/pages/analysis/analysis.component.ts index 3343f31df..a0c2c3baa 100644 --- a/packages/lighthouse-spa/src/app/dashboard/pages/analysis/analysis.component.ts +++ b/packages/lighthouse-spa/src/app/dashboard/pages/analysis/analysis.component.ts @@ -124,15 +124,15 @@ export class AnalysisComponent implements OnInit { } // context selector functions - onToggleBranchSelector(isOpen: boolean): void { + onToggleBranchSelector(isOpen: boolean): void { this.isBranchContextSelectorOpen = isOpen; } - onBranchSelectorSearchChange(searchValue: string): void { + onBranchSelectorSearchChange(searchValue: string): void { this.branchContextSelectorSearchValue = searchValue; } - onBranchSelect(branch: string): void { + onBranchSelect(branch: string): void { this.selectedBranch = branch; this.isBranchContextSelectorOpen = false; this.branchContextSelectorSearchValue = ''; diff --git a/packages/lighthouse-spa/src/app/dashboard/pages/home/home.component.ts b/packages/lighthouse-spa/src/app/dashboard/pages/home/home.component.ts index ccf523537..855868652 100644 --- a/packages/lighthouse-spa/src/app/dashboard/pages/home/home.component.ts +++ b/packages/lighthouse-spa/src/app/dashboard/pages/home/home.component.ts @@ -78,15 +78,15 @@ export class HomeComponent implements OnInit { }); } - ngOnDestroy(): void { + ngOnDestroy(): void { this.searchControl.unsubscribe(); } - validateUrl(url: string): void { + validateUrl(url: string): void { this.validUrl = url.indexOf('http://') == 0 || url.indexOf('https://') == 0; } - navigateToReportGeneration(): void { + navigateToReportGeneration(): void { this.router.navigate(['/playground'], { queryParams: { siteUrl: this.sites, @@ -95,7 +95,7 @@ export class HomeComponent implements OnInit { }); } - onSearchChange(event: Event): void { + onSearchChange(event: Event): void { const searchTerm = (event.target as HTMLInputElement).value; this.searchProject = searchTerm; this.searchControl.next(searchTerm); diff --git a/packages/lighthouse-spa/src/app/leaderboard/pages/leaderboard/leaderboard.component.ts b/packages/lighthouse-spa/src/app/leaderboard/pages/leaderboard/leaderboard.component.ts index a13ab31da..19901bed2 100644 --- a/packages/lighthouse-spa/src/app/leaderboard/pages/leaderboard/leaderboard.component.ts +++ b/packages/lighthouse-spa/src/app/leaderboard/pages/leaderboard/leaderboard.component.ts @@ -38,7 +38,7 @@ export class LeaderboardComponent implements OnInit { this.fetchLHLeaderboard(); } - fetchLHLeaderboard(): void { + fetchLHLeaderboard(): void { this.isPageLoading = true; try { @@ -62,7 +62,7 @@ export class LeaderboardComponent implements OnInit { } } - handleLeaderboardOptionChange(type: LeaderboardCategory): void { + handleLeaderboardOptionChange(type: LeaderboardCategory): void { if (!this.isPageLoading) { this.pageOffset = 0; this.leaderbooardSelectedCategory = type; @@ -70,32 +70,32 @@ export class LeaderboardComponent implements OnInit { } } - handleToggleOption(): void { + handleToggleOption(): void { this.isPageLimitOptionOpen = !this.isPageLimitOptionOpen; } - handleToggleSortOption(): void { + handleToggleSortOption(): void { this.isPageSortOptionOpen = !this.isPageSortOptionOpen; } - handlePageLimitChange(limit: number): void { + handlePageLimitChange(limit: number): void { this.pageLimit = limit; this.pageOffset = 0; this.fetchLHLeaderboard(); this.handleToggleOption(); } - handleNextPageClick(): void { + handleNextPageClick(): void { this.pageOffset += this.pageLimit; this.fetchLHLeaderboard(); } - handlePrevPageClick(): void { + handlePrevPageClick(): void { this.pageOffset -= this.pageLimit; this.fetchLHLeaderboard(); } - handleSortDirChange(dir: Sort): void { + handleSortDirChange(dir: Sort): void { this.pageOffset = 0; this.leaderboardSelectedSortOrder = dir; this.fetchLHLeaderboard(); diff --git a/packages/lighthouse-spa/src/app/playground/components/home/home.component.ts b/packages/lighthouse-spa/src/app/playground/components/home/home.component.ts index bd5ccce47..e4446f8a5 100644 --- a/packages/lighthouse-spa/src/app/playground/components/home/home.component.ts +++ b/packages/lighthouse-spa/src/app/playground/components/home/home.component.ts @@ -96,17 +96,17 @@ export class HomeComponent implements OnInit { return window?.OpAuthHelper?.getUserInfo(); } - scrollBottom = (): void => { + scrollBottom = (): void => { document .querySelector('#codeBlock') .scrollTo(0, document.querySelector('#codeBlock').scrollHeight); }; - validateUrl = (url: string): void => { + validateUrl = (url: string): void => { this.validUrl = url.indexOf('http://') == 0 || url.indexOf('https://') == 0; }; - fetchProjectDetails = (): void => { + fetchProjectDetails = (): void => { if (this.property.buildToken) { this.appService .fetchProjectDetails( @@ -131,7 +131,7 @@ export class HomeComponent implements OnInit { } }; - updateProgress = (): void => { + updateProgress = (): void => { this.appService.autorun().subscribe((progress: string) => { if (progress.substr(0, this.auditId.length) === this.auditId) { if (progress.replace(this.auditId, '')) { @@ -167,7 +167,7 @@ export class HomeComponent implements OnInit { return replacedText; }; - auditWebsite = (): void => { + auditWebsite = (): void => { this.auditProgress = ``; this.loading = true; this.showScore = false; @@ -183,7 +183,7 @@ export class HomeComponent implements OnInit { }); }; - fetchScore = (auditId): void => { + fetchScore = (auditId): void => { this.appService.fetchScore(auditId).then((responses) => { this.showScore = true; const scores = responses.reduce((acc, val) => { @@ -215,13 +215,13 @@ export class HomeComponent implements OnInit { }); }; - fetchProjects = (): void => { + fetchProjects = (): void => { this.appService.fetchProjects().then((responses) => { this.projects = responses.listLHProjects.rows; }); }; - fetchProjectBranches = (): void => { + fetchProjectBranches = (): void => { if (this.projectID) { this.appService.fetchProjectBranches(this.projectID).then((responses) => { this.projectBranches = responses.listLHProjectBranches.rows; @@ -229,7 +229,7 @@ export class HomeComponent implements OnInit { } }; - upload = (property): void => { + upload = (property): void => { const uploadProperty = { auditId: this.auditId, serverBaseUrl: environment.LH_SERVER_URL, diff --git a/packages/lighthouse-spa/src/app/shared/components/avatar/avatar.component.ts b/packages/lighthouse-spa/src/app/shared/components/avatar/avatar.component.ts index cedc387dd..086adcaa7 100644 --- a/packages/lighthouse-spa/src/app/shared/components/avatar/avatar.component.ts +++ b/packages/lighthouse-spa/src/app/shared/components/avatar/avatar.component.ts @@ -19,7 +19,7 @@ export class AvatarComponent implements OnInit { /** * Ref: https://medium.com/@pppped/compute-an-arbitrary-color-for-user-avatar-starting-from-his-username-with-javascript-cd0675943b66 */ - generatorFillColor(str: string, s: number, l: number): string { + generatorFillColor(str: string, s: number, l: number): string { let hash = 0; for (var i = 0; i < str.length; i++) { hash = str.charCodeAt(i) + ((hash << 5) - hash); diff --git a/packages/lighthouse-spa/src/app/shared/components/context-selector/context-selector.component.ts b/packages/lighthouse-spa/src/app/shared/components/context-selector/context-selector.component.ts index b070fc0a5..4b9ff9a05 100644 --- a/packages/lighthouse-spa/src/app/shared/components/context-selector/context-selector.component.ts +++ b/packages/lighthouse-spa/src/app/shared/components/context-selector/context-selector.component.ts @@ -20,15 +20,15 @@ export class ContextSelectorComponent implements OnInit { ngOnInit(): void {} - onToggle(): void { + onToggle(): void { this.onToggleEvent.emit(!this.isOpen); } - onSearchButtonClick(): void { + onSearchButtonClick(): void { this.onSearchButtonClickEvent.emit(this.searchInputValue); } - onSearchInputChange(event: Event): void { + onSearchInputChange(event: Event): void { const inputElementValue = (event.target as HTMLInputElement).value; this.onSearchInputChangeEvent.emit(inputElementValue); } diff --git a/packages/lighthouse-spa/src/app/shared/components/outlined-pie-graph/outlined-pie-graph.component.ts b/packages/lighthouse-spa/src/app/shared/components/outlined-pie-graph/outlined-pie-graph.component.ts index d787a6c1c..317cad73b 100644 --- a/packages/lighthouse-spa/src/app/shared/components/outlined-pie-graph/outlined-pie-graph.component.ts +++ b/packages/lighthouse-spa/src/app/shared/components/outlined-pie-graph/outlined-pie-graph.component.ts @@ -11,7 +11,7 @@ export class OutlinedPieGraphComponent implements OnInit { @Input() name = ''; ngOnInit(): void {} - getType(): string | string | string { + getType(): string | string | string { if (this.score >= 0 && this.score <= 49) { return 'low'; } else if (this.score >= 50 && this.score <= 89) { diff --git a/packages/lighthouse-spa/src/app/shared/layouts/app-layout/app-layout.component.ts b/packages/lighthouse-spa/src/app/shared/layouts/app-layout/app-layout.component.ts index 65960f609..e99e0f371 100644 --- a/packages/lighthouse-spa/src/app/shared/layouts/app-layout/app-layout.component.ts +++ b/packages/lighthouse-spa/src/app/shared/layouts/app-layout/app-layout.component.ts @@ -35,7 +35,7 @@ export class AppLayoutComponent implements OnInit { return baseUrl === url; } - handleComingSoon(): void { + handleComingSoon(): void { window.OpNotification?.info({ subject: 'Coming soon...' }); } } diff --git a/packages/notification-spa/src/app/graphql.module.ts b/packages/notification-spa/src/app/graphql.module.ts index 9131d6418..dea8bb9e5 100644 --- a/packages/notification-spa/src/app/graphql.module.ts +++ b/packages/notification-spa/src/app/graphql.module.ts @@ -1,43 +1,44 @@ -import { NgModule } from '@angular/core'; -import { HttpClientModule } from '@angular/common/http'; -import { APOLLO_OPTIONS } from 'apollo-angular'; -import { HttpLink } from 'apollo-angular/http'; -import { InMemoryCache, ApolloLink } from '@apollo/client/core'; -import { setContext } from '@apollo/client/link/context'; -import { environment } from 'src/environments/environment'; +import { NgModule } from "@angular/core"; +import { HttpClientModule } from "@angular/common/http"; +import { APOLLO_OPTIONS } from "apollo-angular"; +import { HttpLink } from "apollo-angular/http"; +import { InMemoryCache, ApolloLink } from "@apollo/client/core"; +import { setContext } from "@apollo/client/link/context"; +import { environment } from "src/environments/environment"; const uri = environment.API_URL; -export function provideApollo(httpLink: HttpLink): {link: error; -cache: error; -} { +export function provideApollo(httpLink: HttpLink): { + link: error; + cache: error; +} { const basic = setContext((operation, context) => ({ headers: { - Accept: 'charset=utf-8' - } + Accept: "charset=utf-8", + }, })); const auth = setContext((operation, context) => ({ headers: { Authorization: window.OpAuthHelper?.jwtToken - ? 'Bearer ' + window.OpAuthHelper.jwtToken - : '', + ? "Bearer " + window.OpAuthHelper.jwtToken + : "", }, })); - const link = ApolloLink.from( [ basic, auth, httpLink.create( { uri } ) ] ); + const link = ApolloLink.from([basic, auth, httpLink.create({ uri })]); const cache = new InMemoryCache(); return { link, - cache + cache, }; } @NgModule({ - exports: [ - HttpClientModule, + exports: [HttpClientModule], + providers: [ + { + provide: APOLLO_OPTIONS, + useFactory: provideApollo, + deps: [HttpLink], + }, ], - providers: [{ - provide: APOLLO_OPTIONS, - useFactory: provideApollo, - deps: [HttpLink] - }] }) export class GraphQLModule {} diff --git a/packages/notification-spa/src/app/index/spa-notifications-list/spa-notifications-list.component.ts b/packages/notification-spa/src/app/index/spa-notifications-list/spa-notifications-list.component.ts index cff1e9ff4..cff66198a 100644 --- a/packages/notification-spa/src/app/index/spa-notifications-list/spa-notifications-list.component.ts +++ b/packages/notification-spa/src/app/index/spa-notifications-list/spa-notifications-list.component.ts @@ -1,10 +1,10 @@ -import { Component, OnInit, Input } from '@angular/core'; -import { AppService } from 'src/app/app.service'; +import { Component, OnInit, Input } from "@angular/core"; +import { AppService } from "src/app/app.service"; @Component({ - selector: 'op-spa-notifications-list', - templateUrl: './spa-notifications-list.component.html', - styleUrls: ['./spa-notifications-list.component.scss'] + selector: "op-spa-notifications-list", + templateUrl: "./spa-notifications-list.component.html", + styleUrls: ["./spa-notifications-list.component.scss"], }) export class SpaNotificationsListComponent implements OnInit { @Input() notificationInformation: any; @@ -12,21 +12,21 @@ export class SpaNotificationsListComponent implements OnInit { toggleViewMore = true; visibleIndex: number; - constructor( - private appService: AppService, - ) {} + constructor(private appService: AppService) {} ngOnInit(): void { - this.appService.getNotificationConfigBy({ source: this.notificationInformation._id }).then(data => { - this.notificationInformation = { - ...this.notificationInformation, - notificationInfo: data, - }; - }); + this.appService + .getNotificationConfigBy({ source: this.notificationInformation._id }) + .then((data) => { + this.notificationInformation = { + ...this.notificationInformation, + notificationInfo: data, + }; + }); } - deleteConfig(config): void { - this.appService.deleteNotificationConfig(config?.id).subscribe(data => { + deleteConfig(config): void { + this.appService.deleteNotificationConfig(config?.id).subscribe((data) => { this.notificationInformation = { ...this.notificationInformation, notificationInfo: data, @@ -35,7 +35,7 @@ export class SpaNotificationsListComponent implements OnInit { }); } - viewMore(index): void { + viewMore(index): void { if (this.visibleIndex === index) { this.visibleIndex = -1; } else { diff --git a/packages/notification-spa/src/app/manage-notification/manage-notification.component.ts b/packages/notification-spa/src/app/manage-notification/manage-notification.component.ts index a9f3d430e..5de1c3312 100644 --- a/packages/notification-spa/src/app/manage-notification/manage-notification.component.ts +++ b/packages/notification-spa/src/app/manage-notification/manage-notification.component.ts @@ -1,12 +1,12 @@ -import { Component, OnInit } from '@angular/core'; -import { AppService } from '../app.service'; -import { UserProfile } from '../helper'; -import { ActivatedRoute, Router } from '@angular/router'; +import { Component, OnInit } from "@angular/core"; +import { AppService } from "../app.service"; +import { UserProfile } from "../helper"; +import { ActivatedRoute, Router } from "@angular/router"; @Component({ - selector: 'op-manage-notification', - templateUrl: './manage-notification.component.html', - styleUrls: ['./manage-notification.component.scss'] + selector: "op-manage-notification", + templateUrl: "./manage-notification.component.html", + styleUrls: ["./manage-notification.component.scss"], }) export class ManageNotificationComponent implements OnInit { user = UserProfile; @@ -26,9 +26,9 @@ export class ManageNotificationComponent implements OnInit { constructor( private appService: AppService, private route: ActivatedRoute, - private router: Router, + private router: Router ) { - this.route.params.subscribe(res => { + this.route.params.subscribe((res) => { // If editID is available then the form is in edit state or else it is in create state if (res?.id) { this.editConfig(res.id); @@ -38,16 +38,17 @@ export class ManageNotificationComponent implements OnInit { } async ngOnInit() { - this.applications = await this.appService.getHomeTypeByUser(this.user?.rhatUUID) - .then(result => result.filter(spa => spa.entityType === 'spa')) - .catch(err => err); + this.applications = await this.appService + .getHomeTypeByUser(this.user?.rhatUUID) + .then((result) => result.filter((spa) => spa.entityType === "spa")) + .catch((err) => err); } /** * This is a on Submit handler to create or update notification config * @param formData Form data */ - onSubmit(formData): void { + onSubmit(formData): void { this.notificationFormData = { source: this.applicationName, channel: formData.channel, @@ -64,50 +65,64 @@ export class ManageNotificationComponent implements OnInit { createdBy: this.user?.rhatUUID, createdOn: new Date().toUTCString(), }; - this.appService.createNotificationConfig(this.notificationFormData).subscribe((result) => { - if (result) { - window.OpNotification.success({subject: 'Notification successfully created'}); - } - }, - (err) => { - window.OpNotification.danger({subject: 'Error', body: err}); - }); + this.appService + .createNotificationConfig(this.notificationFormData) + .subscribe( + (result) => { + if (result) { + window.OpNotification.success({ + subject: "Notification successfully created", + }); + } + }, + (err) => { + window.OpNotification.danger({ subject: "Error", body: err }); + } + ); } else { this.notificationFormData = { ...this.notificationFormData, updatedBy: UserProfile.rhatUUID, updatedOn: new Date().toUTCString(), }; - this.appService.updateNotificationConfig(this.notificationFormData).subscribe(result => { - if (result) { - window.OpNotification.success({subject: 'Notification successfully created'}); - } - }, - (err) => { - window.OpNotification.danger({subject: 'Error', body: err}); - }); + this.appService + .updateNotificationConfig(this.notificationFormData) + .subscribe( + (result) => { + if (result) { + window.OpNotification.success({ + subject: "Notification successfully created", + }); + } + }, + (err) => { + window.OpNotification.danger({ subject: "Error", body: err }); + } + ); } } - addRoverGroup(roverGroup): void { - if (roverGroup !== '') { - this.targets.push(roverGroup.trim().replace(/ /g, '-')); + addRoverGroup(roverGroup): void { + if (roverGroup !== "") { + this.targets.push(roverGroup.trim().replace(/ /g, "-")); } } - removeTarget(roverGroup): void { - this.targets = this.targets.filter(group => group !== roverGroup); + removeTarget(roverGroup): void { + this.targets = this.targets.filter((group) => group !== roverGroup); } - editConfig(id): void { - this.appService.getNotificationConfigBy({ id }).then((data: NotificationConfig[]) => { - this.notificationID = data[0].id; - this.channel = data[0].channel; - this.type = data[0].type; - this.targets = data[0].targets; - this.createdBy = data[0].createdBy; - this.applicationName = (data[0].source as any).name; - return data; - }); + editConfig(id): void { + this.appService + .getNotificationConfigBy({ id }) + .then((data: NotificationConfig[]) => { + this.notificationID = data[0].id; + this.channel = data[0].channel; + this.type = data[0].type; + this.targets = data[0].targets; + this.createdBy = data[0].createdBy; + this.applicationName = (data[0].source as any).name; + return data; + }); } } diff --git a/packages/opc-base/src/components/opc-loader/opc-loader.ts b/packages/opc-base/src/components/opc-loader/opc-loader.ts index 1c06f4c90..da841806d 100644 --- a/packages/opc-base/src/components/opc-loader/opc-loader.ts +++ b/packages/opc-base/src/components/opc-loader/opc-loader.ts @@ -10,7 +10,7 @@ export class OpcLoader extends LitElement { @property({ type: Boolean }) hidden = false; // to avoid overflow scroll - willUpdate(changedProperties: Map): void { + willUpdate(changedProperties: Map): void { if (changedProperties.has("hidden")) { document.body.style.overflowY = this.hidden ? "auto" : "hidden"; } diff --git a/packages/opc-base/src/keycloakAuthProvider/keycloakAuthProvider.ts b/packages/opc-base/src/keycloakAuthProvider/keycloakAuthProvider.ts index a86efc79a..4aa40de0e 100644 --- a/packages/opc-base/src/keycloakAuthProvider/keycloakAuthProvider.ts +++ b/packages/opc-base/src/keycloakAuthProvider/keycloakAuthProvider.ts @@ -66,7 +66,7 @@ export class OpKeycloakAuthProvider { * * @param {(user) => void} callback */ - onLogin(callback: UserInfoFn): void { + onLogin(callback: UserInfoFn): void { /* If the user is already authenticated, then call the callback immediately */ if (this.isAuthenticated) { callback(this.getUserInfo()); @@ -78,7 +78,7 @@ export class OpKeycloakAuthProvider { /** * Logs the user out, and removes all user and token data from the localStorage and cookies */ - logout(): void { + logout(): void { this._keycloak.logout(); } @@ -89,7 +89,7 @@ export class OpKeycloakAuthProvider { return this._keycloak.authenticated; } - saveTokens(): void { + saveTokens(): void { localStorage.setItem( LocalStorageCreds.LoginToken, this._keycloak.token || "" @@ -143,7 +143,7 @@ export class OpKeycloakAuthProvider { /** * Removes any garbage hashes from the page URL */ - _removeHashes(): void { + _removeHashes(): void { window.location.hash = window.location.hash.replace( "#not-before-policy=0", "" diff --git a/packages/opc-base/src/opc-provider/opc-provider.helper.ts b/packages/opc-base/src/opc-provider/opc-provider.helper.ts index 67ccc2910..064b78d8b 100644 --- a/packages/opc-base/src/opc-provider/opc-provider.helper.ts +++ b/packages/opc-base/src/opc-provider/opc-provider.helper.ts @@ -1,6 +1,8 @@ import { Notification } from "./types"; -export const getNotificationAppCount = (notifications: Notification[]): Record => { +export const getNotificationAppCount = ( + notifications: Notification[] +): Record => { return notifications.reduce>((prev, current) => { if (current?.app) { prev[current.app] = (prev?.[current.app] || 0) + 1; diff --git a/packages/opc-base/src/opc-provider/opc-provider.ts b/packages/opc-base/src/opc-provider/opc-provider.ts index 7f5579b40..a4b5d78f4 100644 --- a/packages/opc-base/src/opc-provider/opc-provider.ts +++ b/packages/opc-base/src/opc-provider/opc-provider.ts @@ -341,7 +341,7 @@ export class OpcProvider extends LitElement { showToast( notification: Notification, options: ToastOptions = { variant: "info" } - ): void { + ): void { if (!notification.sentOn) { notification.sentOn = dayjs().toISOString(); } @@ -453,7 +453,7 @@ export class OpcProvider extends LitElement { * Will update is used for derived propery calculation * notification -> app count is recomputed on notification state change */ - willUpdate(changedProperties: any): void { + willUpdate(changedProperties: any): void { // only need to check changed properties for an expensive computation. if ( changedProperties.has("notifications") || diff --git a/packages/reverse-proxy-service/src/couchdb/resolver.ts b/packages/reverse-proxy-service/src/couchdb/resolver.ts index fb551afb7..b6b00b88e 100644 --- a/packages/reverse-proxy-service/src/couchdb/resolver.ts +++ b/packages/reverse-proxy-service/src/couchdb/resolver.ts @@ -1,34 +1,36 @@ -import { createHmac } from 'crypto'; -import { Request, Response, NextFunction } from 'express'; -import { createProxyMiddleware } from 'http-proxy-middleware'; -import { COUCHDB_HOST, COUCHDB_SECRET } from '../config/env'; +import { createHmac } from "crypto"; +import { Request, Response, NextFunction } from "express"; +import { createProxyMiddleware } from "http-proxy-middleware"; +import { COUCHDB_HOST, COUCHDB_SECRET } from "../config/env"; -const useSecureSSL = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== '0'; +const useSecureSSL = process.env.NODE_TLS_REJECT_UNAUTHORIZED !== "0"; -export default function resolver ( req: Request, res: Response, next: NextFunction ): void { +export default function resolver( + req: Request, + res: Response, + next: NextFunction +): void { const { uid, role, rhatUUID } = res.locals.user; /* Adding additional roles */ - role.push( - 'user:' + uid, - 'user:' + rhatUUID, - 'op-users' - ); + role.push("user:" + uid, "user:" + rhatUUID, "op-users"); - const token = createHmac( 'sha1', COUCHDB_SECRET as string ).update( uid ).digest( 'hex' ); + const token = createHmac("sha1", COUCHDB_SECRET as string) + .update(uid) + .digest("hex"); - const proxy = createProxyMiddleware( { + const proxy = createProxyMiddleware({ target: COUCHDB_HOST, secure: useSecureSSL, changeOrigin: true, headers: { - 'X-Auth-CouchDB-UserName': uid, - 'X-Auth-CouchDB-Roles': role.join( ',' ), - 'X-Auth-CouchDB-Token': token, + "X-Auth-CouchDB-UserName": uid, + "X-Auth-CouchDB-Roles": role.join(","), + "X-Auth-CouchDB-Token": token, }, pathRewrite: { - [ '^/api/couchdb' ]: '' - } - } ); - proxy( req, res, next ); -}; + ["^/api/couchdb"]: "", + }, + }); + proxy(req, res, next); +} diff --git a/packages/reverse-proxy-service/src/middleware/jwtAuth.ts b/packages/reverse-proxy-service/src/middleware/jwtAuth.ts index 5f84c36f2..0c0c2fda8 100644 --- a/packages/reverse-proxy-service/src/middleware/jwtAuth.ts +++ b/packages/reverse-proxy-service/src/middleware/jwtAuth.ts @@ -1,27 +1,27 @@ -import { NextFunction, Request, Response } from 'express'; -import { verifyJwtToken } from '../utils/verifyJwtToken'; +import { NextFunction, Request, Response } from "express"; +import { verifyJwtToken } from "../utils/verifyJwtToken"; -const jwtAuth = ( req: Request, res: Response, next: NextFunction ): void => { +const jwtAuth = (req: Request, res: Response, next: NextFunction): void => { try { - if ( !req.headers?.authorization ) { - throw new Error( 'Request is not authenticated' ); + if (!req.headers?.authorization) { + throw new Error("Request is not authenticated"); } const authorization = req.headers.authorization; - const [ authType, token ] = authorization.split( ' ' ); - if ( authType === 'Bearer' ) { - verifyJwtToken( token, ( err: any, tokenParsed: any ) => { - if ( err ) { - throw new Error( err.message ); + const [authType, token] = authorization.split(" "); + if (authType === "Bearer") { + verifyJwtToken(token, (err: any, tokenParsed: any) => { + if (err) { + throw new Error(err.message); } res.locals.user = tokenParsed; res.locals.authenticated = true; next(); - } ); + }); } else { - throw new Error( `Authentication method not supported` ); + throw new Error(`Authentication method not supported`); } - } catch ( err ) { - res.status( 403 ).json( { error: err.message } ); + } catch (err) { + res.status(403).json({ error: err.message }); } }; diff --git a/packages/reverse-proxy-service/src/utils/setupJest.ts b/packages/reverse-proxy-service/src/utils/setupJest.ts index d9677fda9..ef95ae78e 100644 --- a/packages/reverse-proxy-service/src/utils/setupJest.ts +++ b/packages/reverse-proxy-service/src/utils/setupJest.ts @@ -1,16 +1,16 @@ -import { Server } from 'http'; -import app from '../app'; -import { PORT } from '../config/env'; +import { Server } from "http"; +import app from "../app"; +import { PORT } from "../config/env"; let server: Server; -export function startServer () { - server = app.listen( PORT ); +export function startServer() { + server = app.listen(PORT); return server; } -export function stopServer (): void { - if ( server ) { +export function stopServer(): void { + if (server) { server.close(); } } diff --git a/packages/search-service/src/search-mapping/resolver.ts b/packages/search-service/src/search-mapping/resolver.ts index 5aafc0f37..70932631f 100644 --- a/packages/search-service/src/search-mapping/resolver.ts +++ b/packages/search-service/src/search-mapping/resolver.ts @@ -1,32 +1,36 @@ -import { SearchMap } from './schema'; -import { SearchMapCron } from './cron'; +import { SearchMap } from "./schema"; +import { SearchMapCron } from "./cron"; export const SearchMapResolver = { - Query: { - listSearchMap(root: any, args: any, ctx: any) { - return SearchMap.find().exec().then((res: SearchMapMode[]) => res); - }, - getSearchMap(root: any, args: any, ctx: any) { - return SearchMap.findById(args._id).exec(); - }, - triggerSearchMap ( root: any, args: any, ctx: any ): string { - const searchMapCron = new SearchMapCron(); - searchMapCron.searchMapTrigger(); - return 'Indexing Search Maps has been triggered.'; - } + Query: { + listSearchMap(root: any, args: any, ctx: any) { + return SearchMap.find() + .exec() + .then((res: SearchMapMode[]) => res); }, - Mutation: { - async createSearchMap(root: any, args: any, ctx: any) { - const data = new SearchMap(args.input); - return data.save(); - }, - updateSearchMap(root: any, args: any, ctx: any) { - return SearchMap.findByIdAndUpdate( args.input._id, args.input, { new: true } ).exec(); - }, - deleteSearchMap(root: any, args: any, ctx: any) { - return SearchMap.findByIdAndRemove(args._id) - .then((response: any) => response) - .catch((error: Error) => error); - }, - } -} + getSearchMap(root: any, args: any, ctx: any) { + return SearchMap.findById(args._id).exec(); + }, + triggerSearchMap(root: any, args: any, ctx: any): string { + const searchMapCron = new SearchMapCron(); + searchMapCron.searchMapTrigger(); + return "Indexing Search Maps has been triggered."; + }, + }, + Mutation: { + async createSearchMap(root: any, args: any, ctx: any) { + const data = new SearchMap(args.input); + return data.save(); + }, + updateSearchMap(root: any, args: any, ctx: any) { + return SearchMap.findByIdAndUpdate(args.input._id, args.input, { + new: true, + }).exec(); + }, + deleteSearchMap(root: any, args: any, ctx: any) { + return SearchMap.findByIdAndRemove(args._id) + .then((response: any) => response) + .catch((error: Error) => error); + }, + }, +}; diff --git a/packages/search-spa/src/app/search/search.component.ts b/packages/search-spa/src/app/search/search.component.ts index 72113fbcf..b960ea86b 100644 --- a/packages/search-spa/src/app/search/search.component.ts +++ b/packages/search-spa/src/app/search/search.component.ts @@ -3,13 +3,12 @@ import { ActivatedRoute } from '@angular/router'; import * as _ from 'lodash'; import { AppService } from 'src/app/app.service'; -@Component( { +@Component({ selector: 'app-search', templateUrl: './search.component.html', - styleUrls: [ './search.component.scss' ] -} ) + styleUrls: ['./search.component.scss'], +}) export class SearchComponent implements OnInit { - searchResults: SearchResponseType; sliceLimit = 10; appsStats: any[] = []; @@ -24,82 +23,91 @@ export class SearchComponent implements OnInit { appFilterActive = false; appSortActive = false; selectedOrderName = 'Sort'; - sortList = [ { - name: 'Newest First', - filter: 'desc', - }, - { - name: 'Oldest First', - filter: 'asc', - } ]; + sortList = [ + { + name: 'Newest First', + filter: 'desc', + }, + { + name: 'Oldest First', + filter: 'asc', + }, + ]; - constructor( - private appService: AppService, - private route: ActivatedRoute, - ) { - this.route.queryParamMap.subscribe( params => { - this.query = params.get( 'query' ); - } ); + constructor(private appService: AppService, private route: ActivatedRoute) { + this.route.queryParamMap.subscribe((params) => { + this.query = params.get('query'); + }); } async ngOnInit(): Promise { - await this.search( this.query, this.start, this.rows ).then( () => this.loading = false ); + await this.search(this.query, this.start, this.rows).then( + () => (this.loading = false) + ); await this.generateAppFilter(); } - search = ( query, start, rows ) => { + search = (query, start, rows) => { const startTime = new Date().getTime(); - return this.appService.search( query, start, rows ).then( searchResponse => { - this.responseTime = (( new Date().getTime() - startTime ) / 1000).toFixed(2) + ' Seconds'; - if ( !this.searchResults) { + return this.appService.search(query, start, rows).then((searchResponse) => { + this.responseTime = + ((new Date().getTime() - startTime) / 1000).toFixed(2) + ' Seconds'; + if (!this.searchResults) { this.searchResults = searchResponse; } else { - this.searchResults.response.docs = this.searchResults.response.docs.concat( searchResponse.response.docs ); + this.searchResults.response.docs = + this.searchResults.response.docs.concat(searchResponse.response.docs); } - } ); - } + }); + }; - generateAppFilter = (): void => { + generateAppFilter = (): void => { this.appsStats = []; - this.searchResults?.response?.docs?.map( res => { - this.appsStats.push( res.content_type ); - } ); - this.appsList = _.map( _.groupBy( this.appsStats ), ( value, key ): any => { + this.searchResults?.response?.docs?.map((res) => { + this.appsStats.push(res.content_type); + }); + this.appsList = _.map(_.groupBy(this.appsStats), (value, key): any => { return { content_type: key, - icon: this.searchResults?.response?.docs?.filter( res => res?.content_type === key )[ 0 ].icon, + icon: this.searchResults?.response?.docs?.filter( + (res) => res?.content_type === key + )[0].icon, count: value.length, - selected: false + selected: false, }; - } ); + }); this.filteredApps = []; - } + }; showMore = async () => { this.start += this.rows; - await this.search( this.query, this.start, this.rows ).then( () => this.loading = false ); + await this.search(this.query, this.start, this.rows).then( + () => (this.loading = false) + ); this.sliceLimit = this.start + this.rows; await this.generateAppFilter(); - } + }; - selectedApps = (): void => { - this.filteredApps = _.compact( this.appsList.map( app => { - if ( app.selected ) { - return app.content_type; - } - } ) ); - } + selectedApps = (): void => { + this.filteredApps = _.compact( + this.appsList.map((app) => { + if (app.selected) { + return app.content_type; + } + }) + ); + }; - orderFilter = ( orderType: string, orderName: string ): void => { + orderFilter = (orderType: string, orderName: string): void => { this.selectedOrderName = orderName; - if ( orderType === 'desc' ) { + if (orderType === 'desc') { this.sortOrder = '-createdDate'; - } else if ( orderType === 'asc' ) { + } else if (orderType === 'asc') { this.sortOrder = 'createdDate'; } - } + }; - openFeedbackPanel = (): void => { - ( document as any ).querySelector( 'opc-feedback' ).toggle(); - } + openFeedbackPanel = (): void => { + (document as any).querySelector('opc-feedback').toggle(); + }; } diff --git a/packages/user-group-service/src/api-keys/resolver.ts b/packages/user-group-service/src/api-keys/resolver.ts index 5fe30ebb3..75936f490 100644 --- a/packages/user-group-service/src/api-keys/resolver.ts +++ b/packages/user-group-service/src/api-keys/resolver.ts @@ -1,101 +1,94 @@ -import { v4 as uuidv4 } from 'uuid'; -import { Groups } from '../groups/schema'; -import { Users } from '../users/schema'; -import { APIKeys } from './schema'; -import { hash } from './util'; +import { v4 as uuidv4 } from "uuid"; +import { Groups } from "../groups/schema"; +import { Users } from "../users/schema"; +import { APIKeys } from "./schema"; +import { hash } from "./util"; export const APIKeysResolver = { Query: { - listAPIKeys ( parent: any, { limit }: GraphQLArgs ) { - return APIKeys - .find() - .limit( limit ) - .exec(); + listAPIKeys(parent: any, { limit }: GraphQLArgs) { + return APIKeys.find().limit(limit).exec(); }, - getAPIKeysBy ( parent: any, { selector, limit }: GraphQLArgs ) { - return APIKeys - .find( selector ) - .limit( limit ) - .exec(); + getAPIKeysBy(parent: any, { selector, limit }: GraphQLArgs) { + return APIKeys.find(selector).limit(limit).exec(); }, - async validateAPIKey ( parent: any, { accessToken }: GraphQLArgs ) { - const hashKey = hash( accessToken ); - const key = await APIKeys - .findOne( { hashKey } ) - .exec(); + async validateAPIKey(parent: any, { accessToken }: GraphQLArgs) { + const hashKey = hash(accessToken); + const key = await APIKeys.findOne({ hashKey }).exec(); - if ( !key ) { - throw new Error( 'Invalid API Key' ); + if (!key) { + throw new Error("Invalid API Key"); } - if ( key.expiresOn && key.expiresOn.getTime() < new Date().getTime() ) { - throw new Error( 'API Key has expired' ); + if (key.expiresOn && key.expiresOn.getTime() < new Date().getTime()) { + throw new Error("API Key has expired"); } return key; }, }, Mutation: { - createAPIKey ( parent: any, { apiKey }: GraphQLArgs, ctx: any ) { + createAPIKey(parent: any, { apiKey }: GraphQLArgs, ctx: any) { const accessToken = uuidv4(); - return new APIKeys( { + return new APIKeys({ ...apiKey, accessToken, createdOn: new Date(), createdBy: ctx.rhatUUID, - } ) - .save(); + }).save(); }, - changeAPIKeyPermissions ( parent: any, { id, access }: GraphQLArgs, ctx: any ) { - return APIKeys - .findByIdAndUpdate( id, { + changeAPIKeyPermissions( + parent: any, + { id, access }: GraphQLArgs, + ctx: any + ) { + return APIKeys.findByIdAndUpdate( + id, + { access, updatedOn: new Date(), updatedBy: ctx.rhatUUID, - }, { new: true } ) - .exec(); + }, + { new: true } + ).exec(); }, - revokeAPIKey ( parent: any, { id }: GraphQLArgs, ctx: any ) { + revokeAPIKey(parent: any, { id }: GraphQLArgs, ctx: any) { const accessToken = uuidv4(); - const hashKey = hash( accessToken ); + const hashKey = hash(accessToken); - return APIKeys - .findByIdAndUpdate( id, { + return APIKeys.findByIdAndUpdate( + id, + { accessToken, hashKey, updatedOn: new Date(), updateBy: ctx.rhatUUID, - }, { new: true } ) - .exec(); + }, + { new: true } + ).exec(); + }, + deleteAPIKey(parent: any, { id }: GraphQLArgs) { + return APIKeys.findByIdAndRemove(id).exec(); }, - deleteAPIKey ( parent: any, { id }: GraphQLArgs ) { - return APIKeys - .findByIdAndRemove( id ) - .exec(); - } }, APIKey: { - owner ( parent: APIKey ) { - if ( parent.ownerType === 'Group' ) { - return Groups - .findById( parent.owner ) - .exec(); + owner(parent: APIKey) { + if (parent.ownerType === "Group") { + return Groups.findById(parent.owner).exec(); } else { - return Users - .findOne( { rhatUUID: parent.owner } ) - .exec(); + return Users.findOne({ rhatUUID: parent.owner }).exec(); } - } + }, }, APIKeyOwner: { - __resolveType ( owner: any ): string | string { + __resolveType(owner: any): string | string { /* WKRD: Find a better identifier to differentiate UserType and Group */ - if ( !owner.rhatUUID ) { - return 'Group'; + if (!owner.rhatUUID) { + return "Group"; } else { - return 'UserType'; + return "UserType"; } }, - } + }, }; diff --git a/packages/user-group-service/src/users/cron.ts b/packages/user-group-service/src/users/cron.ts index 7d904bb83..0f167a46f 100644 --- a/packages/user-group-service/src/users/cron.ts +++ b/packages/user-group-service/src/users/cron.ts @@ -1,36 +1,43 @@ - -import { Users } from './schema'; -import { UserGroupAPIHelper } from '../helpers'; -import { isEmpty } from 'lodash'; +import { Users } from "./schema"; +import { UserGroupAPIHelper } from "../helpers"; +import { isEmpty } from "lodash"; /** * @class UserSyncCron */ export class UserSyncCron { - public syncUsers(): void { + public syncUsers(): void { Users.find().then((userInfo: any) => { - if ( userInfo.length ) { - const rhatUuids = userInfo.map( ( user: any ) => user.rhatUuid ); + if (userInfo.length) { + const rhatUuids = userInfo.map((user: any) => user.rhatUuid); if (rhatUuids.length) { rhatUuids.map((rhatUuid: any) => { - return UserGroupAPIHelper - .roverFetch( `/users/search?filter=((rhatUuid=${ rhatUuid }))` ) - .then( async ( res: any ) => { - const response = res?.result[ 0 ]; - const oldProfile = userInfo.filter( ( user: any ) => user.rhatUuid === rhatUuid ); - const newProfile = response; - if ( isEmpty(response) ) { - newProfile.isActive = false; - console.log('Account of ' + oldProfile[0].uid + ' de-activated successfully'); - return Users.findByIdAndUpdate(oldProfile[0]._id, newProfile, { new: true }) - .exec(); - } else { - newProfile.isActive = true; - newProfile.updatedOn = new Date(); - return Users.findByIdAndUpdate(oldProfile[0]._id, newProfile, { new: true }) - .exec(); - } - }); + return UserGroupAPIHelper.roverFetch( + `/users/search?filter=((rhatUuid=${rhatUuid}))` + ).then(async (res: any) => { + const response = res?.result[0]; + const oldProfile = userInfo.filter( + (user: any) => user.rhatUuid === rhatUuid + ); + const newProfile = response; + if (isEmpty(response)) { + newProfile.isActive = false; + console.log( + "Account of " + + oldProfile[0].uid + + " de-activated successfully" + ); + return Users.findByIdAndUpdate(oldProfile[0]._id, newProfile, { + new: true, + }).exec(); + } else { + newProfile.isActive = true; + newProfile.updatedOn = new Date(); + return Users.findByIdAndUpdate(oldProfile[0]._id, newProfile, { + new: true, + }).exec(); + } + }); }); } }