All files / src/commands/emails emails.remove-all.command.js

44.44% Statements 24/54
100% Branches 1/1
0% Functions 0/1
44.44% Lines 24/54

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x                                                             193x 193x  
import { todo_removeEmailAddress as removeEmailAddress } from '@clevercloud/client/esm/api/v2/user.js';
import { z } from 'zod';
import { defineCommand } from '../../lib/define-command.js';
import { defineOption } from '../../lib/define-option.js';
import { confirm } from '../../lib/prompts.js';
import { Logger } from '../../logger.js';
import { getUserEmailAddresses } from '../../models/emails.js';
import { sendToApi } from '../../models/send-to-api.js';
 
export const emailsRemoveAllCommand = defineCommand({
  description: 'Remove all secondary email addresses from the current user',
  since: '3.13.0',
  options: {
    yes: defineOption({
      name: 'yes',
      schema: z.boolean().default(false),
      description: 'Skip confirmation',
      aliases: ['y'],
    }),
  },
  args: [],
  async handler(options) {
    if (!options.yes) {
      await confirm('Are you sure you want to remove all your secondary addresses?', 'No secondary addresses removed');
    }

    const addresses = await getUserEmailAddresses();

    if (addresses.secondary.length === 0) {
      Logger.println('No secondary address to remove');
      return;
    }

    const results = await Promise.all(
      addresses.secondary.map((addressToRemove) => {
        const addressToRemoveEncoded = encodeURIComponent(addressToRemove);
        return removeEmailAddress({ email: addressToRemoveEncoded })
          .then(sendToApi)
          .then(() => [true, addressToRemove])
          .catch(() => [false, addressToRemove]);
      }),
    );

    if (results.every(([isRemoved]) => isRemoved)) {
      Logger.printSuccess('All secondary addresses were removed successfully');
    } else {
      const addressesWithErrors = results
        .filter(([isRemoved]) => !isRemoved)
        .map(([_, address]) => address)
        .join(', ');
      throw new Error(`Some errors occured while removing these addresses: ${addressesWithErrors}`);
    }
  },
});