All files / src/lib/api responses.ts

100% Statements 250/250
100% Branches 18/18
100% Functions 12/12
100% Lines 250/250

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 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 2511x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 393x 393x 393x 393x 393x 393x 393x 393x 393x 393x 393x 393x 393x 393x 393x 393x 1x 1x 1x 1x 1x 1x 1x 60x 60x 60x 60x 60x 60x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 438x 438x 438x 438x 438x 438x 438x 438x 438x 438x 438x 438x 438x 438x 438x 438x 438x 438x 438x 1x 1x 1x 1x 1x 1x 1x 34x 34x 34x 34x 34x 34x 1x 1x 1x 1x 1x 1x 1x 1x 64x 64x 64x 64x 64x 1x 1x 1x 1x 1x 1x 1x 1x 18x 18x 18x 18x 18x 1x 1x 1x 1x 1x 1x 1x 1x 7x 7x 7x 7x 7x 7x 7x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x  
/**
 * Standardized API Response Helpers
 *
 * Provides consistent response formatting across all API endpoints.
 * Use these helpers instead of NextResponse.json() directly for consistent API responses.
 */
 
import { NextResponse } from "next/server";
 
// ============================================================================
// TYPES
// ============================================================================
 
export interface ApiSuccessResponse<T> {
  success: true;
  data: T;
  meta?: PaginationMeta | Record<string, unknown>;
}
 
export interface ApiErrorResponse {
  success: false;
  error: {
    code: string;
    message: string;
    details?: unknown;
  };
}
 
export type ApiResponse<T> = ApiSuccessResponse<T> | ApiErrorResponse;
 
export interface PaginationMeta {
  page: number;
  limit: number;
  total: number;
  pages: number;
  hasNext: boolean;
  hasPrev: boolean;
}
 
export interface ResponseOptions {
  status?: number;
  headers?: Record<string, string>;
}
 
// ============================================================================
// SUCCESS RESPONSES
// ============================================================================
 
/**
 * Create a success response with data
 *
 * @example
 * return successResponse(product);
 * return successResponse(products, { status: 200 });
 */
export function successResponse<T>(
  data: T,
  options?: ResponseOptions & { meta?: Record<string, unknown> }
): NextResponse<ApiSuccessResponse<T>> {
  const { status = 200, meta, headers = {} } = options || {};
 
  return NextResponse.json(
    {
      success: true as const,
      data,
      ...(meta && { meta })},
    {
      status,
      headers}
  );
}
 
/**
 * Create a success response for created resources (201)
 *
 * @example
 * return createdResponse(newProduct);
 */
export function createdResponse<T>(
  data: T,
  options?: Omit<ResponseOptions, "status"> & { meta?: Record<string, unknown> }
): NextResponse<ApiSuccessResponse<T>> {
  return successResponse(data, { ...options, status: 201 });
}
 
/**
 * Create a paginated response with metadata
 *
 * @example
 * return paginatedResponse(products, { page: 1, limit: 20, total: 100 });
 */
export function paginatedResponse<T>(
  data: T[],
  pagination: {
    page: number;
    limit: number;
    total: number;
  },
  options?: ResponseOptions
): NextResponse<ApiSuccessResponse<T[]>> {
  const { status = 200, headers = {} } = options || {};
  const pages = Math.ceil(pagination.total / pagination.limit);
 
  return NextResponse.json(
    {
      success: true as const,
      data,
      meta: {
        page: pagination.page,
        limit: pagination.limit,
        total: pagination.total,
        pages,
        hasNext: pagination.page < pages,
        hasPrev: pagination.page > 1}},
    {
      status,
      headers}
  );
}
 
/**
 * Create a no-content response (204)
 *
 * @example
 * return noContentResponse();
 */
export function noContentResponse(): NextResponse {
  return new NextResponse(null, { status: 204 });
}
 
// ============================================================================
// ERROR RESPONSES
// ============================================================================
 
/**
 * Create an error response
 *
 * @example
 * return errorResponse("VALIDATION_ERROR", "Invalid input", { status: 400 });
 * return errorResponse("NOT_FOUND", "Product not found", { status: 404 });
 */
export function errorResponse(
  code: string,
  message: string,
  options?: ResponseOptions & { details?: unknown }
): NextResponse<ApiErrorResponse> {
  const { status = 400, details, headers = {} } = options || {};
 
  return NextResponse.json(
    {
      success: false as const,
      error: {
        code,
        message,
        ...(details !== undefined && { details })}},
    {
      status,
      headers}
  );
}
 
/**
 * Create a validation error response (400)
 *
 * @example
 * return validationErrorResponse("Email is required", { field: "email" });
 */
export function validationErrorResponse(
  message: string,
  details?: unknown
): NextResponse<ApiErrorResponse> {
  return errorResponse("VALIDATION_ERROR", message, { status: 400, details });
}
 
/**
 * Create an unauthorized error response (401)
 *
 * @example
 * return unauthorizedResponse();
 * return unauthorizedResponse("Session expired");
 */
export function unauthorizedResponse(
  message = "Authentication required"
): NextResponse<ApiErrorResponse> {
  return errorResponse("UNAUTHORIZED", message, { status: 401 });
}
 
/**
 * Create a forbidden error response (403)
 *
 * @example
 * return forbiddenResponse();
 * return forbiddenResponse("Admin access required");
 */
export function forbiddenResponse(
  message = "Access denied"
): NextResponse<ApiErrorResponse> {
  return errorResponse("FORBIDDEN", message, { status: 403 });
}
 
/**
 * Create a not found error response (404)
 *
 * @example
 * return notFoundResponse("Product");
 * return notFoundResponse("User", "user-123");
 */
export function notFoundResponse(
  resource: string,
  id?: string | number
): NextResponse<ApiErrorResponse> {
  const message = id ? `${resource} with ID '${id}' not found` : `${resource} not found`;
  return errorResponse("NOT_FOUND", message, { status: 404 });
}
 
/**
 * Create a conflict error response (409)
 *
 * @example
 * return conflictResponse("Email already exists");
 */
export function conflictResponse(message: string): NextResponse<ApiErrorResponse> {
  return errorResponse("CONFLICT", message, { status: 409 });
}
 
/**
 * Create a rate limit error response (429)
 *
 * @example
 * return rateLimitResponse();
 * return rateLimitResponse("Too many requests, please try again later");
 */
export function rateLimitResponse(
  message = "Rate limit exceeded"
): NextResponse<ApiErrorResponse> {
  return errorResponse("RATE_LIMITED", message, { status: 429 });
}
 
/**
 * Create an internal server error response (500)
 *
 * @example
 * return internalErrorResponse();
 * return internalErrorResponse("Database connection failed");
 */
export function internalErrorResponse(
  message = "An unexpected error occurred"
): NextResponse<ApiErrorResponse> {
  return errorResponse("INTERNAL_ERROR", message, { status: 500 });
}