← back to Norma
app/api/news/outlets/route.ts
37 lines
import { NextRequest, NextResponse } from 'next/server';
import { query } from '@/lib/db';
import { requireRole } from '@/lib/require-role';
import { getOrgId } from '@/lib/orgId';
/**
* GET /api/news/outlets
* Returns distinct outlets with article counts, sorted alphabetically.
* Used by the NewsTab author/outlet filter dropdown.
*
* Response: { outlets: [{ outlet: string, count: number }] }
*/
export async function GET(request: NextRequest) {
const auth = requireRole(request, 'admin', 'staff');
if (auth instanceof NextResponse) return auth;
const orgId = auth.role === 'admin' ? getOrgId(request) : auth.orgId;
try {
const orgFilter = orgId ? ' AND org_id = $1' : '';
const orgParams = orgId ? [orgId] : [];
const result = await query(
`SELECT outlet, COUNT(*)::int AS count
FROM news_items
WHERE outlet IS NOT NULL AND outlet <> ''${orgFilter}
GROUP BY outlet
ORDER BY outlet ASC`,
orgParams
);
return NextResponse.json({ outlets: result.rows });
} catch (err) {
console.error('[api/news/outlets] GET error:', (err as Error).message);
return NextResponse.json({ error: 'Failed to fetch outlets' }, { status: 500 });
}
}