From 609ec18058778cafca87ae127ec19f948abd50c6 Mon Sep 17 00:00:00 2001 From: naskya Date: Thu, 25 Jan 2024 05:23:39 +0900 Subject: [PATCH] chore: add utility for unsafe type casting --- packages/backend/src/prelude/await-all.ts | 4 +++- packages/backend/src/prelude/unsafe-cast.ts | 4 ++++ .../src/server/api/endpoints/admin/set-emoji-moderator.ts | 8 +++----- 3 files changed, 10 insertions(+), 6 deletions(-) create mode 100644 packages/backend/src/prelude/unsafe-cast.ts diff --git a/packages/backend/src/prelude/await-all.ts b/packages/backend/src/prelude/await-all.ts index ce11eb87b..d81870a57 100644 --- a/packages/backend/src/prelude/await-all.ts +++ b/packages/backend/src/prelude/await-all.ts @@ -1,10 +1,12 @@ +import { unsafeCast } from "./unsafe-cast.js"; + export type Promiseable = { [K in keyof T]: Promise | T[K]; }; export async function awaitAll(obj: Promiseable): Promise { const target = {} as T; - const keys = Object.keys(obj) as unknown as (keyof T)[]; + const keys = unsafeCast<(keyof T)[]>(Object.keys(obj)); const values = Object.values(obj) as any[]; const resolvedValues = await Promise.all( diff --git a/packages/backend/src/prelude/unsafe-cast.ts b/packages/backend/src/prelude/unsafe-cast.ts new file mode 100644 index 000000000..f7e251fa3 --- /dev/null +++ b/packages/backend/src/prelude/unsafe-cast.ts @@ -0,0 +1,4 @@ +// unsafe type cast +export function unsafeCast(val: unknown): T { + return val as T; +} diff --git a/packages/backend/src/server/api/endpoints/admin/set-emoji-moderator.ts b/packages/backend/src/server/api/endpoints/admin/set-emoji-moderator.ts index 0bc79c03b..8a4c2f161 100644 --- a/packages/backend/src/server/api/endpoints/admin/set-emoji-moderator.ts +++ b/packages/backend/src/server/api/endpoints/admin/set-emoji-moderator.ts @@ -1,6 +1,8 @@ import { Users } from "@/models/index.js"; import { publishInternalEvent } from "@/services/stream.js"; import define from "../../define.js"; +import type { EmojiModPerm } from "@/models/entities/user.js"; +import { unsafeCast } from "@/prelude/unsafe-cast.js"; export const meta = { tags: ["admin"], @@ -31,12 +33,8 @@ export default define(meta, paramDef, async (ps) => { ); } - const _emojiModPerm = - (ps.emojiModPerm as "unauthorized" | "add" | "mod" | "full") ?? - "unauthorized"; - await Users.update(user.id, { - emojiModPerm: _emojiModPerm, + emojiModPerm: unsafeCast(ps.emojiModPerm), }); publishInternalEvent("userChangeModeratorState", {