All files / src/commands/notify-email notify-email.add.command.js

44.11% Statements 30/68
100% Branches 1/1
0% Functions 0/2
44.11% Lines 30/68

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 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69193x 193x 193x 193x 193x 193x 193x 193x 193x 193x                                         193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x                                     193x 193x  
import { createEmailhook } from '@clevercloud/client/esm/api/v2/notification.js';
import { z } from 'zod';
import { defineCommand } from '../../lib/define-command.js';
import { defineOption } from '../../lib/define-option.js';
import { Logger } from '../../logger.js';
import { getOwnerAndApp } from '../../models/notification.js';
import { sendToApi } from '../../models/send-to-api.js';
import { notificationNameArg } from '../global.args.js';
import { notificationEventTypeOption, notificationScopeOption, orgaIdOrNameOption } from '../global.options.js';
 
function getEmailNotificationTargets(notifTargets) {
  if (notifTargets == null) {
    return [];
  }

  return notifTargets
    .map((el) => {
      if (el.includes('@')) {
        return { type: 'email', target: el };
      }
      if (el.startsWith('user_')) {
        return { type: 'userid', target: el };
      }
      if (el.toLowerCase() === 'organisation') {
        return { type: 'organisation' };
      }
      return null;
    })
    .filter((e) => e != null);
}
 
export const notifyEmailAddCommand = defineCommand({
  description: 'Add a new email notification',
  since: '0.6.1',
  options: {
    notify: defineOption({
      name: 'notify',
      schema: z.string().transform((v) => v.split(',')),
      description:
        'Notify a user, a specific email address or the whole organisation (multiple values allowed, comma separated)',
      placeholder: 'email-address|user-id|organisation',
    }),
    org: orgaIdOrNameOption,
    event: notificationEventTypeOption,
    service: notificationScopeOption,
  },
  args: [notificationNameArg],
  async handler(options, name) {
    const { org, event: events, service, notify: notifTargets } = options;

    if (service != null && org == null) {
      throw new Error('--org is required when using --service');
    }

    const { ownerId, appId } = await getOwnerAndApp(org, org == null && service == null);

    const body = {
      name,
      notified: getEmailNotificationTargets(notifTargets),
      scope: appId != null && service == null ? [appId] : service,
      events,
    };

    await createEmailhook({ ownerId }, body).then(sendToApi);

    Logger.println('The webhook has been added');
  },
});