|
| 1 | +import { Command, Flags } from '@oclif/core'; |
| 2 | +import { LinkedApiAdmin, LinkedApiError } from '@linkedapi/node'; |
| 3 | + |
| 4 | +import { resolveAdminToken } from '@core/auth/auth-manager'; |
| 5 | +import { buildAdminClient } from '@core/client/build-admin-client'; |
| 6 | +import { mapLinkedApiErrorToCliError, writeErrorToStderr } from '@core/errors/error-handler'; |
| 7 | +import { EXIT_CODE } from '@core/errors/exit-codes'; |
| 8 | + |
| 9 | +export abstract class AdminBaseCommand extends Command { |
| 10 | + static override baseFlags = { |
| 11 | + json: Flags.boolean({ |
| 12 | + description: 'Output as JSON', |
| 13 | + default: false, |
| 14 | + }), |
| 15 | + fields: Flags.string({ |
| 16 | + description: 'Comma-separated list of fields to include in output', |
| 17 | + }), |
| 18 | + quiet: Flags.boolean({ |
| 19 | + char: 'q', |
| 20 | + description: 'Suppress progress output on stderr', |
| 21 | + default: false, |
| 22 | + }), |
| 23 | + 'no-color': Flags.boolean({ |
| 24 | + description: 'Disable colored output', |
| 25 | + default: false, |
| 26 | + }), |
| 27 | + }; |
| 28 | + |
| 29 | + public override async init(): Promise<void> { |
| 30 | + await super.init(); |
| 31 | + const { flags } = await this.parse(this.constructor as typeof AdminBaseCommand); |
| 32 | + |
| 33 | + if (flags['no-color']) { |
| 34 | + process.env.NO_COLOR = '1'; |
| 35 | + } |
| 36 | + } |
| 37 | + |
| 38 | + protected async buildAdminClient(): Promise<LinkedApiAdmin> { |
| 39 | + try { |
| 40 | + const linkedApiToken = resolveAdminToken(); |
| 41 | + return buildAdminClient(linkedApiToken); |
| 42 | + } catch (error) { |
| 43 | + if (error instanceof Error) { |
| 44 | + process.stderr.write(error.message + '\n'); |
| 45 | + } |
| 46 | + |
| 47 | + this.exit(EXIT_CODE.AUTH); |
| 48 | + throw error; |
| 49 | + } |
| 50 | + } |
| 51 | + |
| 52 | + protected handleError(error: unknown): never { |
| 53 | + if (error instanceof LinkedApiError) { |
| 54 | + const cliError = mapLinkedApiErrorToCliError(error); |
| 55 | + writeErrorToStderr(cliError); |
| 56 | + this.exit(cliError.exitCode); |
| 57 | + } |
| 58 | + |
| 59 | + if (error instanceof Error) { |
| 60 | + writeErrorToStderr({ |
| 61 | + exitCode: EXIT_CODE.GENERAL, |
| 62 | + error: 'unexpectedError', |
| 63 | + message: error.message, |
| 64 | + }); |
| 65 | + this.exit(EXIT_CODE.GENERAL); |
| 66 | + } |
| 67 | + |
| 68 | + writeErrorToStderr({ |
| 69 | + exitCode: EXIT_CODE.GENERAL, |
| 70 | + error: 'unexpectedError', |
| 71 | + message: 'An unexpected error occurred', |
| 72 | + }); |
| 73 | + this.exit(EXIT_CODE.GENERAL); |
| 74 | + |
| 75 | + throw error; |
| 76 | + } |
| 77 | +} |
0 commit comments