api-response.ts 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. import { NextResponse } from 'next/server';
  2. export const API_ERROR_CODES = {
  3. MISSING_REQUIRED_FIELD: 'MISSING_REQUIRED_FIELD',
  4. MISSING_API_KEY: 'MISSING_API_KEY',
  5. INVALID_REQUEST: 'INVALID_REQUEST',
  6. INVALID_URL: 'INVALID_URL',
  7. REDIRECT_NOT_ALLOWED: 'REDIRECT_NOT_ALLOWED',
  8. CONTENT_SENSITIVE: 'CONTENT_SENSITIVE',
  9. UPSTREAM_ERROR: 'UPSTREAM_ERROR',
  10. GENERATION_FAILED: 'GENERATION_FAILED',
  11. TRANSCRIPTION_FAILED: 'TRANSCRIPTION_FAILED',
  12. PARSE_FAILED: 'PARSE_FAILED',
  13. INTERNAL_ERROR: 'INTERNAL_ERROR',
  14. } as const;
  15. export type ApiErrorCode = (typeof API_ERROR_CODES)[keyof typeof API_ERROR_CODES];
  16. export interface ApiErrorBody {
  17. success: false;
  18. errorCode: ApiErrorCode;
  19. error: string;
  20. details?: string;
  21. }
  22. export function apiError(
  23. code: ApiErrorCode,
  24. status: number,
  25. error: string,
  26. details?: string,
  27. ): NextResponse<ApiErrorBody> {
  28. return NextResponse.json(
  29. {
  30. success: false as const,
  31. errorCode: code,
  32. error,
  33. ...(details ? { details } : {}),
  34. },
  35. { status },
  36. );
  37. }
  38. export function apiSuccess<T extends Record<string, unknown>>(data: T, status = 200): NextResponse {
  39. return NextResponse.json({ success: true, ...data }, { status });
  40. }