Query layer provides server API and composables to search and query contents.
Query server exposes one API:
/api/_content/queryPOST request. GET requests can be made but are limited to simple values (first, skip and limit).$fetch('/api/_content/query', {
method: 'POST',
body: {
first: false, // set to true for returning only one document
skip: 0,
limit: 0,
sort: [],
where: [],
only:[],
without:[]
},
})
// returns an array
// [{ path: 'posts/hello-world' }, ...]
@nuxt/content provide composables to work with content server:
queryContent(...pathParts)const post = await queryContent('posts')
.where({ category: { $in: ['nature', 'people'] } })
.limit(10)
.find()
const doc = await queryContent('/').findOne()
The layer can be extend using custom plugins.
With plugins users can extend query behaviors and add new features to it.
// file `~/plugin-version.ts`
import { defineQueryPlugin } from '#imports'
export default defineQueryPlugin({
name: 'version',
queries: {
version: params => {
return v => {
params.version = v
}
}
},
execute: (data, params) => {
if (params.version) {
return data.filter(v => v.version === params.version)
}
}
})
// file `nuxt.config.ts`
import { defineNuxtConfig } from 'nuxt3'
import { resolveModule } from '@nuxt/kit'
export default defineNuxtConfig({
content: {
query: {
plugins: [resolveModule('./plugin-version', { paths: __dirname })]
}
}
})
const contents = await queryContent()
.where({ category: { $in: ['nature', 'people'] } })
.version('3.x')
.limit(10)
.find()
[
{
"title": "Post 1",
"path": "/real-content/post",
"stem": "1.real-content/post",
"description": "This is the first post written by Alice and Bob used to try $contains filter."
},
{
"title": "Playground s",
"path": "/playground",
"stem": "98.playground",
"description": ""
}
]