import { readAuthAndConfig } from './read-auth-and-config'; import { HttpMethod, RootAPIHelper } from './root-api'; export const constructCommand = (args: string[]) => { const baseCommand = args[2]; // TODO Look at rather finding the index with an enum of commands const commandFromBase = args.splice(2); const cleanedCommand = commandFromBase.map((arg) => { return ['production_', 'sandbox_'].some((e) => arg.includes(e)) ? '' : arg; }); return { baseCommand, fullCommand: `rp ${cleanedCommand.join(' ')}` }; }; export const extractHostFromCommand = (args: string[]): string => { const defaultUrl = '???productionUrl'; // TODO change this const hIndex = args.indexOf('-h') + 1; const hostIndex = args.indexOf('--host') + 1; if (hIndex > args.length - 1 || hostIndex > args.length - 1) { return defaultUrl; } if (hIndex > 0 || hostIndex > 0) { let url: string; url = hIndex > 0 ? args[hIndex] : args[hostIndex]; url = url.includes('http') ? url : defaultUrl; return url; } return defaultUrl; }; export const getHost = (baseCommand: string, args: string[]) => { if (baseCommand === 'clone') { return extractHostFromCommand(args); } const { config } = readAuthAndConfig(); return config.host; }; export const extractApiKeyFromCommand = (args: string[]) => { const apiKey = args.find((arg) => { return arg.includes('production_') || arg.includes('sandbox_'); }); return apiKey || ''; }; export const getApiKey = (baseCommand: string, args: string[]) => { if (baseCommand === 'clone') { return extractApiKeyFromCommand(args); } const { apiKey } = readAuthAndConfig(); return apiKey; }; export const getLogUsageData = (params: { args: string[]; error?: string }) => { const { args, error } = params; const { fullCommand, baseCommand } = constructCommand([...args]); const host = getHost(baseCommand, args); const apiKey = getApiKey(baseCommand, args); const body = error ? { command: fullCommand, error } : { command: fullCommand }; return { body, host, apiKey }; }; export const logUsage = async (params: { args: string[]; error?: string }) => { const { host, body, apiKey } = getLogUsageData(params); const rootApi = new RootAPIHelper({ host, apiKey }); await rootApi.send({ method: HttpMethod.Post, path: 'cli/beta/usage-monitor', body }); };