UNPKG

bump-cli

Version:

The Bump CLI is used to interact with your API documentation hosted on Bump.sh by using the API of developers.bump.sh

98 lines (97 loc) 3.47 kB
import { CLIError } from '@oclif/core/errors'; import chalk from 'chalk'; import d from 'debug'; const debug = d('bump-cli:api-client'); export default class APIError extends CLIError { constructor(httpError, info = [], exit = 100) { const status = httpError?.response?.status; debug(httpError); if (httpError) { switch (status) { case 422: { ; [info, exit] = APIError.invalidDefinition(httpError.response?.data); break; } case 401: { ; [info, exit] = APIError.unauthenticated(); break; } case 404: case 400: { ; [info, exit] = APIError.notFound(httpError.response?.data); break; } } if (info.length > 0) { super(info.join('\n'), { exit }); } else { super(`Unhandled API error (status: ${status}) (error: ${httpError})`, { exit }); } } else { super('Unhandled API error', { exit }); } } static humanAttributeError(attribute, messages) { let info = []; if (Array.isArray(messages)) { const allMessages = messages .map((message, idx) => { if (message instanceof Object) { return this.humanAttributeError(idx.toString(), message); } return message; }) .join(', '); info.push(`${chalk.underline(attribute)} ${allMessages}`); } else if (messages instanceof Object) { for (const [child, childMessages] of Object.entries(messages)) { const childErrors = this.humanAttributeError(`${attribute}.${child}`, childMessages); info = [...info, ...childErrors]; } } else if (messages) { info.push(`${chalk.underline(attribute)} ${messages}`); } return info; } static invalidDefinition(error) { let info = []; const genericMessage = error.message || 'Invalid definition file'; const exit = 122; if (error && 'errors' in error) { for (const [attr, message] of Object.entries(error.errors)) { const humanErrors = APIError.humanAttributeError(attr, message); info = [...info, ...humanErrors]; } } else { info.push(genericMessage); } return [info, exit]; } static is(error) { return error instanceof CLIError && 'http' in error; } static notFound(error) { const genericMessage = error.message || "It seems the documentation provided doesn't exist."; return [ [ genericMessage, `In a hub context you might want to try the ${chalk.dim('--auto-create')} flag.\nOtherwise, please check the given ${chalk.dim('--doc')}, ${chalk.dim('--token')} or ${chalk.dim('--hub')} flags`, ], 104, ]; } static unauthenticated() { return [ ['You are not allowed to deploy to this documentation.', 'please check your --token flag or BUMP_TOKEN variable'], 101, ]; } }