Skip to content

Commit

Permalink
♻️ DRY logic in getter & setter CLI commands
Browse files Browse the repository at this point in the history
  • Loading branch information
AndreMiras committed Dec 6, 2024
1 parent 8b5299d commit f20da8a
Showing 1 changed file with 25 additions and 11 deletions.
36 changes: 25 additions & 11 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,6 +45,28 @@ const addAuthOptions = (command: Command): Command =>
const addMacOption = (command: Command): Command =>
command.requiredOption("-m, --mac <macAddress>", "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<typeof configure>;
}> => {
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.
Expand All @@ -58,11 +80,7 @@ const executeGetter = async (
mac: string
) => Promise<unknown>
): Promise<void> => {
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);
};
Expand All @@ -81,12 +99,8 @@ const executeSetter = async (
value: number
) => Promise<unknown>
): Promise<void> => {
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);
};

Expand Down

0 comments on commit f20da8a

Please sign in to comment.