Files
History-client/api/entities.ts
2026-04-17 20:55:59 +07:00

109 lines
3.0 KiB
TypeScript

import { API_ENDPOINTS } from "@/api/config";
import { requestJson } from "@/api/http";
export type Entity = {
id: string;
name: string;
slug?: string | null;
description?: string | null;
type_id?: string | null;
status?: number | null;
geometry_count?: number;
created_at?: string;
updated_at?: string;
};
export type CreateEntityPayload = {
name: string;
slug?: string | null;
description?: string | null;
type_id?: string | null;
status?: number | null;
};
export type EntityBatchCreateChange =
| ({
action: "create";
entity: CreateEntityPayload & { id?: string };
})
| ({
action: "create";
id?: string;
} & CreateEntityPayload);
export type EntityBatchUpdateChange =
| ({
action: "update";
id: string;
entity: Partial<CreateEntityPayload> & { id?: string };
})
| ({
action: "update";
id: string;
} & Partial<CreateEntityPayload>);
export type EntityBatchDeleteChange = {
action: "delete";
id: string;
};
export type EntityBatchChange =
| EntityBatchCreateChange
| EntityBatchUpdateChange
| EntityBatchDeleteChange;
export type EntityBatchSaveResponse = {
success: boolean;
applied: number;
created_entity_ids: string[];
};
export async function fetchEntities(query?: { q?: string }): Promise<Entity[]> {
const params = new URLSearchParams();
if (query?.q) {
params.set("q", query.q);
}
const suffix = params.toString();
const url = suffix ? `${API_ENDPOINTS.entities}?${suffix}` : API_ENDPOINTS.entities;
return requestJson<Entity[]>(url);
}
export async function searchEntitiesByName(
name: string,
options?: { limit?: number }
): Promise<Entity[]> {
const keyword = name.trim();
if (!keyword.length) return [];
const params = new URLSearchParams({ name: keyword });
if (options?.limit && Number.isFinite(options.limit)) {
params.set("limit", String(Math.trunc(options.limit)));
}
return requestJson<Entity[]>(`${API_ENDPOINTS.entities}/search?${params.toString()}`);
}
export async function createEntity(payload: CreateEntityPayload): Promise<Entity> {
return requestJson<Entity>(API_ENDPOINTS.entities, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
}
export async function updateEntity(id: string, payload: CreateEntityPayload): Promise<Entity> {
return requestJson<Entity>(`${API_ENDPOINTS.entities}/${id}`, {
method: "PUT",
headers: { "Content-Type": "application/json" },
body: JSON.stringify(payload),
});
}
export async function saveEntityBatchChanges(changes: EntityBatchChange[]): Promise<EntityBatchSaveResponse> {
return requestJson<EntityBatchSaveResponse>(API_ENDPOINTS.entitiesBatch, {
method: "POST",
headers: { "Content-Type": "application/json" },
body: JSON.stringify({ changes }),
});
}