53 lines
2.1 KiB
TypeScript
53 lines
2.1 KiB
TypeScript
import type { KyInstance } from "ky";
|
|
import * as api from "./api.js";
|
|
import type { DatalinkEntity, DatalinkField, DatalinkPlatformDetail } from "./types.js";
|
|
|
|
function matches(value: unknown, target: string): boolean {
|
|
return typeof value === "string" && value.toLowerCase() === target.toLowerCase();
|
|
}
|
|
|
|
export async function resolvePlatform(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
target: string
|
|
): Promise<DatalinkPlatformDetail | undefined> {
|
|
const platforms = await api.listPlatforms(client, corpId);
|
|
const found = platforms.find((platform) =>
|
|
[platform.id, platform.name, platform.code].some((value) => matches(value, target))
|
|
);
|
|
return found ? api.getPlatform(client, corpId, found.id) : undefined;
|
|
}
|
|
|
|
export async function resolveEntity(
|
|
client: KyInstance,
|
|
corpId: string,
|
|
platform: DatalinkPlatformDetail,
|
|
target: string
|
|
): Promise<DatalinkEntity | undefined> {
|
|
const entities = await api.listPlatformEntities(client, corpId, platform.id);
|
|
return entities.find((entity) =>
|
|
[entity.id, entity.name, entity.code].some((value) => matches(value, target))
|
|
);
|
|
}
|
|
|
|
export function buildKeywordFilter(keyword: string): string {
|
|
const escaped = keyword.replace(/\\/g, "\\\\").replace(/"/g, '\\"');
|
|
return `(name.containsIgnoreCase("${escaped}")||code.containsIgnoreCase("${escaped}"))&&(active.in(true,false))`;
|
|
}
|
|
|
|
export function selectRecordFields(record: Record<string, unknown>, fields: string[], definitions: DatalinkField[] = []): Record<string, unknown> {
|
|
if (fields.length === 0) return record;
|
|
const dataLink = record.dataLink && typeof record.dataLink === "object" && !Array.isArray(record.dataLink)
|
|
? (record.dataLink as Record<string, unknown>)
|
|
: record;
|
|
const selected: Record<string, unknown> = {};
|
|
for (const selector of fields) {
|
|
const definition = definitions.find((field) => field.name === selector || field.label === selector);
|
|
const sourceName = definition?.name ?? selector;
|
|
if (sourceName in dataLink) selected[definition?.label || selector] = dataLink[sourceName];
|
|
}
|
|
return record.dataLink && typeof record.dataLink === "object"
|
|
? { ...record, dataLink: selected }
|
|
: selected;
|
|
}
|