66 lines
2.0 KiB
TypeScript
66 lines
2.0 KiB
TypeScript
import type { KyInstance } from "ky";
|
|
import { getGlobalCache } from "../../core/cache/index.js";
|
|
import { listRoleGroups, listRoleMembers, listRoles } from "./api.js";
|
|
import type { Role, RoleGroup, RoleMemberReport, RoleQuery } from "./types.js";
|
|
|
|
const CACHE_TTL_MS = 10 * 60 * 1000;
|
|
|
|
async function getCatalog(
|
|
client: KyInstance,
|
|
corpId: string
|
|
): Promise<{ roles: Role[]; groups: RoleGroup[] }> {
|
|
const cache = getGlobalCache();
|
|
return cache.withCache(
|
|
`roles:catalog:${corpId}`,
|
|
async () => {
|
|
const [roles, groups] = await Promise.all([
|
|
listRoles(client, corpId),
|
|
listRoleGroups(client, corpId),
|
|
]);
|
|
return { roles, groups };
|
|
},
|
|
{ namespace: "roles", ttlMs: CACHE_TTL_MS }
|
|
);
|
|
}
|
|
|
|
export async function searchRoles(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
query: RoleQuery = {}
|
|
): Promise<Role[]> {
|
|
const { roles } = await getCatalog(client, corpId);
|
|
const keyword = (query.keyword || query.id || query.code || query.name || "").trim().toLowerCase();
|
|
if (!keyword) return roles;
|
|
return roles.filter((role) =>
|
|
[role.id, role.name, role.code, role.purposeName, role.scope.name].some((value) =>
|
|
value.toLowerCase().includes(keyword)
|
|
)
|
|
);
|
|
}
|
|
|
|
export async function getRoleGroups(client: KyInstance, corpId: string): Promise<RoleGroup[]> {
|
|
return (await getCatalog(client, corpId)).groups;
|
|
}
|
|
|
|
export async function resolveRole(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
target: string
|
|
): Promise<Role | undefined> {
|
|
const matches = await searchRoles(client, corpId, { keyword: target });
|
|
return (
|
|
matches.find((role) => role.id === target || role.code === target || role.name === target) ||
|
|
matches[0]
|
|
);
|
|
}
|
|
|
|
export async function getRoleMembers(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
target: string
|
|
): Promise<RoleMemberReport | undefined> {
|
|
const role = await resolveRole(client, corpId, target);
|
|
if (!role) return undefined;
|
|
return { role, members: await listRoleMembers(client, corpId, role.id) };
|
|
}
|