68 lines
1.5 KiB
TypeScript
68 lines
1.5 KiB
TypeScript
import { zodResolver } from '@hookform/resolvers/zod'
|
|
import { data } from 'react-router'
|
|
import { getValidatedFormData } from 'remix-hook-form'
|
|
import { XiorError } from 'xior'
|
|
|
|
import { createCategoryRequest } from '~/apis/admin/create-category'
|
|
import { handleCookie } from '~/libs/cookies'
|
|
import {
|
|
createCategorySchema,
|
|
type TCategorySchema,
|
|
} from '~/pages/dashboard-category-create'
|
|
|
|
import type { Route } from './+types/actions.register'
|
|
|
|
export const action = async ({ request }: Route.ActionArgs) => {
|
|
const { staffToken } = await handleCookie(request)
|
|
try {
|
|
const {
|
|
errors,
|
|
data: payload,
|
|
receivedValues: defaultValues,
|
|
} = await getValidatedFormData<TCategorySchema>(
|
|
request,
|
|
zodResolver(createCategorySchema),
|
|
false,
|
|
)
|
|
|
|
if (errors) {
|
|
return data({ success: false, errors, defaultValues }, { status: 400 })
|
|
}
|
|
|
|
const { data: categoryData } = await createCategoryRequest({
|
|
accessToken: staffToken,
|
|
payload,
|
|
})
|
|
|
|
return data(
|
|
{
|
|
success: true,
|
|
categoryData,
|
|
},
|
|
{
|
|
status: 200,
|
|
statusText: 'OK',
|
|
},
|
|
)
|
|
} catch (error) {
|
|
if (error instanceof XiorError) {
|
|
return data(
|
|
{
|
|
success: false,
|
|
message: error?.response?.data?.error?.message || error.message,
|
|
},
|
|
{
|
|
status: error?.response?.status || 500,
|
|
},
|
|
)
|
|
}
|
|
return data(
|
|
{
|
|
success: false,
|
|
message: 'Internal server error',
|
|
},
|
|
{ status: 500 },
|
|
)
|
|
}
|
|
}
|