-
-
Notifications
You must be signed in to change notification settings - Fork 676
/
Copy pathnavigation.ts
66 lines (56 loc) · 2.46 KB
/
navigation.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
import { hash } from 'ohash'
import { useRuntimeConfig } from '#app'
import type { NavItem, QueryBuilder, QueryBuilderParams } from '../types'
import { encodeQueryParams } from '../utils/query'
import { jsonStringify } from '../utils/json'
import { addPrerenderPath, shouldUseClientDB, withContentBase } from './utils'
import { queryContent } from './query'
import { useContentPreview } from './preview'
export const fetchContentNavigation = async (queryBuilder?: QueryBuilder | QueryBuilderParams): Promise<Array<NavItem>> => {
const { content } = useRuntimeConfig().public
// Ensure that queryBuilder is an instance of QueryBuilder
if (typeof queryBuilder?.params !== 'function') {
queryBuilder = queryContent(queryBuilder as QueryBuilderParams)
}
// Get query params from queryBuilder instance to ensure default values are applied
const params: QueryBuilderParams = queryBuilder.params()
const apiPath = content.experimental.stripQueryParameters
? withContentBase(`/navigation/${process.dev ? '_' : `${hash(params)}.${content.integrity}`}/${encodeQueryParams(params)}.json`)
: withContentBase(process.dev ? `/navigation/${hash(params)}` : `/navigation/${hash(params)}.${content.integrity}.json`)
// Add `prefetch` to `<head>` in production
if (!process.dev && process.server) {
addPrerenderPath(apiPath)
}
if (shouldUseClientDB()) {
const generateNavigation = await import('./client-db').then(m => m.generateNavigation)
return generateNavigation(params)
}
let data = await $fetch(apiPath as any, {
method: 'GET',
responseType: 'json',
params: content.experimental.stripQueryParameters
? undefined
: {
_params: jsonStringify(params),
previewToken: useContentPreview().getPreviewToken()
}
})
// On SSG, all url are redirected to `404.html` when not found, so we need to check the content type
// to know if the response is a valid JSON or not
if (typeof data === 'string' && (data as string).startsWith('<!DOCTYPE html>')) {
throw new Error('Not found')
}
const { defaultLocale } = content
const queryLocale = params.where?.find(w => w._locale)?._locale
if (defaultLocale && defaultLocale !== queryLocale) {
const addLocalePrefix = (item) => {
item._path = `/${queryLocale}${item._path}`
if (item.children?.length > 0) {
item.children = item.children.map(addLocalePrefix)
}
return item
}
data = data.map(addLocalePrefix)
}
return data
}