-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathgetNews.ts
59 lines (49 loc) · 1.36 KB
/
getNews.ts
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
import type { Context } from 'hono';
import { env } from '../config/env.js';
const printLine = (): void => {
console.log('--------------------------------');
};
const getNews = async () => {
try {
const response = await fetch(
`https://api.currentsapi.services/v1/latest-news?language=ja&apiKey=${env.CURRENTS_API_KEY}`
);
// HTTPエラーが発生した場合
if (!response.ok) {
throw new Error(`HTTPエラー: ${response.status}`);
}
const data = await response.json();
console.log(data);
// ニュースの取得に失敗した場合
if (data.status !== 'ok') {
throw new Error('ニュースの取得に失敗しました。');
}
const newsArray = data.news;
let news;
for (let i = 0; i < newsArray.length; i++) {
const newsTemp = newsArray[i];
if (newsTemp.title !== '' && newsTemp.description !== '' && newsTemp.url !== '') {
news = newsTemp;
break;
}
}
if (!news) {
throw new Error('表示できるニュースがありません。');
}
return {
isSuccess: true,
news: {
title: news.title,
description: news.description,
url: news.url,
},
};
} catch (error: any) {
console.error(error);
return {
isSuccess: false,
message: error.message,
};
}
};
export default getNews;