Skip to content

Commit

Permalink
support webhook condition on nested key (#557)
Browse files Browse the repository at this point in the history
  • Loading branch information
oXtxNt9U authored Apr 23, 2024
1 parent fb42146 commit 1befb46
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
41 changes: 41 additions & 0 deletions packages/webhooks/source/listener.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,30 @@ describe<{
expectFinishedEventData(spyOnDispatchArguments[1]);
});

it("should broadcast satisfied webhook condition with nested key", async ({ database, listener }) => {
const spyOnPost = stub(Utils.http, "post").resolvedValue({
statusCode: 200,
});
const spyOnDispatch = stub(eventDispatcher, "dispatch");

webhook.conditions = [
{
condition: "eq",
key: "some.nested.prop",
value: 1,
},
];
database.create(webhook);

await listener.handle({ data: { some: { nested: { prop: 1 } } }, name: "event" });

spyOnPost.calledOnce();
spyOnDispatch.calledOnce();
const spyOnDispatchArguments = spyOnDispatch.getCallArgs(0);
assert.equal(spyOnDispatchArguments[0], WebhookEvent.Broadcasted);
expectFinishedEventData(spyOnDispatchArguments[1]);
});

it("should not broadcast if webhook condition is not satisfied", async ({ database, listener }) => {
const spyOnPost = stub(Utils.http, "post");

Expand All @@ -163,6 +187,23 @@ describe<{
spyOnPost.neverCalled();
});

it("should not broadcast if webhook condition with nested key is not satisfied", async ({ database, listener }) => {
const spyOnPost = stub(Utils.http, "post");

webhook.conditions = [
{
condition: "eq",
key: "some.nested.prop",
value: 1,
},
];
database.create(webhook);

await listener.handle({ data: { some: { nested: { prop: 2 } } }, name: "event" });

spyOnPost.neverCalled();
});

it("should not broadcast if webhook condition throws error", async ({ database, listener }) => {
const spyOnEq = stub(conditions, "eq").callsFake(() => {
throw new Error("dummy error");
Expand Down
3 changes: 2 additions & 1 deletion packages/webhooks/source/listener.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import { inject, injectable } from "@mainsail/container";
import { Contracts, Identifiers } from "@mainsail/contracts";
import { Utils } from "@mainsail/kernel";
import { get } from "@mainsail/utils";
import { performance } from "perf_hooks";

import { conditions } from "./conditions.js";
Expand Down Expand Up @@ -102,7 +103,7 @@ export class Listener {
try {
const satisfies = conditions[condition.condition];

if (satisfies(payload[condition.key], condition.value)) {
if (satisfies(get(payload, condition.key), condition.value)) {
return true;
}
} catch {
Expand Down

0 comments on commit 1befb46

Please sign in to comment.