import type { InvalidInputError, Subscription, SubscriptionDraft, SubscriptionSetKeyAction, SubscriptionUpdateAction, } from "@commercetools/platform-sdk"; import type { Config } from "#src/config.ts"; import { CommercetoolsError } from "#src/exceptions.ts"; import { SubscriptionDraftSchema } from "#src/schemas/generated/subscription.ts"; import { getBaseResourceProperties } from "../helpers.ts"; import type { Writable } from "../types.ts"; import type { RepositoryContext, UpdateHandlerInterface } from "./abstract.ts"; import { AbstractResourceRepository, AbstractUpdateHandler, } from "./abstract.ts"; export class SubscriptionRepository extends AbstractResourceRepository<"subscription"> { constructor(config: Config) { super("subscription", config); this.actions = new SubscriptionUpdateHandler(config.storage); this.draftSchema = SubscriptionDraftSchema; } async create( context: RepositoryContext, draft: SubscriptionDraft, ): Promise { // TODO: We could actually test this here by using the aws sdk. For now // hardcode a failed check when account id is 0000000000 if (draft.destination.type === "SQS") { const queueURL = new URL(draft.destination.queueUrl); const accountId = queueURL.pathname.split("/")[1]; if (accountId === "0000000000") { const dest = draft.destination; throw new CommercetoolsError( { code: "InvalidInput", message: `A test message could not be delivered to this destination: SQS ${dest.queueUrl} in ${dest.region} for ${dest.accessKey}. Please make sure your destination is correctly configured.`, }, 400, ); } } const resource: Subscription = { ...getBaseResourceProperties(context.clientId), changes: draft.changes || [], destination: draft.destination, format: draft.format || { type: "Platform", }, key: draft.key, messages: draft.messages || [], status: "Healthy", events: draft.events || [], }; return await this.saveNew(context, resource); } } class SubscriptionUpdateHandler extends AbstractUpdateHandler implements Partial> { setKey( _context: RepositoryContext, resource: Writable, { key }: SubscriptionSetKeyAction, ) { resource.key = key; } }