From f20da8a79173bd770078f695ee74745a8a9435db Mon Sep 17 00:00:00 2001 From: Andre Miras Date: Fri, 6 Dec 2024 12:27:40 +0100 Subject: [PATCH] :recycle: DRY logic in getter & setter CLI commands --- src/cli.ts | 36 +++++++++++++++++++++++++----------- 1 file changed, 25 insertions(+), 11 deletions(-) diff --git a/src/cli.ts b/src/cli.ts index 3367dba..e74add3 100755 --- a/src/cli.ts +++ b/src/cli.ts @@ -45,6 +45,28 @@ const addAuthOptions = (command: Command): Command => const addMacOption = (command: Command): Command => command.requiredOption("-m, --mac ", "MAC address of the device"); +/** + * Handles common authentication and API initialization logic. + * @param options The options passed from the CLI command. + * @returns An object containing the normalized MAC, JWT token, and configured API instance. + */ +const initializeCommand = async (options: { + username: string; + password?: string; + mac: string; +}): Promise<{ + normalizedMac: string; + jwtToken: string; + api: ReturnType; +}> => { + const { username, password, mac } = options; + const normalizedMac = mac.replace(/:/g, ""); + const pwd = password || (await promptPassword()); + const jwtToken = await signIn(username, pwd); + const api = configure(); + return { normalizedMac, jwtToken, api }; +}; + /** * Executes a getter command by handling common steps (authentication, API initialization). * @param options The options passed from the CLI command. @@ -58,11 +80,7 @@ const executeGetter = async ( mac: string ) => Promise ): Promise => { - const { username, password, mac } = options; - const normalizedMac = mac.replace(/:/g, ""); - const pwd = password || (await promptPassword()); - const jwtToken = await signIn(username, pwd); - const api = configure(); + const { normalizedMac, jwtToken, api } = await initializeCommand(options); const result = await getter(api, jwtToken, normalizedMac); console.log(result); }; @@ -81,12 +99,8 @@ const executeSetter = async ( value: number ) => Promise ): Promise => { - const { username, password, mac, value } = options; - const normalizedMac = mac.replace(/:/g, ""); - const pwd = password || (await promptPassword()); - const jwtToken = await signIn(username, pwd); - const api = configure(); - const result = await setter(api, jwtToken, normalizedMac, value); + const { normalizedMac, jwtToken, api } = await initializeCommand(options); + const result = await setter(api, jwtToken, normalizedMac, options.value); console.log(result); };