Skip to content

Commit 632eb34

Browse files
committed
fetch the right event to update
1 parent c06cdb2 commit 632eb34

File tree

1 file changed

+24
-21
lines changed

1 file changed

+24
-21
lines changed

src/component/event.ts

Lines changed: 24 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,10 @@ export async function awaitEvent(
1212
entry: Doc<"steps">,
1313
args: { eventId?: Id<"events">; name: string },
1414
) {
15-
const event = await getOrCreateEvent(ctx, entry.workflowId, args);
15+
const event = await getOrCreateEvent(ctx, entry.workflowId, args, [
16+
"sent",
17+
"created",
18+
]);
1619
switch (event.state.kind) {
1720
case "consumed": {
1821
throw new Error(
@@ -64,6 +67,7 @@ async function getOrCreateEvent(
6467
ctx: MutationCtx,
6568
workflowId: Id<"workflows">,
6669
args: { eventId?: Id<"events">; name?: string },
70+
statuses: Doc<"events">["state"]["kind"][],
6771
): Promise<Doc<"events">> {
6872
if (args.eventId) {
6973
const event = await ctx.db.get(args.eventId);
@@ -75,22 +79,16 @@ async function getOrCreateEvent(
7579
return event;
7680
}
7781
assert(args.name, "Name is required if eventId is not specified");
78-
const sentEvent = await ctx.db
79-
.query("events")
80-
.withIndex("workflowId_state", (q) =>
81-
q.eq("workflowId", workflowId).eq("state.kind", "sent"),
82-
)
83-
.filter((q) => q.eq("name", args.name))
84-
.first();
85-
if (sentEvent) return sentEvent;
86-
const createdEvent = await ctx.db
87-
.query("events")
88-
.withIndex("workflowId_state", (q) =>
89-
q.eq("workflowId", workflowId).eq("state.kind", "created"),
90-
)
91-
.filter((q) => q.eq("name", args.name))
92-
.first();
93-
if (createdEvent) return createdEvent;
82+
for (const status of statuses) {
83+
const event = await ctx.db
84+
.query("events")
85+
.withIndex("workflowId_state", (q) =>
86+
q.eq("workflowId", workflowId).eq("state.kind", status),
87+
)
88+
.filter((q) => q.eq(q.field("name"), args.name))
89+
.first();
90+
if (event) return event;
91+
}
9492
const eventId = await ctx.db.insert("events", {
9593
workflowId,
9694
name: args.name,
@@ -111,10 +109,15 @@ export const send = mutation({
111109
},
112110
returns: v.id("events"),
113111
handler: async (ctx, args) => {
114-
const event = await getOrCreateEvent(ctx, args.workflowId, {
115-
eventId: args.eventId,
116-
name: args.name,
117-
});
112+
const event = await getOrCreateEvent(
113+
ctx,
114+
args.workflowId,
115+
{
116+
eventId: args.eventId,
117+
name: args.name,
118+
},
119+
["waiting", "created"],
120+
);
118121
const name = args.name ?? event.name;
119122
switch (event.state.kind) {
120123
case "sent": {

0 commit comments

Comments
 (0)