Skip to content

Commit

Permalink
feat(route): switch to ofetch for API calls (DIYgod#18012)
Browse files Browse the repository at this point in the history
* feat(route): switch to ofetch for API calls

* feat(route): change api
  • Loading branch information
Geraldxm authored Jan 1, 2025
1 parent 0ad07d2 commit 8c1f249
Showing 1 changed file with 29 additions and 26 deletions.
55 changes: 29 additions & 26 deletions lib/routes/chongdiantou/index.ts
Original file line number Diff line number Diff line change
@@ -1,30 +1,8 @@
import { Route } from '@/types';
import { namespace } from './namespace';
import { load } from 'cheerio';
import ofetch from '@/utils/ofetch';
import logger from '@/utils/logger';

async function getPosts() {
try {
// Fetch data directly from the API without caching
const response = await ofetch('https://www.chongdiantou.com/wp-json/wp/v2/posts?_embed&per_page=10', {
headers: {
method: 'GET',
},
});
return response.map((post) => ({
title: post.title.rendered,
link: post.link,
pubDate: new Date(post.date_gmt), // Use date_gmt instead of date
category: post._embedded['wp:term'][0].map((term) => term.name).join(', '),
description: post.content.rendered,
author: post._embedded.author[0].name,
image: post._embedded['wp:featuredmedia'] ? post._embedded['wp:featuredmedia'][0].source_url : '',
}));
} catch (error) {
logger.error('Error fetching posts:', error);
return [];
}
}
import cache from '@/utils/cache';

export const route: Route = {
path: '/',
Expand All @@ -42,12 +20,37 @@ export const route: Route = {
};

async function handler() {
const items = await getPosts();
const response = await ofetch('https://www.chongdiantou.com/nice-json/front-end/home-load-more');
let items = [];

items = response.data.map((item) => ({
title: item.title,
link: item.link,
image: item.cover,
pubDate: new Date(item.time),
category: item.cat.name,
}));

items = await Promise.all(
items.map(
async (item) =>
await cache.tryGet(item.link, async () => {
try {
const response = await ofetch(item.link);
const $ = load(response);
item.description = $('.post-content').html() || 'No content found';
} catch {
item.description = 'Failed to fetch content';
}
return item;
})
)
);

return {
title: '充电头网 - 最新资讯',
description: '充电头网新闻资讯',
link: 'https://www.chongdiantou.com/',
link: 'https://www.chongdiantou.com',
image: 'https://static.chongdiantou.com/wp-content/uploads/2021/02/2021021806172389.png',
item: items,
};
Expand Down

0 comments on commit 8c1f249

Please sign in to comment.