41 lines
2.0 KiB
TypeScript
41 lines
2.0 KiB
TypeScript
'use server';
|
|
import { BACKEND_URL } from '@/_config/backend';
|
|
|
|
import { revalidatePath } from 'next/cache';
|
|
import { UnitTemplate, UnitTemplateData } from '@/types/anlagen/unit-templates';
|
|
import { UnitCopy, UnitResponse } from '@/types/anlagen/units';
|
|
|
|
const url = BACKEND_URL + '/rk2/unit-templates';
|
|
async function request<T>(path: string, method: string, data?: unknown): Promise<ActionResult<T>> {
|
|
try {
|
|
const response = await fetch(url + path, {
|
|
method, cache: 'no-store', headers: { 'Content-Type': 'application/json' },
|
|
...(data !== undefined && { body: JSON.stringify(data) }),
|
|
});
|
|
const result = await response.json();
|
|
if (!response.ok) return { success: false, errors: Array.isArray(result.message) ? result.message : [result.message ?? 'Aktion fehlgeschlagen'] };
|
|
if (method !== 'GET') revalidatePath('/units/templates');
|
|
return { success: true, data: result };
|
|
} catch {
|
|
return { success: false, errors: ['Keine Verbindung zum Backend. Bitte vor erneutem Speichern oder Einfügen die Liste prüfen.'] };
|
|
}
|
|
}
|
|
export async function api_templates_list() { return request<UnitTemplate[]>('', 'GET'); }
|
|
export async function api_templates_save(data: UnitTemplateData, id?: string) {
|
|
return request<UnitTemplate>(id ? `/${encodeURIComponent(id)}` : '', id ? 'PUT' : 'POST', data);
|
|
}
|
|
export async function api_templates_fromUnit(id: string, name: string) {
|
|
return request<UnitTemplate>(`/from-unit/${encodeURIComponent(id)}`, 'POST', { name });
|
|
}
|
|
export async function api_templates_delete(id: string) { return request<{ success: boolean }>(`/${encodeURIComponent(id)}`, 'DELETE'); }
|
|
export async function api_templates_insert(id: string, data: UnitCopy) {
|
|
const result = await request<UnitResponse>(`/${encodeURIComponent(id)}/instantiate`, 'POST', data);
|
|
if (result.success) {
|
|
revalidatePath('/units');
|
|
revalidatePath('/signals');
|
|
revalidatePath('/hardware/io-zuordnung');
|
|
revalidatePath('/hardware/zuordnung-uebersicht');
|
|
}
|
|
return result;
|
|
}
|