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

47 lines
1.8 KiB
TypeScript
Raw Permalink Normal View History

import { db } from "@/lib/db"
import { NextResponse } from "next/server";
import fetchUserWithImpersonation from "@/lib/fetch-user-impersonation";
2024-08-25 17:35:46 -04:00
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)
2024-08-25 17:35:46 -04:00
return NextResponse.json({ message: 'Unauthorized.', error: null, value: null }, { status: 401 })
const { searchParams } = new URL(req.url)
const groupId = searchParams.get('groupId') as string
2024-08-25 17:35:46 -04:00
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 }[]
2024-08-25 17:35:46 -04:00
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) }))
2024-08-25 17:35:46 -04:00
.map(({ userId, chatterLabel, ...attrs }) => attrs))
} catch (error) {
2024-08-25 17:35:46 -04:00
return NextResponse.json({ message: 'Failed to get groups', error: error, value: null }, { status: 500 })
}
}