You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
86 lines
2.8 KiB
86 lines
2.8 KiB
import { dbGlobal } from "drizzle-pkg/lib/db";
|
|
import { users } from "drizzle-pkg/lib/schema/auth";
|
|
import { eq } from "drizzle-orm";
|
|
import { UNAUTHORIZED_MESSAGE } from "#server/constants/auth";
|
|
import { toPublicAuthError } from "#server/service/auth/errors";
|
|
import { delCache, requireUser } from "#server/utils/context";
|
|
|
|
export default defineWrappedResponseHandler(async (event) => {
|
|
try {
|
|
const user = await requireUser(event);
|
|
if (!user) {
|
|
throw createError({
|
|
statusCode: 401,
|
|
statusMessage: UNAUTHORIZED_MESSAGE,
|
|
});
|
|
}
|
|
|
|
const body = await readBody<{
|
|
// username?: string;
|
|
email?: string;
|
|
nickname?: string;
|
|
}>(event);
|
|
|
|
if (!body || Object.keys(body).length === 0) {
|
|
throw createError({
|
|
statusCode: 400,
|
|
statusMessage: "请提供要更新的字段",
|
|
});
|
|
}
|
|
|
|
const updateData: Partial<{
|
|
// username: string;
|
|
email: string | null;
|
|
nickname: string | null;
|
|
}> = {};
|
|
|
|
// if (body.username !== undefined) {
|
|
// if (typeof body.username !== "string" || body.username.trim().length === 0) {
|
|
// throw createError({ statusCode: 400, statusMessage: "用户名不能为空" });
|
|
// }
|
|
// if (body.username.length < 2 || body.username.length > 50) {
|
|
// throw createError({ statusCode: 400, statusMessage: "用户名长度需在2-50字符之间" });
|
|
// }
|
|
// updateData.username = body.username.trim();
|
|
// }
|
|
|
|
if (body.email !== undefined) {
|
|
if (body.email && !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(body.email)) {
|
|
throw createError({ statusCode: 400, statusMessage: "邮箱格式不正确" });
|
|
}
|
|
updateData.email = body.email?.trim() || null;
|
|
}
|
|
|
|
if (body.nickname !== undefined) {
|
|
updateData.nickname = body.nickname?.trim() || null;
|
|
}
|
|
|
|
if (Object.keys(updateData).length > 0) {
|
|
await dbGlobal
|
|
.update(users)
|
|
.set(updateData)
|
|
.where(eq(users.id, user.id));
|
|
|
|
// Invalidate me cache
|
|
await delCache(`auth:me:${user.id}`);
|
|
}
|
|
|
|
// Fetch updated user data
|
|
const [row] = await dbGlobal
|
|
.select({
|
|
id: users.id,
|
|
username: users.username,
|
|
email: users.email,
|
|
role: users.role,
|
|
nickname: users.nickname,
|
|
avatar: users.avatar,
|
|
})
|
|
.from(users)
|
|
.where(eq(users.id, user.id))
|
|
.limit(1);
|
|
|
|
return R.success({ user: row });
|
|
} catch (err) {
|
|
throw toPublicAuthError(err);
|
|
}
|
|
});
|