All files / libs/tools/plugin/src/executors/sonar-tracker/use-cases/sonar get-sonar-issues-overview.use-case.ts

0% Statements 0/69
0% Branches 0/1
0% Functions 0/1
0% Lines 0/69

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70                                                                                                                                           
import { z } from 'zod';

import { assert } from '@amalia/ext/typescript';

import { sonarConfiguration } from '../../configurations';
import { type SonarIssuesOverview, type SonarSeverity, type SonarSeverityLevel } from '../../types';

const Validator = z.object({
  facets: z.array(
    z.object({
      property: z.literal('severities'),
      values: z.array(
        z.object({
          val: z.enum(['CRITICAL', 'MAJOR', 'MINOR', 'INFO', 'BLOCKER']),
          count: z.number(),
        }),
      ),
    }),
  ),
});

export class GetSonarIssuesOverviewUseCase {
  public async execute(): Promise<SonarIssuesOverview> {
    const response = await fetch(`${sonarConfiguration.url}/api/issues/search?statuses=OPEN&facets=severities`, {
      headers: {
        Authorization: `Bearer ${sonarConfiguration.token}`,
      },
    });

    const data = await response.json();
    const dataParsed = await Validator.parseAsync(data);

    const severitiesFacet = dataParsed.facets.at(0);
    assert(severitiesFacet, 'No severities facet found');

    return severitiesFacet.values.reduce(
      (acc, { count, val: sonarSeverity }) => {
        const severity = this.mapSonarSeverityToSeverityLevel(sonarSeverity);

        return {
          ...acc,
          [severity]: acc[severity] + count,
          total: (('total' in acc ? acc.total : undefined) ?? 0) + count,
        };
      },
      {
        HIGH: 0,
        MEDIUM: 0,
        LOW: 0,
        total: 0,
      },
    );
  }

  private mapSonarSeverityToSeverityLevel(sonarSeverity: SonarSeverity): SonarSeverityLevel {
    switch (sonarSeverity) {
      case 'BLOCKER':
      case 'CRITICAL':
        return 'HIGH';
      case 'MAJOR':
        return 'MEDIUM';
      case 'MINOR':
      case 'INFO':
        return 'LOW';
      default:
        throw new Error(`Unknown Sonar severity: ${sonarSeverity}`);
    }
  }
}