newsnow/server/utils/source.ts

49 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-10-21 17:00:51 +08:00
import type { AllSourceID } from "@shared/types"
2024-10-20 20:28:49 +08:00
import defu from "defu"
2024-10-21 17:00:51 +08:00
import type { RSSHubOption, RSSHubInfo as RSSHubResponse, SourceGetter, SourceOption } from "#/types"
2024-10-04 15:36:03 +08:00
2024-10-21 01:38:58 +08:00
type X = SourceGetter | Partial<Record<AllSourceID, SourceGetter>>
2024-10-20 20:28:49 +08:00
export function defineSource<T extends X>(source: T): T {
2024-10-05 17:20:49 +08:00
return source
2024-10-04 15:36:03 +08:00
}
2024-10-20 20:28:49 +08:00
export function defineRSSSource(url: string, option?: SourceOption): SourceGetter {
2024-10-04 15:36:03 +08:00
return async () => {
2024-10-05 01:22:41 +08:00
const data = await rss2json(url)
if (!data?.items.length) throw new Error("Cannot fetch data")
2024-10-20 20:28:49 +08:00
return data.items.map(item => ({
2024-10-05 17:20:49 +08:00
title: item.title,
url: item.link,
id: item.link,
extra: {
2024-10-06 00:31:43 +08:00
date: !option?.hiddenDate && item.created,
2024-10-05 17:20:49 +08:00
},
}))
2024-10-04 15:36:03 +08:00
}
}
2024-10-05 01:22:41 +08:00
2024-10-20 20:28:49 +08:00
export function defineRSSHubSource(route: string, RSSHubOptions?: RSSHubOption, sourceOption?: SourceOption): SourceGetter {
2024-10-05 01:22:41 +08:00
return async () => {
2024-10-06 00:31:43 +08:00
// "https://rsshub.pseudoyu.com"
const RSSHubBase = "https://rsshub.rssforever.com"
2024-10-05 01:22:41 +08:00
const url = new URL(route, RSSHubBase)
url.searchParams.set("format", "json")
2024-10-20 20:28:49 +08:00
RSSHubOptions = defu<RSSHubOption, RSSHubOption[]>(RSSHubOptions, {
2024-10-05 01:22:41 +08:00
sorted: true,
2024-10-20 20:28:49 +08:00
})
Object.entries(RSSHubOptions).forEach(([key, value]) => {
2024-10-05 01:22:41 +08:00
url.searchParams.set(key, value.toString())
})
2024-10-20 20:28:49 +08:00
const data: RSSHubResponse = await $fetch(url)
return data.items.map(item => ({
2024-10-05 17:20:49 +08:00
title: item.title,
url: item.url,
id: item.id ?? item.url,
extra: {
2024-10-06 00:31:43 +08:00
date: !sourceOption?.hiddenDate && item.date_published,
2024-10-05 17:20:49 +08:00
},
}))
2024-10-05 01:22:41 +08:00
}
}