This is an example of how to manipulate (import and use) JSON files with Nuxt 3’s server/api. The following article was used as a reference.
https://github.com/nuxt/framework/discussions/775#discussioncomment-1470136
While there is much room for improvement in areas such as type definitions, the following approach was confirmed to work.
// async/await を使用しています。
export default defineEventHandler(async (event) => {
const items_: any = await import('~/assets/index.json')
// .defaultをつける点に注意
const items_total: any[] = items_.default
// 以下の参考リンクを参照してください。
const query = getQuery(event)
const page: number = Number(query.page) || 1;
const size: number = Number(query.size) || 20;
const items: any[] = items_total.slice((page - 1) * size, page * size);
return {
"hits": {
"total": {
"value": items_total.length,
},
"hits": items
}
}
});
With the above, by using a query like /api/items?page=2&size=40, it was possible to return a portion of the imported JSON file (~/assets/index.json). Paths other than assets seem to work as well, but this has not been thoroughly verified.
While there is much room for improvement, we hope this serves as a useful reference.
References
https://v3.nuxtjs.org/guide/directory-structure/server/#handling-requests-with-query-parameters