Repository navigation
Expand file tree
/
Copy pathgdelt-doc.js
More file actions
63 lines (54 loc) · 1.9 KB
/
Copy pathgdelt-doc.js
File metadata and controls
63 lines (54 loc) · 1.9 KB
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
export const config = { runtime: 'edge' };
const MAX_RECORDS = 20;
const DEFAULT_RECORDS = 10;
export default async function handler(req) {
const url = new URL(req.url);
const query = url.searchParams.get('query');
const maxrecords = Math.min(
parseInt(url.searchParams.get('maxrecords') || DEFAULT_RECORDS, 10),
MAX_RECORDS
);
const timespan = url.searchParams.get('timespan') || '72h';
if (!query || query.length < 2) {
return new Response(JSON.stringify({ error: 'Query parameter required' }), {
status: 400,
headers: { 'Content-Type': 'application/json' },
});
}
try {
const gdeltUrl = new URL('https://api.gdeltproject.org/api/v2/doc/doc');
gdeltUrl.searchParams.set('query', query);
gdeltUrl.searchParams.set('mode', 'artlist');
gdeltUrl.searchParams.set('maxrecords', maxrecords.toString());
gdeltUrl.searchParams.set('format', 'json');
gdeltUrl.searchParams.set('sort', 'date');
gdeltUrl.searchParams.set('timespan', timespan);
const response = await fetch(gdeltUrl.toString());
if (!response.ok) {
throw new Error(`GDELT returned ${response.status}`);
}
const data = await response.json();
const articles = (data.articles || []).map(article => ({
title: article.title,
url: article.url,
source: article.domain || article.source?.domain,
date: article.seendate,
image: article.socialimage,
language: article.language,
tone: article.tone,
}));
return new Response(JSON.stringify({ articles, query }), {
status: 200,
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*',
'Cache-Control': 'public, max-age=300',
},
});
} catch (error) {
return new Response(JSON.stringify({ error: error.message, articles: [] }), {
status: 500,
headers: { 'Content-Type': 'application/json' },
});
}
}