mirror of
https://github.com/openclaw/openclaw.git
synced 2026-03-30 19:32:27 +00:00
refactor: share normalized account lookups
This commit is contained in:
@@ -1,5 +1,5 @@
|
||||
import { describe, expect, it } from "vitest";
|
||||
import { resolveAccountEntry } from "./account-lookup.js";
|
||||
import { resolveAccountEntry, resolveNormalizedAccountEntry } from "./account-lookup.js";
|
||||
|
||||
describe("resolveAccountEntry", () => {
|
||||
it("resolves direct and case-insensitive account keys", () => {
|
||||
@@ -17,3 +17,26 @@ describe("resolveAccountEntry", () => {
|
||||
expect(resolveAccountEntry(accounts, "default")).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe("resolveNormalizedAccountEntry", () => {
|
||||
it("resolves normalized account keys with a custom normalizer", () => {
|
||||
const accounts = {
|
||||
"Ops Team": { id: "ops" },
|
||||
};
|
||||
|
||||
expect(
|
||||
resolveNormalizedAccountEntry(accounts, "ops-team", (accountId) =>
|
||||
accountId.trim().toLowerCase().replaceAll(" ", "-"),
|
||||
),
|
||||
).toEqual({ id: "ops" });
|
||||
});
|
||||
|
||||
it("ignores prototype-chain values", () => {
|
||||
const inherited = { default: { id: "polluted" } };
|
||||
const accounts = Object.create(inherited) as Record<string, { id: string }>;
|
||||
|
||||
expect(
|
||||
resolveNormalizedAccountEntry(accounts, "default", (accountId) => accountId),
|
||||
).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,3 +12,19 @@ export function resolveAccountEntry<T>(
|
||||
const matchKey = Object.keys(accounts).find((key) => key.toLowerCase() === normalized);
|
||||
return matchKey ? accounts[matchKey] : undefined;
|
||||
}
|
||||
|
||||
export function resolveNormalizedAccountEntry<T>(
|
||||
accounts: Record<string, T> | undefined,
|
||||
accountId: string,
|
||||
normalizeAccountId: (accountId: string) => string,
|
||||
): T | undefined {
|
||||
if (!accounts || typeof accounts !== "object") {
|
||||
return undefined;
|
||||
}
|
||||
if (Object.hasOwn(accounts, accountId)) {
|
||||
return accounts[accountId];
|
||||
}
|
||||
const normalized = normalizeAccountId(accountId);
|
||||
const matchKey = Object.keys(accounts).find((key) => normalizeAccountId(key) === normalized);
|
||||
return matchKey ? accounts[matchKey] : undefined;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user