hermes-web/app/api/settings/groups/users/route.ts

47 lines
1.8 KiB
TypeScript

import { db } from "@/lib/db"
import { NextResponse } from "next/server";
import fetchUserWithImpersonation from "@/lib/fetch-user-impersonation";
import { z } from "zod";
const groupIdSchema = z.string({
required_error: "Group ID should be available.",
invalid_type_error: "Group ID must be a string"
}).regex(/^[\w\-\=]{1,32}$/, "Group ID must contain only letters, numbers, dashes, underscores & equal signs.")
export async function GET(req: Request) {
try {
const user = await fetchUserWithImpersonation(req)
if (!user)
return NextResponse.json({ message: 'Unauthorized.', error: null, value: null }, { status: 401 })
const { searchParams } = new URL(req.url)
const groupId = searchParams.get('groupId') as string
if (groupId) {
const groupIdValidation = await groupIdSchema.safeParseAsync(groupId)
if (!groupIdValidation.success)
return NextResponse.json({ message: 'groupId does not meet requirements.', error: JSON.parse(groupIdValidation.error['message'])[0], value: null }, { status: 400 })
}
let chatters: { userId: string, groupId: string, chatterId: bigint, chatterLabel: string }[]
if (groupId)
chatters = await db.chatterGroup.findMany({
where: {
userId: user.id,
groupId
}
})
else
chatters = await db.chatterGroup.findMany({
where: {
userId: user.id
}
})
return NextResponse.json(chatters.map(u => ({ ...u, chatterId: Number(u.chatterId) }))
.map(({ userId, chatterLabel, ...attrs }) => attrs))
} catch (error) {
return NextResponse.json({ message: 'Failed to get groups', error: error, value: null }, { status: 500 })
}
}