All files / src/commands/webhooks webhooks.add.command.js

66.66% Statements 36/54
100% Branches 1/1
0% Functions 0/1
66.66% Lines 36/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 193x 193x 193x 193x 193x 193x 193x 193x 193x 193x                                     193x 193x  
import { createWebhook } from '@clevercloud/client/esm/api/v2/notification.js';
import { z } from 'zod';
import { defineArgument } from '../../lib/define-argument.js';
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';
 
export const webhooksAddCommand = defineCommand({
  description: 'Register webhook to be called when events happen',
  since: '0.6.0',
  options: {
    format: defineOption({
      name: 'format',
      schema: z.string().default('raw'),
      description: "Format of the body sent to the webhook ('raw', 'slack', 'gitter', or 'flowdock')",
      placeholder: 'format',
    }),
    org: orgaIdOrNameOption,
    event: notificationEventTypeOption,
    service: notificationScopeOption,
  },
  args: [
    notificationNameArg,
    defineArgument({
      schema: z.string(),
      description: 'Webhook URL',
      placeholder: 'url',
    }),
  ],
  async handler(options, name, hookUrl) {
    const { org, format, event: events, service } = 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,
      urls: [{ format, url: hookUrl }],
      scope: appId != null && service == null ? [appId] : service,
      events,
    };

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

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