рефакторинг
This commit is contained in:
@@ -1,198 +0,0 @@
|
||||
export interface CreateTemplateInput {
|
||||
name: string
|
||||
description?: string
|
||||
elements: Record<string, any>
|
||||
}
|
||||
|
||||
export interface CreateTemplateOutput {
|
||||
id: string
|
||||
}
|
||||
|
||||
export interface GetTemplatesOutput {
|
||||
templates: ApiTemplate[]
|
||||
}
|
||||
|
||||
export interface GetTemplateOutput {
|
||||
template: ApiTemplate | null
|
||||
}
|
||||
|
||||
export interface PatchTemplateInput {
|
||||
name?: string | null
|
||||
description?: string | null
|
||||
elements?: Record<string, any> | null
|
||||
}
|
||||
|
||||
export interface PatchTemplateOutput {
|
||||
id: string
|
||||
}
|
||||
|
||||
export interface ApiTemplate {
|
||||
id: string
|
||||
name: string
|
||||
description?: string | null
|
||||
elements: Record<string, any>
|
||||
created_at: string
|
||||
updated_at: string
|
||||
deleted_at?: string | null
|
||||
}
|
||||
|
||||
// Импортируем типы для преобразования
|
||||
import { getDefaultLayoutSettings, migrateTemplateElement } from '../lib/utils'
|
||||
import { Template, TemplateElement } from '../type/template'
|
||||
|
||||
// Утилитарные функции для преобразования данных
|
||||
|
||||
// Преобразование API шаблона в внутренний формат
|
||||
export function apiTemplateToTemplate(apiTemplate: ApiTemplate): Template {
|
||||
// Преобразуем elements из Record<string, any> в TemplateElement[]
|
||||
const elements: TemplateElement[] = Object.values(apiTemplate.elements || {})
|
||||
.map(el => migrateTemplateElement(el))
|
||||
.sort((a, b) => (a.order || 0) - (b.order || 0))
|
||||
|
||||
return {
|
||||
id: apiTemplate.id,
|
||||
name: apiTemplate.name,
|
||||
description: apiTemplate.description || undefined,
|
||||
elements,
|
||||
layoutSettings: getDefaultLayoutSettings(),
|
||||
createdAt: new Date(apiTemplate.created_at),
|
||||
updatedAt: new Date(apiTemplate.updated_at),
|
||||
}
|
||||
}
|
||||
|
||||
// Преобразование внутреннего шаблона в API формат для создания
|
||||
export function templateToCreateInput(
|
||||
template: Omit<Template, 'id' | 'createdAt' | 'updatedAt'>
|
||||
): CreateTemplateInput {
|
||||
// Преобразуем элементы в Record<string, any>
|
||||
const elements: Record<string, any> = {}
|
||||
template.elements.forEach((element, index) => {
|
||||
elements[element.id] = element
|
||||
})
|
||||
|
||||
return {
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
elements,
|
||||
}
|
||||
}
|
||||
|
||||
// Преобразование внутреннего шаблона в API формат для обновления
|
||||
export function templateToPatchInput(template: Template): PatchTemplateInput {
|
||||
// Преобразуем элементы в Record<string, any>
|
||||
const elements: Record<string, any> = {}
|
||||
template.elements.forEach((element, index) => {
|
||||
elements[element.id] = element
|
||||
})
|
||||
|
||||
return {
|
||||
name: template.name,
|
||||
description: template.description,
|
||||
elements,
|
||||
}
|
||||
}
|
||||
|
||||
// API создание шаблона
|
||||
export async function createTemplate(
|
||||
template: CreateTemplateInput
|
||||
): Promise<CreateTemplateOutput> {
|
||||
try {
|
||||
const response = await fetch('/api/templates/', {
|
||||
method: 'POST',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(template),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`)
|
||||
}
|
||||
|
||||
const result: CreateTemplateOutput = await response.json()
|
||||
return result
|
||||
} catch (error) {
|
||||
console.error('Ошибка при создании шаблона:', error)
|
||||
throw new Error('Ошибка при создании шаблона на сервере')
|
||||
}
|
||||
}
|
||||
|
||||
// API получение всех шаблонов
|
||||
export async function getTemplates(): Promise<GetTemplatesOutput> {
|
||||
try {
|
||||
const response = await fetch('/api/templates/', {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`)
|
||||
}
|
||||
|
||||
const result: GetTemplatesOutput = await response.json()
|
||||
return result
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении шаблонов:', error)
|
||||
throw new Error('Ошибка при получении шаблонов с сервера')
|
||||
}
|
||||
}
|
||||
|
||||
// API получение конкретного шаблона
|
||||
export async function getTemplate(
|
||||
templateId: string
|
||||
): Promise<GetTemplateOutput> {
|
||||
try {
|
||||
const response = await fetch(`/api/templates/${templateId}`, {
|
||||
method: 'GET',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`)
|
||||
}
|
||||
|
||||
const result: GetTemplateOutput = await response.json()
|
||||
return result
|
||||
} catch (error) {
|
||||
console.error('Ошибка при получении шаблона:', error)
|
||||
throw new Error('Ошибка при получении шаблона с сервера')
|
||||
}
|
||||
}
|
||||
|
||||
// API обновление шаблона
|
||||
export async function patchTemplate(
|
||||
templateId: string,
|
||||
template: PatchTemplateInput
|
||||
): Promise<PatchTemplateOutput> {
|
||||
try {
|
||||
const response = await fetch(`/api/templates/${templateId}`, {
|
||||
method: 'PATCH',
|
||||
headers: {
|
||||
'Content-Type': 'application/json',
|
||||
},
|
||||
body: JSON.stringify(template),
|
||||
})
|
||||
|
||||
if (!response.ok) {
|
||||
throw new Error(`HTTP error! status: ${response.status}`)
|
||||
}
|
||||
|
||||
const result: PatchTemplateOutput = await response.json()
|
||||
return result
|
||||
} catch (error) {
|
||||
console.error('Ошибка при обновлении шаблона:', error)
|
||||
throw new Error('Ошибка при обновлении шаблона на сервере')
|
||||
}
|
||||
}
|
||||
|
||||
// Алиас для удобства использования
|
||||
export async function updateTemplate(
|
||||
template: Template
|
||||
): Promise<PatchTemplateOutput> {
|
||||
const patchInput = templateToPatchInput(template)
|
||||
return patchTemplate(template.id, patchInput)
|
||||
}
|
||||
Reference in New Issue
Block a user