|
| 1 | +/* eslint-disable no-console */ |
| 2 | + |
| 3 | +import chalk from 'chalk' |
| 4 | +import meow from 'meow' |
| 5 | +import ora from 'ora' |
| 6 | + |
| 7 | +import { handleApiCall, handleUnsuccessfulApiResponse } from '../../utils/api-helpers.js' |
| 8 | +import { getDefaultKey, setupSdk } from '../../utils/sdk.js' |
| 9 | + |
| 10 | +/** @type {import('../../utils/meow-with-subcommands.js').CliSubcommand} */ |
| 11 | +export const organizations = { |
| 12 | + description: 'List organizations associated with the API key used', |
| 13 | + async run (argv, importMeta, { parentName }) { |
| 14 | + const name = parentName + ' organizations' |
| 15 | + |
| 16 | + setupCommand(name, organizations.description, argv, importMeta) |
| 17 | + await fetchOrganizations() |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +// Internal functions |
| 22 | + |
| 23 | +/** |
| 24 | + * @param {string} name |
| 25 | + * @param {string} description |
| 26 | + * @param {readonly string[]} argv |
| 27 | + * @param {ImportMeta} importMeta |
| 28 | + * @returns {void} |
| 29 | + */ |
| 30 | +function setupCommand (name, description, argv, importMeta) { |
| 31 | + meow(` |
| 32 | + Usage |
| 33 | + $ ${name} |
| 34 | + `, { |
| 35 | + argv, |
| 36 | + description, |
| 37 | + importMeta |
| 38 | + }) |
| 39 | +} |
| 40 | + |
| 41 | +/** |
| 42 | + * @typedef OrganizationsData |
| 43 | + * @property {import('@socketsecurity/sdk').SocketSdkReturnType<'getOrganizations'>["data"]} data |
| 44 | + */ |
| 45 | + |
| 46 | +/** |
| 47 | + * @returns {Promise<void|OrganizationsData>} |
| 48 | + */ |
| 49 | +async function fetchOrganizations () { |
| 50 | + const apiKey = getDefaultKey() |
| 51 | + const socketSdk = await setupSdk(apiKey) |
| 52 | + const spinner = ora('Fetching organizations...').start() |
| 53 | + |
| 54 | + const result = await handleApiCall(socketSdk.getOrganizations(), 'looking up organizations') |
| 55 | + |
| 56 | + if (result.success === false) { |
| 57 | + return handleUnsuccessfulApiResponse('getOrganizations', result, spinner) |
| 58 | + } |
| 59 | + |
| 60 | + spinner.stop() |
| 61 | + |
| 62 | + const organizations = Object.values(result.data.organizations) |
| 63 | + if (apiKey) { |
| 64 | + console.log(`List of organizations associated with your API key: ${chalk.italic(apiKey)}`) |
| 65 | + } else { |
| 66 | + console.log('List of organizations associated with your API key.') |
| 67 | + } |
| 68 | + |
| 69 | + organizations.map(o => { |
| 70 | + console.log(` |
| 71 | +Name: ${o?.name} |
| 72 | +ID: ${o?.id} |
| 73 | +Plan: ${o?.plan} |
| 74 | + `) |
| 75 | + return o |
| 76 | + }) |
| 77 | + |
| 78 | + return { |
| 79 | + data: result.data |
| 80 | + } |
| 81 | +} |
0 commit comments