2025-10-28 11:21:04 -04:00
|
|
|
import { NextRequest, NextResponse } from 'next/server';
|
|
|
|
|
import { getAutotaskClient } from '@/lib/services/autotask-factory';
|
|
|
|
|
import { apiCache } from '@/lib/services/cache';
|
|
|
|
|
|
|
|
|
|
export async function GET(
|
|
|
|
|
request: NextRequest,
|
|
|
|
|
{ params }: { params: Promise<{ id: string }> }
|
|
|
|
|
) {
|
|
|
|
|
try {
|
|
|
|
|
const { id } = await params;
|
2025-11-19 14:18:16 -05:00
|
|
|
const contactId = parseInt(id);
|
|
|
|
|
|
|
|
|
|
if (isNaN(contactId)) {
|
|
|
|
|
return NextResponse.json(
|
|
|
|
|
{ error: 'Invalid contact ID' },
|
|
|
|
|
{ status: 400 }
|
|
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const cacheKey = `contact:${contactId}`;
|
2025-10-28 11:21:04 -04:00
|
|
|
|
|
|
|
|
// Check cache first
|
|
|
|
|
const cached = apiCache.get(cacheKey);
|
|
|
|
|
if (cached) {
|
|
|
|
|
return NextResponse.json(cached);
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
const autotaskClient = getAutotaskClient();
|
|
|
|
|
|
|
|
|
|
// Query for the contact by ID
|
|
|
|
|
const contacts = await autotaskClient.queryEntity('Contacts', {
|
2025-11-19 14:18:16 -05:00
|
|
|
filter: [{ op: 'eq', field: 'id', value: contactId }],
|
2025-10-28 11:21:04 -04:00
|
|
|
});
|
|
|
|
|
|
|
|
|
|
const contact = contacts.length > 0 ? contacts[0] : null;
|
|
|
|
|
|
2025-11-19 14:18:16 -05:00
|
|
|
// Cache for 10 minutes (even if null to avoid repeated failed lookups)
|
|
|
|
|
apiCache.set(cacheKey, { contact }, 10 * 60);
|
2025-10-28 11:21:04 -04:00
|
|
|
|
|
|
|
|
return NextResponse.json({ contact });
|
|
|
|
|
} catch (error) {
|
2025-11-19 14:18:16 -05:00
|
|
|
const { id } = await params;
|
|
|
|
|
console.error(`Error fetching contact ${id}:`, error);
|
|
|
|
|
const errorMessage = error instanceof Error && error.message
|
|
|
|
|
? error.message
|
|
|
|
|
: 'Failed to fetch contact from Autotask';
|
|
|
|
|
|
|
|
|
|
// Return 200 with null contact instead of 500 to prevent UI errors
|
|
|
|
|
// The contact might not exist or might not be accessible
|
2025-10-28 11:21:04 -04:00
|
|
|
return NextResponse.json(
|
2025-11-19 14:18:16 -05:00
|
|
|
{ contact: null, error: errorMessage }
|
2025-10-28 11:21:04 -04:00
|
|
|
);
|
|
|
|
|
}
|
|
|
|
|
}
|