Files
Checkmate/server/src/service/network/AdvancedMatcher.ts
T

49 lines
1.6 KiB
TypeScript
Raw Normal View History

2026-06-09 12:34:15 -07:00
import { Monitor } from "@/domain/monitors/monitor.types.js";
2026-03-04 23:24:48 +00:00
import jmespath from "jmespath";
type JmesPath = typeof jmespath;
2026-03-20 11:29:44 -07:00
export interface IAdvancedMatcher {
2026-03-20 11:28:53 -07:00
validate<T>(payload: T, monitor: Monitor): { ok: boolean; message: string; extracted?: T | undefined };
}
2026-03-20 11:29:44 -07:00
export class AdvancedMatcher implements IAdvancedMatcher {
2026-03-04 23:24:48 +00:00
constructor(private jmespath: JmesPath) {}
private compare(actual: unknown, expected: string, method?: string): boolean {
if (method === "equal") return String(actual) === expected;
if (method === "include") return String(actual).includes(expected);
if (method === "regex") return new RegExp(expected).test(String(actual));
return String(actual) === expected; // Default
}
2026-03-20 11:28:53 -07:00
validate<T>(payload: T, monitor: Monitor): { ok: boolean; message: string; extracted?: T | undefined } {
2026-03-04 23:24:48 +00:00
const { useAdvancedMatching, jsonPath, matchMethod, expectedValue } = monitor;
if (!useAdvancedMatching) return { ok: true, message: "Success" };
let dataToValidate = payload;
if (jsonPath) {
try {
dataToValidate = this.jmespath.search(payload, jsonPath);
} catch {
return { ok: false, message: "Error evaluating JSON path" };
}
}
if (expectedValue) {
const ok = this.compare(dataToValidate, expectedValue, matchMethod);
return {
ok,
message: ok ? "Success" : "Expected value did not match",
extracted: dataToValidate,
};
}
2026-03-20 11:28:53 -07:00
const isFalsy = dataToValidate === false || dataToValidate === "false" || dataToValidate === undefined || dataToValidate === null;
2026-03-04 23:24:48 +00:00
return {
2026-03-20 11:28:53 -07:00
ok: !isFalsy,
message: !isFalsy ? "Success" : "Extracted value is falsy",
2026-03-04 23:24:48 +00:00
extracted: dataToValidate,
};
}
}