Advanced
Custom Source
Define a custom source to retrive data.
By default, Nuxt Content provides some built-in sources like local files source and remote Github source. However this is not enough for some cases, for example, you want to fetch data from a remote API. In this case, you can define a custom source to fetch data and use it in your collections.
Using defineCollectionSource
, you can define a custom source.
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())
},
})
Then you can use this source in your collections.
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,
},
})