The Learning Events API Route is a critical component of the Sophra system’s adaptive learning pipeline. This Next.js API route, implemented in TypeScript, serves as the interface for retrieving learning events from the system’s database. It plays a crucial role in the analytics and machine learning processes that drive Sophra’s intelligent data processing capabilities. Architecturally, this component is designed as a serverless function, leveraging Next.js 14’s API routes feature. It integrates directly with Sophra’s primary database through Prisma ORM, ensuring type-safe database operations. The route implements a robust query parameter validation system using Zod, enhancing the reliability and security of incoming requests. One of the key architectural decisions in this component is the use of raw SQL queries through Prisma’s $queryRaw method. This approach allows for more fine-grained control over the database queries, potentially improving performance for complex data retrievals. However, it also introduces the need for careful query construction to prevent SQL injection vulnerabilities. Performance optimization is a core focus of this component. It implements limit-based pagination to control the volume of data returned in a single request. Additionally, the component includes date range filtering capabilities, allowing clients to retrieve only the most relevant learning events. These features combine to reduce unnecessary data transfer and processing, enhancing the overall system efficiency. A unique technical capability of this route is its ability to handle different types of learning events. The LearningEventType enum allows for flexible categorization of events, supporting Sophra’s diverse learning and analytics needs. This extensibility is crucial for accommodating future expansions of the system’s learning capabilities.

Exported Components

export async function GET(req: NextRequest): Promise<NextResponse>
The GET function is the primary export of this route. It handles HTTP GET requests and returns learning events based on query parameters.

Parameters

  • req: NextRequest: The incoming Next.js request object.

Return Type

  • Promise<NextResponse>: A promise that resolves to a Next.js response object containing the retrieved learning events or error information.

Implementation Examples

const { searchParams } = new URL(req.url);
const validation = querySchema.safeParse(Object.fromEntries(searchParams));

if (!validation.success) {
  logger.error("Invalid query parameters", {
    errors: validation.error.format(),
  });
  return NextResponse.json(
    {
      success: false,
      error: "Invalid query parameters",
      details: validation.error.format(),
    },
    { status: 400 }
  );
}

const { limit, type, startDate, endDate } = validation.data;
This example demonstrates how the route handles and validates query parameters using Zod schema validation.
const events = await prisma.$queryRaw`
  SELECT * FROM "LearningEvent" 
  WHERE type::text = ${type || "SEARCH_PATTERN"}
  AND timestamp >= ${startDate ? new Date(startDate) : new Date(0)}
  AND timestamp <= ${endDate ? new Date(endDate) : new Date()}
  ORDER BY timestamp DESC
  LIMIT ${limit}
`;
This example shows the raw SQL query used to retrieve learning events from the database, demonstrating the component’s integration with Prisma and the database.

Sophra Integration Details

The Learning Events API Route integrates closely with several Sophra components:
  1. Database Service: Utilizes Prisma client for database operations.
  2. Logging Service: Employs the shared logger for error and info logging.
  3. Type System: Leverages shared types for learning events and enums.

Error Handling

The route implements comprehensive error handling:
  1. Database Connection Errors: Checks database connectivity and returns a 503 Service Unavailable response if the connection fails.
  2. Query Parameter Validation: Uses Zod to validate and sanitize input, returning detailed error messages for invalid parameters.
  3. General Error Handling: Catches and logs any unexpected errors, returning a graceful response to the client.
All errors are logged using the shared logger service, facilitating centralized error tracking and analysis.

Performance Considerations

  1. Pagination: Implements limit-based pagination to control result set size.
  2. Date Range Filtering: Allows clients to specify date ranges, reducing unnecessary data retrieval.
  3. Raw SQL Queries: Uses Prisma’s $queryRaw for optimized database access.
// TODO: Implement Redis caching for frequently accessed events
const cacheKey = `learning_events:${type}:${startDate}:${endDate}:${limit}`;
let cachedEvents = await redisClient.get(cacheKey);

if (cachedEvents) {
  return NextResponse.json(JSON.parse(cachedEvents));
}

// ... Fetch from database if not cached

await redisClient.set(cacheKey, JSON.stringify(events), 'EX', 300); // Cache for 5 minutes

Security Implementation

  1. Input Validation: Strict validation of query parameters using Zod schema.
  2. SQL Injection Prevention: Use of parameterized queries with Prisma’s $queryRaw.
  3. Error Message Sanitization: Careful control of error details exposed to clients.
TODO: Implement authentication middleware to ensure only authorized clients can access this route.

Configuration

The route relies on the following environment variables and configurations:
POSTGRESQL_URL="your-database-url"
LOG_LEVEL="info"
These configurations allow for flexible deployment across different environments and easy adjustment of query parameter constraints.