55 lines
1.9 KiB
TypeScript
55 lines
1.9 KiB
TypeScript
import type { KyInstance } from "ky";
|
|
import { getGlobalCache } from "../../core/cache/index.js";
|
|
import { listDimensionCatalogs, listDimensionItems } from "./api.js";
|
|
import type { DimensionCatalog, DimensionItem, DimensionQuery } from "./types.js";
|
|
|
|
const CACHE_TTL_MS = 10 * 60 * 1000;
|
|
|
|
async function getCachedCatalogs(client: KyInstance, corpId: string): Promise<DimensionCatalog[]> {
|
|
const cache = getGlobalCache();
|
|
return cache.withCache(
|
|
`dimensions:catalogs:${corpId}`,
|
|
() => listDimensionCatalogs(client, corpId),
|
|
{ namespace: "dimensions", ttlMs: CACHE_TTL_MS }
|
|
);
|
|
}
|
|
|
|
export async function searchDimensions(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
query: DimensionQuery = {}
|
|
): Promise<DimensionCatalog[]> {
|
|
const catalogs = await getCachedCatalogs(client, corpId);
|
|
const keyword = (query.name || query.code || query.id || "").trim().toLowerCase();
|
|
if (!keyword) return catalogs;
|
|
return catalogs.filter((item) =>
|
|
[item.id, item.name, item.code].some((value) => value.toLowerCase().includes(keyword))
|
|
);
|
|
}
|
|
|
|
export async function getDimensionItems(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
dimension: DimensionCatalog,
|
|
start = 0,
|
|
count = 100
|
|
): Promise<DimensionItem[]> {
|
|
const cache = getGlobalCache();
|
|
return cache.withCache(
|
|
`dimensions:items:${corpId}:${dimension.id}:${start}:${count}`,
|
|
() => listDimensionItems(client, corpId, dimension.id, start, count),
|
|
{ namespace: "dimensions", ttlMs: CACHE_TTL_MS }
|
|
);
|
|
}
|
|
|
|
export async function resolveDimension(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
target: string
|
|
): Promise<{ dimension: DimensionCatalog; items: DimensionItem[] } | undefined> {
|
|
const matches = await searchDimensions(client, corpId, { id: target, code: target, name: target });
|
|
const dimension = matches[0];
|
|
if (!dimension) return undefined;
|
|
return { dimension, items: await getDimensionItems(client, corpId, dimension) };
|
|
}
|