feat(SW-360): Added register form with server action
This commit is contained in:
committed by
Chuma McPhoy
parent
c69e4b4b29
commit
e086857072
82
actions/registerUser.ts
Normal file
82
actions/registerUser.ts
Normal file
@@ -0,0 +1,82 @@
|
||||
"use server"
|
||||
|
||||
import { z } from "zod"
|
||||
|
||||
import * as api from "@/lib/api"
|
||||
import { profileServiceServerActionProcedure } from "@/server/trpc"
|
||||
|
||||
import { registerSchema } from "@/components/Forms/Register/schema"
|
||||
import { passwordValidator } from "@/utils/passwordValidator"
|
||||
import { phoneValidator } from "@/utils/phoneValidator"
|
||||
|
||||
const registerUserPayload = z.object({
|
||||
language: z.string(),
|
||||
firstName: z.string(),
|
||||
lastName: z.string(),
|
||||
email: z.string(),
|
||||
phoneNumber: phoneValidator("Phone is required"),
|
||||
dateOfBirth: z.string(),
|
||||
address: z.object({
|
||||
city: z.string().default(""),
|
||||
country: z.string().default(""),
|
||||
countryCode: z.string().default(""),
|
||||
zipCode: z.string().default(""),
|
||||
streetAddress: z.string().default(""),
|
||||
}),
|
||||
password: passwordValidator("Password is required"),
|
||||
})
|
||||
|
||||
export const registerUser = profileServiceServerActionProcedure
|
||||
.input(registerSchema)
|
||||
.mutation(async function ({ ctx, input }) {
|
||||
const payload = {
|
||||
...input,
|
||||
language: ctx.lang,
|
||||
phoneNumber: input.phoneNumber.replace(/\s+/g, ""),
|
||||
}
|
||||
|
||||
const parsedPayload = registerUserPayload.safeParse(payload)
|
||||
if (!parsedPayload.success) {
|
||||
console.error(
|
||||
"registerUser payload validation error",
|
||||
JSON.stringify({
|
||||
query: input,
|
||||
error: parsedPayload.error,
|
||||
})
|
||||
)
|
||||
|
||||
return false
|
||||
}
|
||||
|
||||
try {
|
||||
const apiResponse = await api.post(api.endpoints.v1.profile, {
|
||||
body: parsedPayload.data,
|
||||
headers: {
|
||||
Authorization: `Bearer ${ctx.serviceToken}`,
|
||||
},
|
||||
})
|
||||
|
||||
if (!apiResponse.ok) {
|
||||
const text = apiResponse.text()
|
||||
console.error(
|
||||
"registerUser api error",
|
||||
JSON.stringify({
|
||||
query: input,
|
||||
error: {
|
||||
status: apiResponse.status,
|
||||
statusText: apiResponse.statusText,
|
||||
error: text,
|
||||
},
|
||||
})
|
||||
)
|
||||
return false
|
||||
}
|
||||
|
||||
const json = await apiResponse.json()
|
||||
console.log("json", json)
|
||||
|
||||
return true
|
||||
} catch (error) {
|
||||
return false
|
||||
}
|
||||
})
|
||||
Reference in New Issue
Block a user