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

105 lines
3.1 KiB
TypeScript
Raw Normal View History

import { db } from "@/lib/db"
import { NextResponse } from "next/server";
import fetchUserWithImpersonation from "@/lib/fetch-user-impersonation";
import { ActionType, Prisma } from "@prisma/client";
export async function GET(req: Request) {
try {
const user = await fetchUserWithImpersonation(req)
if (!user) {
return new NextResponse("Unauthorized", { status: 401 });
}
const actions = await db.group.findMany({
where: {
userId: user.id
}
})
return NextResponse.json(actions.map(({userId, ...attrs}) => attrs));
} catch (error) {
console.log("[GROUPS]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}
export async function POST(req: Request) {
try {
const user = await fetchUserWithImpersonation(req)
if (!user) {
return new NextResponse("Unauthorized", { status: 401 });
}
const { name, priority }: { name: string, priority: number } = await req.json();
if (!name)
return new NextResponse("Bad Request", { status: 400 });
const group = await db.group.create({
data: {
userId: user.id,
name: name.toLowerCase(),
priority
}
});
return NextResponse.json(group, { status: 200 });
} catch (error) {
console.log("[GROUPS]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}
export async function PUT(req: Request) {
try {
const user = await fetchUserWithImpersonation(req)
if (!user) {
return new NextResponse("Unauthorized", { status: 401 });
}
const { id, name, priority }: { id: string, name: string, priority: number } = await req.json();
if (!id)
return new NextResponse("Bad Request", { status: 400 });
if (!name && !priority)
return new NextResponse("Bad Request", { status: 400 });
let data: any = {}
if (!!name)
data = { ...data, name: name.toLowerCase() }
if (!!priority)
data = { ...data, priority }
const group = await db.group.update({
where: {
id
},
data: data
});
return NextResponse.json(group, { status: 200 });
} catch (error) {
console.log("[GROUPS]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}
export async function DELETE(req: Request) {
try {
const user = await fetchUserWithImpersonation(req)
if (!user) {
return new NextResponse("Unauthorized", { status: 401 });
}
const { searchParams } = new URL(req.url)
const id = searchParams.get('id') as string
const group = await db.group.delete({
where: {
id
}
})
return NextResponse.json(group);
} catch (error) {
console.log("[GROUPS]", error);
return new NextResponse("Internal Error", { status: 500 });
}
}