justindra
06/20/2022, 9:32 PMthdxr
06/20/2022, 10:23 PMthdxr
06/20/2022, 10:23 PMjustindra
06/20/2022, 10:53 PMthdxr
06/20/2022, 11:27 PMthdxr
06/20/2022, 11:28 PMconst client = new EventBridgeClient({})
async function doPublish(events: readonly Event[]) {
await client.send(
new PutEventsCommand({
Entries: events.map((item) => ({
EventBusName: Config.BUS_NAME,
Detail: JSON.stringify(item),
Source: item.source,
DetailType: item.type,
})),
})
)
return events
}
export interface Event {
id: string
source: "bumi"
type: string
properties: any
actor: Actor
}
export interface Events {}
export type EventTypes = keyof Events
export type FromType<T extends EventTypes> = payload<T, Events[T]>
export type AnyEvent = FromType<EventTypes>
export type payload<T extends string, P extends Record<string, any>> = {
id: string
source: "bumi"
type: T
properties: P
actor: Actor
}
export async function publish<T extends EventTypes>(
type: T,
properties: Events[T],
actor?: Actor
) {
const ctxActor = useContext(ActorContext)
const payload: Event = {
id: ulid(),
source: "bumi",
type,
properties,
actor: actor ? actor : ctxActor,
}
await useLoader(publish, doPublish).load(payload)
return payload
}
thdxr
06/20/2022, 11:28 PMdeclare module "@bumi/core/bus" {
export interface Events {
"business.created": {
id: string
name: string
}
"business.deleted": {
id: string
}
}
}
thdxr
06/20/2022, 11:28 PMBus.publish(...)
typesafethdxr
06/20/2022, 11:29 PMexport function createHandler<T extends EventTypes>(
cb: (event: FromType<T>, record: SQSRecord) => Promise<void>
) {
const result = async (event: SQSEvent) => {
const promises = []
for (const record of event.Records) {
const msg = JSON.parse(record.body)
async function run() {
try {
await cb(msg.detail as FromType<T>, record)
return { type: "success" }
} catch (e) {
console.error(e)
return { type: "error", messageId: record.messageId }
}
}
promises.push(run())
}
const results = await Promise.all(promises)
return {
batchItemFailures: results
.filter((i) => i.type === "error")
.map((i) => ({
itemIdentifier: i,
})),
}
}
return result
// return AWSLambda.wrapHandler(result)
}
thdxr
06/20/2022, 11:30 PMexport const handler = createHandler<"business.created">(async (evt) => {
thdxr
06/20/2022, 11:30 PMsst.EventBus
construct scan your code for createHandler
and automatically setup subscriptions for youJay
justindra
06/20/2022, 11:36 PMjustindra
06/20/2022, 11:38 PM