refactor: share path-root query predicate (WealthLedger/frontend#142) (#154)
This commit was merged in pull request #154.
This commit is contained in:
@@ -13,6 +13,7 @@ export {
|
||||
isApiErrorCode,
|
||||
isBrokerageAccessLoss,
|
||||
} from "./problem-details";
|
||||
export { isGetUnder } from "./query-predicate";
|
||||
export { isReadFailureExhausted, readRetry } from "./read-failure";
|
||||
|
||||
export {
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
|
||||
import { isGetUnder } from "./query-predicate";
|
||||
|
||||
describe("isGetUnder", () => {
|
||||
it("matches the root itself and nested paths for get queries only", () => {
|
||||
const predicate = isGetUnder(["/api/v1/bank-cards"]);
|
||||
|
||||
expect(predicate(["get", "/api/v1/bank-cards"])).toBe(true);
|
||||
expect(predicate(["get", "/api/v1/bank-cards/{id}"])).toBe(true);
|
||||
expect(predicate(["get", "/api/v1/bank-cards"])).toBe(true);
|
||||
expect(predicate(["get", "/api/v1/bank-cardsx"])).toBe(false);
|
||||
expect(predicate(["post", "/api/v1/bank-cards"])).toBe(false);
|
||||
expect(predicate(["get", "/api/v1/other"])).toBe(false);
|
||||
});
|
||||
|
||||
it("checks every root and tolerates init and non-string parts", () => {
|
||||
const predicate = isGetUnder(["/api/v1/stocks", "/api/v1/bonds"]);
|
||||
|
||||
expect(predicate(["get", "/api/v1/stocks/{uid}/quote", { params: {} }]))
|
||||
.toBe(true);
|
||||
expect(predicate(["get", "/api/v1/bonds"])).toBe(true);
|
||||
expect(predicate([undefined, "/api/v1/stocks"])).toBe(false);
|
||||
expect(predicate(["get", undefined])).toBe(false);
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,18 @@
|
||||
import type { QueryKey } from "@tanstack/react-query";
|
||||
|
||||
// openapi-react-query shapes query keys as [method, path, init].
|
||||
function isGetUnder(roots: readonly string[]) {
|
||||
const predicate = (queryKey: QueryKey) => {
|
||||
const [method, path] = queryKey as readonly [unknown, unknown];
|
||||
|
||||
return (
|
||||
method === "get"
|
||||
&& typeof path === "string"
|
||||
&& roots.some(root => path === root || path.startsWith(`${root}/`))
|
||||
);
|
||||
};
|
||||
|
||||
return predicate;
|
||||
}
|
||||
|
||||
export { isGetUnder };
|
||||
Reference in New Issue
Block a user