All files / adapters/nextjs index.ts

87.12% Statements 115/132
67.7% Branches 65/96
100% Functions 16/16
87.12% Lines 115/132

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 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574                                                                                                                                                                                                                                                                          43x     43x         43x             43x 43x     43x             17x 17x     17x 17x 15x 2x 1x 1x   1x 1x 1x           17x 17x       17x 15x       17x 15x     17x             4x 3x 3x                         16x     16x   16x 11x     11x 7x 7x 4x 3x 3x 1x         2x 2x   1x           1x           8x   7x 7x 1x           6x 6x   6x         1x     1x                                 5x     5x   5x 2x         2x 2x   2x                                                 7x     7x   7x 4x     4x 2x 2x 2x 1x 1x           1x 1x               1x           3x     3x 3x 1x             2x 4x             2x     2x 2x   2x                                                 7x     7x   7x 4x     4x 2x 2x 2x 2x 2x 1x         1x 1x                             3x     3x   2x         1x     1x                                   8x     8x   8x 5x 5x 1x           4x 4x   4x 1x           3x 1x             2x     2x   2x                                                                                 2x                                
/**
 * Next.js App Router adapter for Drizzle Cube
 * Provides Cube.js-compatible API endpoints as Next.js route handlers
 */
 
import { NextRequest, NextResponse } from 'next/server'
import type { 
  SemanticQuery, 
  SecurityContext, 
  DatabaseExecutor,
  DrizzleDatabase,
  Cube
} from '../../server'
import { SemanticLayerCompiler } from '../../server'
import type { PostgresJsDatabase } from 'drizzle-orm/postgres-js'
import type { MySql2Database } from 'drizzle-orm/mysql2'
import type { BetterSQLite3Database } from 'drizzle-orm/better-sqlite3'
import {
  handleDryRun,
  formatCubeResponse,
  formatSqlResponse,
  formatMetaResponse,
  formatErrorResponse,
  handleBatchRequest
} from '../utils'
 
export interface NextCorsOptions {
  /**
   * Allowed origins for CORS
   */
  origin?: string | string[] | ((origin: string) => boolean)
  
  /**
   * Allowed HTTP methods
   */
  methods?: string[]
  
  /**
   * Allowed headers
   */
  allowedHeaders?: string[]
  
  /**
   * Allow credentials
   */
  credentials?: boolean
}
 
export interface NextAdapterOptions {
  /**
   * Array of cube definitions to register
   */
  cubes: Cube[]
  
  /**
   * Drizzle database instance (REQUIRED)
   * This is the core of drizzle-cube - Drizzle ORM integration
   * Accepts PostgreSQL, MySQL, or SQLite database instances
   */
  drizzle: PostgresJsDatabase<any> | MySql2Database<any> | BetterSQLite3Database<any> | DrizzleDatabase
  
  /**
   * Database schema for type inference (RECOMMENDED)
   * Provides full type safety for cube definitions
   */
  schema?: any
  
  /**
   * Extract security context from incoming HTTP request.
   * Called for EVERY API request to determine user permissions and multi-tenant isolation.
   * 
   * This is your security boundary - ensure proper authentication and authorization here.
   * 
   * @param request - Next.js Request object containing the incoming HTTP request
   * @param context - Route context with params (optional)
   * @returns Security context with organisationId, userId, roles, etc.
   * 
   * @example
   * extractSecurityContext: async (request, context) => {
   *   // Extract JWT from Authorization header
   *   const token = request.headers.get('Authorization')?.replace('Bearer ', '')
   *   const decoded = await verifyJWT(token)
   *   
   *   // Return context that will be available in all cube SQL functions
   *   return {
   *     organisationId: decoded.orgId,
   *     userId: decoded.userId,
   *     roles: decoded.roles
   *   }
   * }
   */
  extractSecurityContext: (request: NextRequest, context?: RouteContext) => SecurityContext | Promise<SecurityContext>
  
  /**
   * Database engine type (optional - auto-detected if not provided)
   */
  engineType?: 'postgres' | 'mysql' | 'sqlite'
  
  /**
   * CORS configuration (optional)
   */
  cors?: NextCorsOptions
  
  /**
   * Runtime environment (default: 'nodejs')
   * 'edge' for Edge Runtime, 'nodejs' for Node.js Runtime
   */
  runtime?: 'edge' | 'nodejs'
}
 
export interface RouteContext {
  params?: Record<string, string | string[]>
}
 
export type RouteHandler = (
  request: NextRequest,
  context?: RouteContext
) => Promise<Response>
 
export interface CubeHandlers {
  load: RouteHandler
  meta: RouteHandler
  sql: RouteHandler
  dryRun: RouteHandler
  batch: RouteHandler
}
 
/**
 * Helper function to create and configure semantic layer from options
 */
function createSemanticLayer(
  options: NextAdapterOptions
): SemanticLayerCompiler {
  const { cubes, drizzle, schema, engineType } = options
 
  // Validate required options
  Iif (!cubes || cubes.length === 0) {
    throw new Error('At least one cube must be provided in the cubes array')
  }
 
  // Create semantic layer and register all cubes
  const semanticLayer = new SemanticLayerCompiler({
    drizzle,
    schema,
    engineType
  })
 
  // Register all provided cubes
  cubes.forEach(cube => {
    semanticLayer.registerCube(cube)
  })
 
  return semanticLayer
}
 
/**
 * Generate CORS headers for Next.js responses
 */
function getCorsHeaders(request: NextRequest, corsOptions: NextCorsOptions): HeadersInit {
  const origin = request.headers.get('origin')
  const headers: HeadersInit = {}
 
  // Handle origin
  Eif (corsOptions.origin) {
    if (typeof corsOptions.origin === 'string') {
      headers['Access-Control-Allow-Origin'] = corsOptions.origin
    } else if (Array.isArray(corsOptions.origin)) {
      Eif (origin && corsOptions.origin.includes(origin)) {
        headers['Access-Control-Allow-Origin'] = origin
      }
    E} else if (typeof corsOptions.origin === 'function') {
      Eif (origin && corsOptions.origin(origin)) {
        headers['Access-Control-Allow-Origin'] = origin
      }
    }
  }
 
  // Handle methods
  Eif (corsOptions.methods) {
    headers['Access-Control-Allow-Methods'] = corsOptions.methods.join(', ')
  }
 
  // Handle headers
  if (corsOptions.allowedHeaders) {
    headers['Access-Control-Allow-Headers'] = corsOptions.allowedHeaders.join(', ')
  }
 
  // Handle credentials
  if (corsOptions.credentials) {
    headers['Access-Control-Allow-Credentials'] = 'true'
  }
 
  return headers
}
 
/**
 * Create OPTIONS handler for CORS preflight requests
 */
export function createOptionsHandler(corsOptions: NextCorsOptions): RouteHandler {
  return async function optionsHandler(request: NextRequest) {
    const corsHeaders = getCorsHeaders(request, corsOptions)
    return new Response(null, {
      status: 200,
      headers: corsHeaders
    })
  }
}
 
/**
 * Create load handler - Execute queries
 */
export function createLoadHandler(
  options: NextAdapterOptions
): RouteHandler {
  const { extractSecurityContext, cors } = options
 
  // Create semantic layer with all cubes registered
  const semanticLayer = createSemanticLayer(options)
 
  return async function loadHandler(request: NextRequest, context?: RouteContext) {
    try {
      let query: SemanticQuery
 
      if (request.method === 'POST') {
        const body = await request.json()
        query = (body as any).query || body // Handle nested format
      } else if (request.method === 'GET') {
        const queryParam = request.nextUrl.searchParams.get('query')
        if (!queryParam) {
          return NextResponse.json(
            formatErrorResponse('Query parameter is required', 400),
            { status: 400 }
          )
        }
        try {
          query = JSON.parse(queryParam)
        } catch (parseError) {
          return NextResponse.json(
            formatErrorResponse('Invalid JSON in query parameter', 400),
            { status: 400 }
          )
        }
      } else {
        return NextResponse.json(
          formatErrorResponse('Method not allowed', 405),
          { status: 405 }
        )
      }
 
      const securityContext = await extractSecurityContext(request, context)
      
      const validation = semanticLayer.validateQuery(query)
      if (!validation.isValid) {
        return NextResponse.json(
          formatErrorResponse(`Query validation failed: ${validation.errors.join(', ')}`, 400),
          { status: 400 }
        )
      }
 
      const result = await semanticLayer.executeMultiCubeQuery(query, securityContext)
      const response = formatCubeResponse(query, result, semanticLayer)
      
      return NextResponse.json(response, {
        headers: cors ? getCorsHeaders(request, cors) : {}
      })
      
    } catch (error) {
      Iif (process.env.NODE_ENV !== 'test') {
        console.error('Next.js load handler error:', error)
      }
      return NextResponse.json(
        formatErrorResponse(
          error instanceof Error ? error.message : 'Query execution failed',
          500
        ),
        { status: 500 }
      )
    }
  }
}
 
/**
 * Create meta handler - Get cube metadata
 */
export function createMetaHandler(
  options: NextAdapterOptions
): RouteHandler {
  const { cors } = options
 
  // Create semantic layer with all cubes registered
  const semanticLayer = createSemanticLayer(options)
 
  return async function metaHandler(request: NextRequest, _context?: RouteContext) {
    try {
      // Extract security context (some apps may want to filter cubes by context)
      // const securityContext = await getSecurityContext(request, context) // Available if needed for filtering
      
      // Get cached metadata (fast path)
      const metadata = semanticLayer.getMetadata()
      const response = formatMetaResponse(metadata)
      
      return NextResponse.json(response, {
        headers: cors ? getCorsHeaders(request, cors) : {}
      })
      
    } catch (error) {
      if (process.env.NODE_ENV !== 'test') {
        console.error('Next.js meta handler error:', error)
      }
      return NextResponse.json(
        formatErrorResponse(
          error instanceof Error ? error.message : 'Failed to fetch metadata',
          500
        ),
        { status: 500 }
      )
    }
  }
}
 
/**
 * Create SQL handler - Generate SQL without execution
 */
export function createSqlHandler(
  options: NextAdapterOptions
): RouteHandler {
  const { extractSecurityContext, cors } = options
 
  // Create semantic layer with all cubes registered
  const semanticLayer = createSemanticLayer(options)
 
  return async function sqlHandler(request: NextRequest, context?: RouteContext) {
    try {
      let query: SemanticQuery
 
      if (request.method === 'POST') {
        const body = await request.json()
        query = (body as any).query || body // Handle nested format
      } else if (request.method === 'GET') {
        const queryParam = request.nextUrl.searchParams.get('query')
        Iif (!queryParam) {
          return NextResponse.json(
            formatErrorResponse('Query parameter is required', 400),
            { status: 400 }
          )
        }
        try {
          query = JSON.parse(queryParam)
        } catch (parseError) {
          return NextResponse.json(
            formatErrorResponse('Invalid JSON in query parameter', 400),
            { status: 400 }
          )
        }
      } else {
        return NextResponse.json(
          formatErrorResponse('Method not allowed', 405),
          { status: 405 }
        )
      }
      
      const securityContext = await extractSecurityContext(request, context)
      
      // Validate query structure and field existence
      const validation = semanticLayer.validateQuery(query)
      if (!validation.isValid) {
        return NextResponse.json(
          formatErrorResponse(`Query validation failed: ${validation.errors.join(', ')}`, 400),
          { status: 400 }
        )
      }
 
      // For SQL generation, we need at least one cube referenced
      const firstMember = query.measures?.[0] || query.dimensions?.[0]
      Iif (!firstMember) {
        return NextResponse.json(
          formatErrorResponse('No measures or dimensions specified', 400),
          { status: 400 }
        )
      }
 
      const cubeName = firstMember.split('.')[0]
      
      // Generate SQL using the semantic layer compiler
      const sqlResult = await semanticLayer.generateSQL(cubeName, query, securityContext)
      const response = formatSqlResponse(query, sqlResult)
      
      return NextResponse.json(response, {
        headers: cors ? getCorsHeaders(request, cors) : {}
      })
      
    } catch (error) {
      if (process.env.NODE_ENV !== 'test') {
        console.error('Next.js SQL handler error:', error)
      }
      return NextResponse.json(
        formatErrorResponse(
          error instanceof Error ? error.message : 'SQL generation failed',
          500
        ),
        { status: 500 }
      )
    }
  }
}
 
/**
 * Create dry-run handler - Validate queries without execution
 */
export function createDryRunHandler(
  options: NextAdapterOptions
): RouteHandler {
  const { extractSecurityContext, cors } = options
 
  // Create semantic layer with all cubes registered
  const semanticLayer = createSemanticLayer(options)
 
  return async function dryRunHandler(request: NextRequest, context?: RouteContext) {
    try {
      let query: SemanticQuery
 
      if (request.method === 'POST') {
        const body = await request.json()
        query = (body as any).query || body // Handle nested format
      } else if (request.method === 'GET') {
        const queryParam = request.nextUrl.searchParams.get('query')
        if (!queryParam) {
          return NextResponse.json(
            { error: 'Query parameter is required', valid: false },
            { status: 400 }
          )
        }
        try {
          query = JSON.parse(queryParam)
        } catch (parseError) {
          return NextResponse.json(
            { error: 'Invalid JSON in query parameter', valid: false },
            { status: 400 }
          )
        }
      } else E{
        return NextResponse.json(
          { error: 'Method not allowed', valid: false },
          { status: 405 }
        )
      }
      
      // Extract security context using user-provided function
      const securityContext = await extractSecurityContext(request, context)
      
      // Perform dry-run analysis
      const result = await handleDryRun(query, securityContext, semanticLayer)
      
      return NextResponse.json(result, {
        headers: cors ? getCorsHeaders(request, cors) : {}
      })
      
    } catch (error) {
      Iif (process.env.NODE_ENV !== 'test') {
        console.error('Next.js dry-run handler error:', error)
      }
      return NextResponse.json(
        {
          error: error instanceof Error ? error.message : 'Dry-run validation failed',
          valid: false
        },
        { status: 400 }
      )
    }
  }
}
 
/**
 * Create batch handler - Execute multiple queries in a single request
 * Optimizes network overhead for dashboards with many portlets
 */
export function createBatchHandler(
  options: NextAdapterOptions
): RouteHandler {
  const { extractSecurityContext, cors } = options
 
  // Create semantic layer with all cubes registered
  const semanticLayer = createSemanticLayer(options)
 
  return async function batchHandler(request: NextRequest, context?: RouteContext) {
    try {
      if (request.method !== 'POST') {
        return NextResponse.json(
          formatErrorResponse('Method not allowed - use POST', 405),
          { status: 405 }
        )
      }
 
      const body = await request.json()
      const { queries } = body as { queries: SemanticQuery[] }
 
      if (!queries || !Array.isArray(queries)) {
        return NextResponse.json(
          formatErrorResponse('Request body must contain a "queries" array', 400),
          { status: 400 }
        )
      }
 
      if (queries.length === 0) {
        return NextResponse.json(
          formatErrorResponse('Queries array cannot be empty', 400),
          { status: 400 }
        )
      }
 
      // Extract security context ONCE (shared across all queries)
      const securityContext = await extractSecurityContext(request, context)
 
      // Use shared batch handler (wraps existing single query logic)
      const batchResult = await handleBatchRequest(queries, securityContext, semanticLayer)
 
      return NextResponse.json(batchResult, {
        headers: cors ? getCorsHeaders(request, cors) : {}
      })
 
    } catch (error) {
      if (process.env.NODE_ENV !== 'test') {
        console.error('Next.js batch handler error:', error)
      }
      return NextResponse.json(
        formatErrorResponse(
          error instanceof Error ? error.message : 'Batch execution failed',
          500
        ),
        { status: 500 }
      )
    }
  }
}
 
/**
 * Convenience function to create all route handlers
 *
 * @example
 * const handlers = createCubeHandlers({
 *   cubes: [salesCube, employeesCube],
 *   drizzle: db,
 *   schema,
 *   extractSecurityContext: async (request, context) => {
 *     const token = request.headers.get('Authorization')?.replace('Bearer ', '')
 *     const decoded = await verifyJWT(token)
 *     return { organisationId: decoded.orgId, userId: decoded.userId }
 *   }
 * })
 *
 * // Use in your API routes:
 * export const GET = handlers.load
 * export const POST = handlers.load
 */
export function createCubeHandlers(
  options: NextAdapterOptions
): CubeHandlers {
  return {
    load: createLoadHandler(options),
    meta: createMetaHandler(options),
    sql: createSqlHandler(options),
    dryRun: createDryRunHandler(options),
    batch: createBatchHandler(options)
  }
}
 
// Re-export types for convenience
export type { 
  SecurityContext, 
  DatabaseExecutor, 
  SemanticQuery, 
  DrizzleDatabase,
  NextCorsOptions as CorsOptions
}