Some checks failed
Docker Deploy / build-and-push (push) Has been cancelled
59 lines
1.5 KiB
TypeScript
59 lines
1.5 KiB
TypeScript
import type { APIRoute } from "astro";
|
|
import { db } from "../../../db";
|
|
import { users } from "../../../db/schema";
|
|
import { eq } from "drizzle-orm";
|
|
|
|
export const POST: APIRoute = async ({ request, locals, redirect }) => {
|
|
const user = locals.user;
|
|
const contentType = request.headers.get("content-type");
|
|
const isJson = contentType?.includes("application/json");
|
|
|
|
if (!user) {
|
|
if (isJson) {
|
|
return new Response(JSON.stringify({ error: "Unauthorized" }), {
|
|
status: 401,
|
|
});
|
|
}
|
|
return redirect("/login");
|
|
}
|
|
|
|
let name: string | undefined;
|
|
|
|
if (isJson) {
|
|
const body = await request.json();
|
|
name = body.name;
|
|
} else {
|
|
const formData = await request.formData();
|
|
name = formData.get("name") as string;
|
|
}
|
|
|
|
if (!name || name.trim().length === 0) {
|
|
const msg = "Name is required";
|
|
if (isJson) {
|
|
return new Response(JSON.stringify({ error: msg }), { status: 400 });
|
|
}
|
|
return new Response(msg, { status: 400 });
|
|
}
|
|
|
|
try {
|
|
await db
|
|
.update(users)
|
|
.set({ name: name.trim() })
|
|
.where(eq(users.id, user.id))
|
|
.run();
|
|
|
|
if (isJson) {
|
|
return new Response(JSON.stringify({ success: true }), { status: 200 });
|
|
}
|
|
|
|
return redirect("/dashboard/settings?success=profile");
|
|
} catch (error) {
|
|
console.error("Error updating profile:", error);
|
|
const msg = "Failed to update profile";
|
|
if (isJson) {
|
|
return new Response(JSON.stringify({ error: msg }), { status: 500 });
|
|
}
|
|
return new Response(msg, { status: 500 });
|
|
}
|
|
};
|