74 lines
2.0 KiB
TypeScript
74 lines
2.0 KiB
TypeScript
import { v4 as uuidv4 } from 'uuid';
|
|
import { type ChartInstance, type LayoutItem, type Template } from '@/domain';
|
|
import { type ITemplateUseCase } from '../ports/input/ITemplateUseCase';
|
|
import { type IStorageGateway } from '../ports/output/IStorageGateway';
|
|
|
|
const TEMPLATE_KEY_PREFIX = 'template:';
|
|
|
|
export class TemplateUseCase implements ITemplateUseCase {
|
|
constructor(private readonly storage: IStorageGateway) {}
|
|
|
|
save(
|
|
name: string,
|
|
description: string,
|
|
charts: ChartInstance[],
|
|
layout: LayoutItem[],
|
|
theme: string,
|
|
): Template {
|
|
const template: Template = {
|
|
id: uuidv4(),
|
|
name,
|
|
description,
|
|
charts: charts.map(({ dataSetId: _, ...rest }) => rest),
|
|
layout,
|
|
theme,
|
|
createdAt: new Date().toISOString(),
|
|
};
|
|
|
|
this.storage.save(`${TEMPLATE_KEY_PREFIX}${template.id}`, template);
|
|
return template;
|
|
}
|
|
|
|
load(templateId: string): Template | null {
|
|
return this.storage.load<Template>(`${TEMPLATE_KEY_PREFIX}${templateId}`);
|
|
}
|
|
|
|
list(): Template[] {
|
|
const keys = this.storage.listKeys(TEMPLATE_KEY_PREFIX);
|
|
const templates: Template[] = [];
|
|
for (const key of keys) {
|
|
const template = this.storage.load<Template>(key);
|
|
if (template) {
|
|
templates.push(template);
|
|
}
|
|
}
|
|
return templates;
|
|
}
|
|
|
|
remove(templateId: string): void {
|
|
this.storage.remove(`${TEMPLATE_KEY_PREFIX}${templateId}`);
|
|
}
|
|
|
|
exportTemplate(templateId: string): string {
|
|
const template = this.load(templateId);
|
|
if (!template) {
|
|
throw new Error(`Template not found: ${templateId}`);
|
|
}
|
|
return JSON.stringify(template);
|
|
}
|
|
|
|
importTemplate(json: string): Template {
|
|
const parsed = JSON.parse(json) as Template;
|
|
|
|
// Assign a new ID to avoid collisions
|
|
const template: Template = {
|
|
...parsed,
|
|
id: uuidv4(),
|
|
createdAt: new Date().toISOString(),
|
|
};
|
|
|
|
this.storage.save(`${TEMPLATE_KEY_PREFIX}${template.id}`, template);
|
|
return template;
|
|
}
|
|
}
|