Files
bewell-in-ua/actions/admin/entity.ts
2025-03-11 02:54:09 +02:00

108 lines
2.3 KiB
TypeScript

'use server'
import {EntityLocale, EntityType, Meta} from '@prisma/client'
import {z} from 'zod'
import {i18nLocalesCodes} from '@/i18n-config'
import {STORE_ID} from '@/lib/config/constants'
import {db} from '@/lib/db/prisma/client'
import {createEntityFormSchema} from '@/lib/schemas/admin/entity'
import {
cleanEmptyParams,
dbErrorHandling,
slug as slugger,
toEmptyParams
} from '@/lib/utils'
export const onEntityCreateEditAction = async (
formData: z.infer<typeof createEntityFormSchema>
) => {
const validatedData = createEntityFormSchema.parse(formData)
if (!validatedData) return {error: 'Недійсні вхідні дані'}
if (validatedData.locales.length < i18nLocalesCodes.length) {
return {error: 'Заповніть всі мови'}
}
const {published, media, type, slug, scopes} = validatedData
const meta: Meta[] = []
for (const i in validatedData.meta) {
const normalizedMeta: any = cleanEmptyParams(validatedData.meta[i])
meta.push(normalizedMeta)
}
const locales: EntityLocale[] = []
for (const i in validatedData.locales) {
const locale = validatedData.locales[i]
const {title, lang} = locale
const slug = slugger(title, lang)
//const result = await getProductBySlug({slug, lang})
const result = null
if (!result) {
const normalized: any = cleanEmptyParams({slug, ...locale})
locales.push(normalized)
} else {
return {error: `Сутність з такою назвою ${title} вже існує`}
}
}
try {
const newEntity = await db.entity.create({
data: {
published,
scopes: scopes ? JSON.parse(scopes) : null,
type: type as EntityType,
slug: slug || null,
media: media || null,
locales: {
create: locales
}
}
})
return {success: JSON.stringify(newEntity, null, 2)}
} catch (error) {
return dbErrorHandling(error)
}
}
export const getBlockEntity = async (scope: string) => {
return db.entity.findMany({
where: {
published: true,
storeId: STORE_ID,
type: 'block',
scopes: {
array_contains: [scope]
}
},
include: {
locales: true
},
orderBy: {
position: 'asc'
}
})
}
export const getPageEntityBySlug = async (slug: string) => {
return db.entity.findFirst({
where: {
published: true,
storeId: STORE_ID,
type: 'page',
slug
},
include: {
locales: true
}
})
}