All files / src/app/api/admin/api-docs/history route.ts

0% Statements 0/163
100% Branches 0/0
0% Functions 0/1
0% Lines 0/163

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164                                                                                                                                                                                                                                                                                                                                       
/**
 * API Request History Endpoints
 *
 * Manages API request history for the admin documentation tester
 */

export const dynamic = "force-dynamic";

import { NextRequest, NextResponse } from 'next/server';
import { Session } from "next-auth";
import { prisma } from "@/lib/prisma";
import {
  withUser,
  withErrorHandling,
  successResponse,
  createdResponse,
  ApiError,
  ApiSuccessResponse,
  ApiErrorResponse } from "@/lib/api";
import { RouteContext } from "@/lib/api/middleware";
import type { AuthenticatedUser } from '@/lib/api/middleware/types';

// GET - Retrieve request history
async function handleGet(
  request: NextRequest,
  _context: RouteContext | undefined,
  _session: Session,
  user: AuthenticatedUser
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const userId = user.id;
  const { searchParams } = new URL(request.url);

  const limit = parseInt(searchParams.get("limit") || "50");
  const offset = parseInt(searchParams.get("offset") || "0");
  const endpointId = searchParams.get("endpointId");
  const method = searchParams.get("method");

  const where: { userId: number; endpointId?: string; method?: string } = { userId };
  if (endpointId) where.endpointId = endpointId;
  if (method) where.method = method;

  const [history, total] = await Promise.all([
    prisma.apiRequestHistory.findMany({
      where,
      orderBy: { createdAt: "desc" },
      take: limit,
      skip: offset,
      select: {
        id: true,
        endpointId: true,
        method: true,
        path: true,
        pathParams: true,
        queryParams: true,
        headers: true,
        body: true,
        useAuth: true,
        status: true,
        statusText: true,
        responseHeaders: true,
        responseBody: true,
        duration: true,
        createdAt: true}}),
    prisma.apiRequestHistory.count({ where }),
  ]);

  return successResponse({
    data: history,
    pagination: {
      total,
      limit,
      offset,
      hasMore: offset + limit < total}});
}

// POST - Save a new request to history
async function handlePost(
  request: NextRequest,
  _context: RouteContext | undefined,
  _session: Session,
  user: AuthenticatedUser
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const userId = user.id;
  const body = await request.json();

  const {
    endpointId,
    method,
    path,
    pathParams,
    queryParams,
    headers,
    requestBody,
    useAuth,
    status,
    statusText,
    responseHeaders,
    responseBody,
    duration} = body;

  // Validate required fields
  if (!endpointId || !method || !path || status === undefined) {
    throw ApiError.badRequest("Missing required fields");
  }

  const historyItem = await prisma.apiRequestHistory.create({
    data: {
      userId,
      endpointId,
      method,
      path,
      pathParams: pathParams || null,
      queryParams: queryParams || null,
      headers: headers || null,
      body: requestBody || null,
      useAuth: useAuth || false,
      status,
      statusText: statusText || "",
      responseHeaders: responseHeaders || null,
      responseBody: responseBody || null,
      duration: duration || 0}});

  return createdResponse(historyItem);
}

// DELETE - Clear request history
async function handleDelete(
  request: NextRequest,
  _context: RouteContext | undefined,
  _session: Session,
  user: AuthenticatedUser
): Promise<NextResponse<ApiSuccessResponse<unknown> | ApiErrorResponse>> {
  const userId = user.id;
  const { searchParams } = new URL(request.url);
  const id = searchParams.get("id");

  if (id) {
    // Delete specific history item
    const historyItem = await prisma.apiRequestHistory.findFirst({
      where: { id: parseInt(id), userId }});

    if (!historyItem) {
      throw ApiError.notFound("History item");
    }

    await prisma.apiRequestHistory.delete({
      where: { id: parseInt(id) }});

    return successResponse({ success: true });
  } else {
    // Clear all history for user
    const result = await prisma.apiRequestHistory.deleteMany({
      where: { userId }});

    return successResponse({
      success: true,
      deletedCount: result.count});
  }
}

export const GET = withErrorHandling(withUser(handleGet));
export const POST = withErrorHandling(withUser(handlePost));
export const DELETE = withErrorHandling(withUser(handleDelete));