From eabe943960f0fc3f2f4ca276ec3c27e71125f563 Mon Sep 17 00:00:00 2001 From: Iain Sproat <68657+iainsproat@users.noreply.github.com> Date: Thu, 13 Mar 2025 17:26:21 +0000 Subject: [PATCH] Tidy up type checking --- .../src/controller/daemon.ts | 45 ++++++++++++------- 1 file changed, 29 insertions(+), 16 deletions(-) diff --git a/packages/fileimport-service/src/controller/daemon.ts b/packages/fileimport-service/src/controller/daemon.ts index d9447b440..2fe0a9a90 100644 --- a/packages/fileimport-service/src/controller/daemon.ts +++ b/packages/fileimport-service/src/controller/daemon.ts @@ -250,22 +250,9 @@ async function doTask( const output: unknown = JSON.parse(fs.readFileSync(TMP_RESULTS_PATH, 'utf8')) - if ( - !output || - typeof output !== 'object' || - !('success' in output) || - !output.success || - !('commitId' in output) - ) - throw new Error( - output && - typeof output === 'object' && - 'error' in output && - output.error && - typeof output.error === 'string' - ? output.error - : 'Unknown error' - ) + if (!isSuccessOutput(output)) { + throw new Error(isErrorOutput(output) ? output.error : 'Unknown error') + } const commitId = output.commitId @@ -319,6 +306,32 @@ async function doTask( } } +function isSuccessOutput( + maybeSuccessOutput: unknown +): maybeSuccessOutput is { success: true; commitId: string } { + return ( + !!maybeSuccessOutput && + typeof maybeSuccessOutput === 'object' && + 'success' in maybeSuccessOutput && + typeof maybeSuccessOutput.success === 'boolean' && + maybeSuccessOutput.success && + 'commitId' in maybeSuccessOutput && + typeof maybeSuccessOutput.commitId === 'string' + ) +} + +function isErrorOutput( + maybeErrorOutput: unknown +): maybeErrorOutput is { success: false; error: string } { + return ( + !!maybeErrorOutput && + typeof maybeErrorOutput === 'object' && + 'error' in maybeErrorOutput && + typeof maybeErrorOutput.error === 'string' && + !!maybeErrorOutput.error + ) +} + function runProcessWithTimeout( processLogger: Logger, cmd: string,