Skip to content

🪢 Open source agent evals & observability: Trace, evaluate, and improve LLM applications with one open platform.

2.7 KB
Raw Blame
import { prisma } from "@langfuse/shared/src/db";
import { logger } from "@langfuse/shared/src/server";
import { organizationNameSchema } from "@/src/features/organizations/utils/organizationNameSchema";
import { auditLog } from "@/src/features/audit-logs/auditLog";
import { type NextApiRequest, type NextApiResponse } from "next";
import { z } from "zod";

export async function handleGetOrganizations(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  const organizations = await prisma.organization.findMany({
    select: {
      id: true,
      name: true,
      createdAt: true,
      metadata: true,
      projects: {
        select: {
          id: true,
          name: true,
          metadata: true,
          createdAt: true,
          updatedAt: true,
        },
        where: {
          deletedAt: null,
        },
      },
    },
  });
  return res.status(200).json({
    organizations: organizations.map((org) => ({
      ...org,
      metadata: org.metadata ?? {},
      projects: org.projects,
    })),
  });
}

export async function handleCreateOrganization(
  req: NextApiRequest,
  res: NextApiResponse,
) {
  const validationResult = z
    .object({ name: organizationNameSchema })
    .safeParse(req.body);

  if (!validationResult.success) {
    res.status(400).json({
      error: "Invalid request body",
      details: z.formatError(validationResult.error),
    });
    return;
  }

  const { name } = validationResult.data;

  const { metadata } = req.body;
  if (metadata !== undefined && typeof metadata !== "object") {
    try {
      JSON.parse(metadata);
    } catch (error) {
      return res.status(400).json({
        message: `Invalid metadata. Should be a valid JSON object: ${error}`,
      });
    }
  }

  // Create the organization in the database
  const organization = await prisma.organization.create({
    data: {
      name,
      metadata,
    },
    select: {
      id: true,
      name: true,
      createdAt: true,
      metadata: true,
      projects: {
        select: {
          id: true,
          name: true,
          metadata: true,
          createdAt: true,
          updatedAt: true,
        },
        where: {
          deletedAt: null,
        },
      },
    },
  });

  // Log the organization creation
  await auditLog({
    resourceType: "organization",
    resourceId: organization.id,
    action: "create",
    orgId: organization.id,
    orgRole: "ADMIN",
    after: organization,
    apiKeyId: "ADMIN_KEY",
  });

  logger.info(`Created organization ${organization.id} via admin API`);

  return res.status(201).json({
    id: organization.id,
    name: organization.name,
    createdAt: organization.createdAt,
    metadata: organization.metadata ?? {},
    projects: organization.projects,
  });
}