# All files / src/providers/openai Moderation.ts

90.9% Statements 10/11
50% Branches 3/6
100% Functions 2/2
90.9% Lines 10/11

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

    40x
    40x

    1x

    1x
    1x

    1x

    1x

    1x
    1x
    1x

     import { ModerationRequest, ModerationResponse } from "../Provider.js";
    import { handleOpenAIError } from "./Errors.js";
    import { DEFAULT_MODELS } from "../../constants.js";
    import { buildUrl } from "./utils.js";
    import { logger } from "../../utils/logger.js";
    import { fetchWithTimeout } from "../../utils/fetch.js";

    export class OpenAIModeration {
      constructor(
        private readonly baseUrl: string,
        private readonly apiKey: string
      ) {}

      async execute(request: ModerationRequest): Promise<ModerationResponse> {
        const body = {
          input: request.input,
          model: request.model || DEFAULT_MODELS.MODERATION
        };

        const url = buildUrl(this.baseUrl, "/moderations");
        logger.logRequest("OpenAI", "POST", url, body);

        const response = await fetchWithTimeout(
          url,
          {
            method: "POST",
            headers: {
              Authorization: `Bearer ${this.apiKey}`,
              "Content-Type": "application/json"
            },
            body: JSON.stringify(body)
          },
          request.requestTimeout
        );

        Iif (!response.ok) {
          await handleOpenAIError(response, request.model || DEFAULT_MODELS.MODERATION);
        }

        const json = (await response.json()) as ModerationResponse;
        logger.logResponse("OpenAI", response.status, response.statusText, json);
        return json;
      }
    }