Skip to content

Commit eacd302

Browse files
committed
feat(plugin): add custom fetch for client
exposed client now fetch data to server useAsyncData for data caching
1 parent 5c6eecb commit eacd302

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

src/runtime/plugins/client.ts

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,37 @@
11
import { Client } from '@notionhq/client'
2-
import { defineNuxtPlugin, useRuntimeConfig } from '#app'
2+
import type { Ref } from 'vue'
3+
import { defineNuxtPlugin, useAsyncData, useRuntimeConfig } from '#app'
34

45
export default defineNuxtPlugin({
56
name: 'nuxt-notion-cms',
67
enforce: 'pre',
78
async setup() {
8-
const config = useRuntimeConfig().public.notion
9+
const config = useRuntimeConfig().notion
10+
11+
const notionFetch = $fetch.create({
12+
baseURL: config.apiBase,
13+
})
914

1015
const client = new Client({
1116
...config,
1217
auth: 'custom-auth-token',
18+
fetch: async (url, params) => {
19+
const urlSlug = url.replace('https://api.notion.com/v1', '')
20+
21+
const res = await useAsyncData(urlSlug, () => notionFetch(urlSlug), {
22+
server: true,
23+
getCachedData(key, nuxtApp) {
24+
const data: Ref<unknown> = nuxtApp.payload.data[key] || nuxtApp.static.data[key]
25+
return data
26+
},
27+
})
28+
29+
const data = res.data.value as unknown
30+
31+
const response = new Response(JSON.stringify(data), params)
32+
33+
return response
34+
},
1335
})
1436

1537
return {

0 commit comments

Comments
 (0)