links
This commit is contained in:
@@ -1,9 +1,51 @@
|
||||
import { NextResponse } from 'next/server';
|
||||
import { executeQuery } from '@/lib/clickhouse';
|
||||
import { NextRequest } from 'next/server';
|
||||
|
||||
export async function GET() {
|
||||
export async function GET(request: NextRequest) {
|
||||
try {
|
||||
// Query to fetch shorturl data from ClickHouse
|
||||
// Get pagination and filter parameters from the URL
|
||||
const searchParams = request.nextUrl.searchParams;
|
||||
const page = parseInt(searchParams.get('page') || '1', 10);
|
||||
const pageSize = parseInt(searchParams.get('page_size') || '10', 10);
|
||||
const search = searchParams.get('search');
|
||||
const team = searchParams.get('team');
|
||||
|
||||
// Calculate OFFSET
|
||||
const offset = (page - 1) * pageSize;
|
||||
|
||||
// Build WHERE conditions
|
||||
const whereConditions = ['deleted_at IS NULL'];
|
||||
|
||||
if (search) {
|
||||
whereConditions.push(`(
|
||||
title ILIKE '%${search}%' OR
|
||||
slug ILIKE '%${search}%' OR
|
||||
original_url ILIKE '%${search}%'
|
||||
)`);
|
||||
}
|
||||
|
||||
if (team) {
|
||||
whereConditions.push(`hasToken(teams, 'team_id', '${team}')`);
|
||||
}
|
||||
|
||||
const whereClause = whereConditions.join(' AND ');
|
||||
|
||||
// First query to get total count
|
||||
const countQuery = `
|
||||
SELECT count(*) as total
|
||||
FROM shorturl_analytics.shorturl
|
||||
WHERE ${whereClause}
|
||||
`;
|
||||
|
||||
const countResult = await executeQuery(countQuery);
|
||||
// Handle the result safely by using an explicit type check
|
||||
const total = Array.isArray(countResult) && countResult.length > 0 && typeof countResult[0] === 'object' && countResult[0] !== null && 'total' in countResult[0]
|
||||
? Number(countResult[0].total)
|
||||
: 0;
|
||||
const totalPages = Math.ceil(total / pageSize);
|
||||
|
||||
// Main query with pagination
|
||||
const query = `
|
||||
SELECT
|
||||
id,
|
||||
@@ -31,17 +73,21 @@ export async function GET() {
|
||||
click_count,
|
||||
unique_visitors
|
||||
FROM shorturl_analytics.shorturl
|
||||
WHERE deleted_at IS NULL
|
||||
WHERE ${whereClause}
|
||||
ORDER BY created_at DESC
|
||||
LIMIT ${pageSize} OFFSET ${offset}
|
||||
`;
|
||||
|
||||
// Execute the query using the shared client
|
||||
const rows = await executeQuery(query);
|
||||
|
||||
// Return the data
|
||||
// Return the data with pagination metadata
|
||||
return NextResponse.json({
|
||||
links: rows,
|
||||
total: rows.length
|
||||
total: total,
|
||||
total_pages: totalPages,
|
||||
page: page,
|
||||
page_size: pageSize
|
||||
});
|
||||
} catch (error) {
|
||||
console.error('Error fetching shortlinks from ClickHouse:', error);
|
||||
|
||||
Reference in New Issue
Block a user