Skip to content

Instantly share code, notes, and snippets.

@gdagley
Created November 8, 2023 13:48

Revisions

  1. gdagley created this gist Nov 8, 2023.
    87 changes: 87 additions & 0 deletions EventStack.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,87 @@
    import {Config, EventBus, EventBusRuleProps, Queue, Stack, StackContext, Table} from "@serverless-stack/resources";

    const snakeToCamel = (s: string) => s.replace(/(_\w)/g, k => k[1].toUpperCase());

    const addBusinessRule = (stack: Stack, bus: EventBus, dlq: Queue, eventType: string) => {
    const ruleKey = eventType.replace(".", "_");
    const queueName = `${ruleKey}_queue`;
    const handlerLambda = `functions/events/${snakeToCamel(ruleKey)}/handler.main`;

    const rules: Record<string, EventBusRuleProps> = {};
    rules[ruleKey] = {
    pattern: {
    detailType: [eventType]
    },
    targets: {
    function: new Queue(
    stack,
    queueName,
    {
    consumer: {
    function: {
    handler: handlerLambda,
    deadLetterQueueEnabled: true,
    deadLetterQueue: dlq.cdk.queue,
    }
    }
    }
    ),
    }
    };

    bus.addRules(stack, rules);
    };

    export function EventStack({stack}: StackContext) {
    const bus = new EventBus(stack, "StudiousEventsBus", {});
    const dlq = new Queue(stack, "StudiousEventsDLQ");

    addBusinessRule(stack, bus, dlq, "emailSubscription.created");
    addBusinessRule(stack, bus, dlq, "user.updated");
    addBusinessRule(stack, bus, dlq, "team.updated");
    addBusinessRule(stack, bus, dlq, "invitation.created");

    const EVENT_BUS = new Config.Parameter(
    stack,
    "EVENT_BUS",
    {
    value: bus.eventBusName
    }
    );

    const table = new Table(stack, "StudiousEventsTable",
    {
    fields: {
    sourceKey: "string",
    createdAt: "string"
    },
    primaryIndex: {
    partitionKey: "sourceKey",
    sortKey: "createdAt"
    },
    stream: true,
    consumers: {
    outbox: {
    function: {
    handler: "functions/events/outbox/handler.main",
    permissions: [bus],
    config: [EVENT_BUS],
    },
    }
    }
    }
    );

    const EVENT_OUTBOX_TABLE_NAME = new Config.Parameter(
    stack,
    "EVENT_OUTBOX_TABLE_NAME",
    {
    value: table.tableName
    }
    );

    return {
    EVENT_OUTBOX_TABLE_NAME,
    EVENT_BUS
    };
    }
    10 changes: 10 additions & 0 deletions directory_structure.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,10 @@
    src/functions
    ├── events
    │   ├── emailSubscriptionCreated
    │   │   ├── emailSubscriptionCreated.html
    │   │   └── handler.ts
    │   ├── invitationCreated
    │   ├── outbox
    │   ├── teamUpdated
    │   └── userUpdated
    ├── utils