Skip to content

Instantly share code, notes, and snippets.

@gdagley
Created November 8, 2023 13:48
Show Gist options
  • Save gdagley/1c60aecf17a8c6a8e0a29e281926db2c to your computer and use it in GitHub Desktop.
Save gdagley/1c60aecf17a8c6a8e0a29e281926db2c to your computer and use it in GitHub Desktop.
Simplify adding EventBus rules to SST
src/functions
├── events
│   ├── emailSubscriptionCreated
│   │   ├── emailSubscriptionCreated.html
│   │   └── handler.ts
│   ├── invitationCreated
│   ├── outbox
│   ├── teamUpdated
│   └── userUpdated
├── utils
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
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment