Files
desa-darmasaba/src/app/api/[[...slugs]]/_lib/user/updt.ts
2025-09-02 11:28:48 +08:00

48 lines
1.4 KiB
TypeScript

import { Context } from "elysia";
import prisma from "@/lib/prisma";
import bcrypt from "bcryptjs";
type FormEditUser = {
nama?: string;
email?: string;
password?: string;
roleId?: string;
instansi?: string;
isActive?: boolean;
};
export default async function userEdit(context: Context) {
const { id } = context.params as { id: string };
const body = (await context.body) as FormEditUser;
if (!id) throw new Error("ID user wajib diisi");
try {
const existing = await prisma.user.findUnique({ where: { id } });
if (!existing) throw new Error("User tidak ditemukan");
let hashedPassword: string | undefined;
if (body.password) {
hashedPassword = await bcrypt.hash(body.password, 10);
}
const updated = await prisma.user.update({
where: { id },
data: {
nama: body.nama ?? existing.nama,
email: body.email ?? existing.email,
password: hashedPassword ?? existing.password,
roleId: body.roleId ?? existing.roleId,
instansi: body.instansi ?? existing.instansi,
isActive: body.isActive ?? existing.isActive,
},
include: { role: true },
});
return { success: true, message: "User berhasil diperbarui", data: updated };
} catch (error) {
console.error("Error updating user:", error);
throw new Error("Gagal mengedit user: " + (error as Error).message);
}
}