owltide/server/api/admin/user.patch.ts
Hornwitser 985b8e0950 Refactor base types for entities and tombstones
Rename the base Entity type to ApiEntity, and the base EntityToombstone
to ApiTombstone to better reflect the reality that its only used in the
API interface and that the client and server types uses its own base if
any.

Remove EntityLiving and pull EntityTombstone out of of the base entity
type so that the types based on ApiEntity are always living entities and
if it's possible for it to contain tombstone this will be explicitly
told with the type including a union with ApiTombstone.

Refactor the types of the ClientEntity and ClientMap to better reflect
the types of the entities it stores and converts to/from.
2025-06-24 15:19:11 +02:00

79 lines
1.8 KiB
TypeScript

import { readUsers, type ServerUser, writeUsers } from "~/server/database";
import { type ApiTombstone, type ApiUser, apiUserPatchSchema } from "~/shared/types/api";
import { z } from "zod/v4-mini";
import { broadcastEvent } from "~/server/streams";
function serverUserToApi(user: ServerUser): ApiUser | ApiTombstone {
if (user.deleted) {
return {
id: user.id,
updatedAt: user.updatedAt,
deleted: true,
}
}
return {
id: user.id,
updatedAt: user.updatedAt,
type: user.type,
name: user.name,
};
}
export default defineEventHandler(async (event) => {
const session = await requireServerSession(event);
if (session.account.type !== "admin") {
throw createError({
statusCode: 403,
statusMessage: "Forbidden",
});
}
const { success, error, data: patch } = apiUserPatchSchema.safeParse(await readBody(event));
if (!success) {
throw createError({
status: 400,
statusText: "Bad Request",
message: z.prettifyError(error),
});
}
const users = await readUsers();
const user = users.find(user => user.id === patch.id);
if (!user || user.deleted) {
throw createError({
status: 409,
statusText: "Conflict",
message: "User does not exist",
});
}
if (patch.type) {
if (patch.type === "anonymous" || user.type === "anonymous") {
throw createError({
status: 409,
statusText: "Conflict",
message: "Anonymous user type cannot be changed.",
});
}
user.type = patch.type;
}
if (patch.name) {
if (user.type === "anonymous") {
throw createError({
status: 409,
statusText: "Conflict",
message: "Anonymous user cannot have name set.",
});
}
user.name = patch.name;
}
user.updatedAt = new Date().toISOString();
await writeUsers(users);
broadcastEvent({
type: "user-update",
data: serverUserToApi(user),
})
// Update Schedule counts.
await updateScheduleInterestedCounts(users);
})