← back to Norma
app/api/journalists/[id]/route.ts
137 lines
import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/db';
import { requireRole } from '@/lib/require-role';
/* ═══════════════════════════════════════════════════════════════════════════
GET /api/journalists/:id — full journalist detail with articles & orgs
Query: ?year=2024&tag=
═══════════════════════════════════════════════════════════════════════════ */
export async function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const auth = requireRole(req, 'admin', 'staff');
if (auth instanceof NextResponse) return auth;
try {
const { id } = await params;
const { searchParams } = new URL(req.url);
const year = searchParams.get('year') || '';
// Journalist info
const { rows: jRows } = await query(`SELECT * FROM journalists WHERE id = $1`, [id]);
if (!jRows.length) return NextResponse.json({ error: 'Not found' }, { status: 404 });
const journalist = jRows[0];
// Articles (optionally filtered by year)
let articleSql = `SELECT * FROM journalist_articles WHERE journalist_id = $1`;
const articleParams: (string | number)[] = [id];
if (year) {
articleSql += ` AND EXTRACT(YEAR FROM published_date) = $2`;
articleParams.push(Number(year));
}
articleSql += ` ORDER BY published_date DESC`;
const { rows: articles } = await query(articleSql, articleParams);
// Year breakdown
const { rows: yearBreakdown } = await query(
`SELECT EXTRACT(YEAR FROM published_date)::int AS year, COUNT(*)::int AS count
FROM journalist_articles WHERE journalist_id = $1
GROUP BY year ORDER BY year`,
[id]
);
// Tag breakdown
const { rows: tagBreakdown } = await query(
`SELECT UNNEST(tags) AS tag, COUNT(*)::int AS count
FROM journalist_articles WHERE journalist_id = $1
GROUP BY tag ORDER BY count DESC LIMIT 20`,
[id]
);
// Topic breakdown
const { rows: topicBreakdown } = await query(
`SELECT UNNEST(topics) AS topic, COUNT(*)::int AS count
FROM journalist_articles WHERE journalist_id = $1
GROUP BY topic ORDER BY count DESC LIMIT 20`,
[id]
);
// Organization relationships
const { rows: orgs } = await query(
`SELECT * FROM journalist_orgs WHERE journalist_id = $1 ORDER BY strength DESC`,
[id]
);
return NextResponse.json({
journalist,
articles,
yearBreakdown,
tagBreakdown,
topicBreakdown,
orgs,
articleCount: articles.length,
});
} catch (err: any) {
console.error('Journalist detail error:', err.message);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
/* ═══════════════════════════════════════════════════════════════════════════
PATCH /api/journalists/:id — update journalist
═══════════════════════════════════════════════════════════════════════════ */
export async function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const auth = requireRole(req, 'admin', 'staff');
if (auth instanceof NextResponse) return auth;
try {
const { id } = await params;
const body = await req.json();
const allowed = ['name', 'outlet', 'beat', 'bio', 'twitter_handle', 'email', 'tags', 'is_active', 'linkedin_url', 'website', 'instagram_handle', 'facebook_url', 'youtube_url', 'substack_url', 'medium_url', 'podcast_url', 'rss_feed'];
const sets: string[] = [];
const vals: any[] = [];
let idx = 1;
for (const key of allowed) {
if (body[key] !== undefined) {
sets.push(`${key} = $${idx++}`);
vals.push(body[key]);
}
}
if (!sets.length) return NextResponse.json({ error: 'No fields to update' }, { status: 400 });
sets.push(`updated_at = NOW()`);
vals.push(id);
const { rows } = await query(
`UPDATE journalists SET ${sets.join(', ')} WHERE id = $${idx} RETURNING *`,
vals
);
if (!rows.length) return NextResponse.json({ error: 'Not found' }, { status: 404 });
return NextResponse.json({ journalist: rows[0] });
} catch (err: any) {
console.error('[journalists] PATCH error:', err.message);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}
/* ═══════════════════════════════════════════════════════════════════════════
DELETE /api/journalists/:id
═══════════════════════════════════════════════════════════════════════════ */
export async function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
const auth = requireRole(req, 'admin', 'staff');
if (auth instanceof NextResponse) return auth;
try {
const { id } = await params;
const { rows } = await query(`DELETE FROM journalists WHERE id = $1 RETURNING id`, [id]);
if (!rows.length) return NextResponse.json({ error: 'Not found' }, { status: 404 });
return NextResponse.json({ deleted: true });
} catch (err: any) {
console.error('[journalists] DELETE error:', err.message);
return NextResponse.json({ error: 'Internal server error' }, { status: 500 });
}
}