Merge branch 'feat/register' of https://github.com/digitalsolutiongroup/amati into feat/register

This commit is contained in:
abiyasa05 2024-08-13 10:38:38 +07:00
commit e6d5f61c70

View File

@ -3,6 +3,7 @@ import { HTTPException } from "hono/http-exception";
import db from "../../drizzle"; import db from "../../drizzle";
import { respondents } from "../../drizzle/schema/respondents"; import { respondents } from "../../drizzle/schema/respondents";
import { users } from "../../drizzle/schema/users"; import { users } from "../../drizzle/schema/users";
import { rolesToUsers } from "../../drizzle/schema/rolesToUsers";
import { hashPassword } from "../../utils/passwordUtils"; import { hashPassword } from "../../utils/passwordUtils";
import requestValidator from "../../utils/requestValidator"; import requestValidator from "../../utils/requestValidator";
import authInfo from "../../middlewares/authInfo"; import authInfo from "../../middlewares/authInfo";
@ -21,6 +22,23 @@ const registerFormSchema = z.object({
workExperience: z.string().min(1).max(255), workExperience: z.string().min(1).max(255),
address: z.string().min(1), address: z.string().min(1),
phoneNumber: z.string().min(1).max(13), phoneNumber: z.string().min(1).max(13),
isEnabled: z.string().default("false"),
roles: z
.string()
.refine(
(data) => {
try {
const parsed = JSON.parse(data);
return Array.isArray(parsed);
} catch {
return false;
}
},
{
message: "Roles must be an array",
}
)
.optional(),
}); });
const respondentsRoute = new Hono<HonoEnv>() const respondentsRoute = new Hono<HonoEnv>()
@ -32,6 +50,8 @@ const respondentsRoute = new Hono<HonoEnv>()
async (c) => { async (c) => {
const formData = c.req.valid("json"); const formData = c.req.valid("json");
console.log("Form Data:", formData);
// Build conditions based on available formData // Build conditions based on available formData
const conditions = []; const conditions = [];
if (formData.email) { if (formData.email) {
@ -44,11 +64,15 @@ const respondentsRoute = new Hono<HonoEnv>()
.from(users) .from(users)
.where(or(...conditions)); .where(or(...conditions));
console.log("Existing Users:", existingUser);
const existingRespondent = await db const existingRespondent = await db
.select() .select()
.from(respondents) .from(respondents)
.where(eq(respondents.phoneNumber, formData.phoneNumber)); .where(eq(respondents.phoneNumber, formData.phoneNumber));
console.log("Existing Respondents:", existingRespondent);
if (existingUser.length > 0) { if (existingUser.length > 0) {
throw new HTTPException(400, { throw new HTTPException(400, {
message: "Email atau username sudah terdaftar", message: "Email atau username sudah terdaftar",
@ -64,6 +88,8 @@ const respondentsRoute = new Hono<HonoEnv>()
// Hash the password // Hash the password
const hashedPassword = await hashPassword(formData.password); const hashedPassword = await hashPassword(formData.password);
console.log("Hashed Password:", hashedPassword);
// Start a transaction // Start a transaction
try { try {
const result = await db.transaction(async (trx) => { const result = await db.transaction(async (trx) => {
@ -75,30 +101,50 @@ const respondentsRoute = new Hono<HonoEnv>()
username: formData.username, username: formData.username,
email: formData.email, email: formData.email,
password: hashedPassword, password: hashedPassword,
isEnabled: formData.isEnabled?.toLowerCase() === "true" || true,
}) })
.returning(); .returning();
console.log("New User:", newUser);
// Create respondent // Create respondent
await trx await trx.insert(respondents).values({
.insert(respondents) companyName: formData.companyName,
.values({ position: formData.position,
companyName: formData.companyName, workExperience: formData.workExperience,
position: formData.position, address: formData.address,
workExperience: formData.workExperience, phoneNumber: formData.phoneNumber,
address: formData.address, userId: newUser.id,
phoneNumber: formData.phoneNumber, });
userId: newUser.id,
}); console.log("Respondent Created for User ID:", newUser.id);
// If roles are included in the request, add to rolesToUsers
if (formData.roles) {
try {
const roles = JSON.parse(formData.roles) as string[];
if (roles.length) {
await trx.insert(rolesToUsers).values(
roles.map((role) => ({
userId: newUser.id,
roleId: role,
}))
);
}
} catch (error) {
console.error("Error parsing roles:", error);
throw new HTTPException(400, {
message: "Invalid roles format",
});
}
}
return newUser; return newUser;
}); });
return c.json( return c.json({
{ message: "User and respondent created successfully",
message: "User and respondent created successfully", }, 201);
},
201
);
} catch (error) { } catch (error) {
console.error("Error creating user and respondent:", error); console.error("Error creating user and respondent:", error);
throw new HTTPException(500, { throw new HTTPException(500, {