sst / ion

❍ — a new engine for SST
https://ion.sst.dev
MIT License
1.12k stars 136 forks source link

Add event bus component #327

Closed thelegendtubaguy closed 1 month ago

thelegendtubaguy commented 2 months ago

Hey there! I thought I might try my hand at this, seems like an easy component. Basically just needs a name.

Closes #326

san4d commented 2 months ago

I have something similar I've been working with. Publishing is straight-forward, but I found subscribing to have a bit of boilerplate. My implementation is limited to SQS based on my usage, but I'll share here:

export interface EventBusRule {
    name: string
    /**
     * Represents an [EventBridge Pattern](https://docs.aws.amazon.com/eventbridge/latest/userguide/eb-event-patterns.html)
     */
    pattern?: {
        source?: string[]
        detail?: { [key: string]: any }
        detailType?: string[]
    }
    /**
     *
     */
    target: {
        arn: Input<string>
    }
}
export class EventBus extends Component implements Link.Linkable, Link.AWS.Linkable {
        private bus: aws.cloudwatch.EventBus
        private busName: string

        ....

        public addSubscriber(rule: EventBusRule) {
        const name = `${this.busName}${rule.name}`
        const ruleName = prefixName(128, name)
        const targetName = prefixName(64, name)

        const eventPattern: Record<string, unknown> = { ...rule.pattern }
        if (!!rule.pattern?.detailType) {
            eventPattern['detail-type'] = rule.pattern.detailType
            delete eventPattern['detailType']
        }
        eventPattern

        const cwRule = new aws.cloudwatch.EventRule(`${name}Rule`, {
            eventPattern: JSON.stringify(eventPattern),
            eventBusName: this.bus.name,
            name: ruleName,
        })

        new aws.cloudwatch.EventTarget(`${name}Target`, {
            arn: rule.target.arn,
            rule: cwRule.name,
            targetId: targetName,
            eventBusName: this.bus.name,
        })
    }
}

Feel free to use as much or as little as makes sense.

thelegendtubaguy commented 1 month ago

Looks like they're adding it... without commenting here. :)

jayair commented 1 month ago

Yeah still working on it