feat(route): switch to ofetch for API calls (#18012)

* feat(route): switch to ofetch for API calls

* feat(route): change api
This commit is contained in:
Geraldxm 2025-01-01 14:45:00 +08:00 committed by GitHub
parent 0ad07d2d88
commit 8c1f249372
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 29 additions and 26 deletions

View File

@ -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: '/',
@ -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,
};