Lzh on GitHub

自定义数据源

定义一个自定义数据源来检索数据。

默认情况下,Nuxt Content 提供了一些内置的源,例如本地文件源和远程 Github 源。然而,这在某些情况下是不够的,例如,你想要从远程 API 获取数据。在这种情况下,你可以定义一个自定义源来获取数据,并在你的集合中使用它。

使用 defineCollectionSource,你可以定义一个自定义源。

import { defineCollectionSource } from '@nuxt/content'

const hackernewsSource = defineCollectionSource({
  getKeys: () => {
    return fetch('https://hacker-news.firebaseio.com/v0/topstories.json')
      .then(res => res.json())
      .then(data => data.map((key: string) => `${key}.json`))
  },
  getItem: (key: string) => {
    const id = key.split('.')[0]
    return fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`)
      .then(res => res.json())
  },
})

然后你可以在你的集合中使用这个源。

content.config.ts
import { defineContentConfig, defineCollectionSource, defineCollection, z } from '@nuxt/content'

const hackernewsSource = defineCollectionSource({
  getKeys: () => {
    return fetch('https://hacker-news.firebaseio.com/v0/topstories.json')
      .then(res => res.json())
      .then(data => data.map((key: string) => `${key}.json`))
  },
  getItem: (key: string) => {
    const id = key.split('.')[0]
    return fetch(`https://hacker-news.firebaseio.com/v0/item/${id}.json`)
      .then(res => res.json())
  },
})

const hackernews = defineCollection({
  type: 'data',
  source: hackernewsSource,
  schema: z.object({
    title: z.string(),
    date: z.date(),
    type: z.string(),
    score: z.number(),
    url: z.string(),
    by: z.string(),
  }),
})

export default defineContentConfig({
  collections: {
    hackernews,
  },
})