All files / src/models operator.js

50% Statements 23/46
100% Branches 1/1
0% Functions 0/2
50% Lines 23/46

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 47193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x       193x 193x 193x 193x 193x 193x 193x 193x 193x                                          
import dedent from 'dedent';
import { getOperator } from '../clever-client/operators.js';
import { styleText } from '../lib/style-text.js';
import { findAddonsByNameOrId } from './ids-resolver.js';
import { sendToApi } from './send-to-api.js';
 
/**
 * Get the details of an operator from its name or ID
 * @param {string} provider The operator's provider
 * @param {object|string} operatorIdOrName The operator's ID or name
 * @returns {Promise<object>} The operator's details
 * @throws {Error} If the operator provider is unknown
 */
export async function getDetails(provider, operatorIdOrName) {
  const realId = await getSingleRealId(operatorIdOrName);
  return getOperator({ provider, realId }).then(sendToApi);
}
 
/**
 * Get the real ID of an operator from its name or ID
 * @param {object|string} operatorIdOrName The operator's ID or name
 * @returns {Promise<string>} The operator's real ID
 * @throws {Error} If the operator is not found
 * @throws {Error} If the operator name is ambiguous
 */
export async function getSingleRealId(operatorIdOrName) {
  if (operatorIdOrName.operator_id != null) {
    return operatorIdOrName.operator_id;
  }

  const name = operatorIdOrName.addon_name ?? operatorIdOrName.addon_id;
  const operators = await findAddonsByNameOrId(name);

  if (operators.length === 0) {
    throw new Error(`Could not find ${styleText('red', name)}`);
  }

  if (operators.length > 1) {
    throw new Error(dedent`
      Ambiguous name ${styleText('red', name)}, use the real ID instead:
        ${styleText('grey', operators.map((otoroshi) => `- ${otoroshi.name} (${otoroshi.realId})`).join('\n'))}
    `);
  }

  return operators[0].realId;
}