101 lines
2.7 KiB
TypeScript
101 lines
2.7 KiB
TypeScript
"use server"
|
|
|
|
import { z } from "zod"
|
|
|
|
import { ApiLang } from "@/constants/languages"
|
|
import * as api from "@/lib/api"
|
|
import { protectedServerActionProcedure } from "@/server/trpc"
|
|
|
|
import { editProfileSchema } from "@/components/Forms/Edit/Profile/schema"
|
|
import { countriesMap } from "@/components/TempDesignSystem/Form/Country/countries"
|
|
import { phoneValidator } from "@/utils/phoneValidator"
|
|
|
|
import { Status } from "@/types/components/myPages/myProfile/edit"
|
|
|
|
const editProfilePayload = z
|
|
.object({
|
|
address: z.object({
|
|
city: z.string().optional(),
|
|
countryCode: z.nativeEnum(countriesMap),
|
|
streetAddress: z.string().optional(),
|
|
zipCode: z.string().min(1, { message: "Zip code is required" }),
|
|
}),
|
|
dateOfBirth: z.string(),
|
|
email: z.string().email(),
|
|
language: z.nativeEnum(ApiLang),
|
|
newPassword: z.string().optional(),
|
|
password: z.string().optional(),
|
|
phoneNumber: phoneValidator("Phone is required"),
|
|
})
|
|
.transform((data) => {
|
|
if (!data.password || !data.newPassword) {
|
|
delete data.password
|
|
delete data.newPassword
|
|
}
|
|
return data
|
|
})
|
|
|
|
export const editProfile = protectedServerActionProcedure
|
|
.input(editProfileSchema)
|
|
.mutation(async function ({ ctx, input }) {
|
|
const payload = editProfilePayload.safeParse(input)
|
|
if (!payload.success) {
|
|
return {
|
|
data: input,
|
|
issues: payload.error.issues.map((issue) => ({
|
|
field: issue.path.join("."),
|
|
message: issue.message,
|
|
})),
|
|
message: "Validation failed.",
|
|
status: Status.error,
|
|
}
|
|
}
|
|
|
|
const response = await api.patch(api.endpoints.v1.profile, {
|
|
body: payload.data,
|
|
cache: "no-store",
|
|
headers: {
|
|
Authorization: `Bearer ${ctx.session.token.access_token}`,
|
|
},
|
|
})
|
|
|
|
if (!response.ok) {
|
|
console.info(`Response not ok`)
|
|
console.error(response)
|
|
return {
|
|
data: input,
|
|
issues: [],
|
|
message: "Server error",
|
|
status: Status.error,
|
|
}
|
|
}
|
|
|
|
const json = await response.json()
|
|
if (json.errors?.length) {
|
|
json.errors.forEach((error: any) => {
|
|
console.info(`API Fail in response`)
|
|
console.error(error)
|
|
})
|
|
}
|
|
|
|
const validatedData = editProfileSchema.safeParse(json.data.attributes)
|
|
if (!validatedData.success) {
|
|
console.log({ ees: validatedData.error })
|
|
return {
|
|
data: input,
|
|
issues: validatedData.error.issues.map((issue) => ({
|
|
field: issue.path.join("."),
|
|
message: issue.message,
|
|
})),
|
|
message: "Data is insufficient",
|
|
status: Status.error,
|
|
}
|
|
}
|
|
|
|
return {
|
|
data: validatedData.data,
|
|
message: "All good!",
|
|
status: Status.success,
|
|
}
|
|
})
|