/
utils.ts
43 lines (38 loc) · 1017 Bytes
/
utils.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
import path from 'node:path'
import { LOCALE_REGEX } from './constants'
import { Meta } from './types'
export function parseFileName(filePath: string): {
name: string
locale: string
ext: string
} {
// Get file name and extension from file path
const { name, ext } = path.parse(filePath)
const locale = name.match(LOCALE_REGEX)?.[1] || ''
return {
name: locale ? name.replace(LOCALE_REGEX, '') : name,
locale,
ext
}
}
export const parseJsonFile = (
content: string,
path: string
): Record<string, any> => {
try {
return JSON.parse(content)
} catch (err) {
console.error(
`[nextra] Error parsing ${path}, make sure it's a valid JSON`,
err
)
return {}
}
}
type Truthy<T> = T extends false | '' | 0 | null | undefined ? never : T // from lodash
export function truthy<T>(value: T): value is Truthy<T> {
return !!value
}
export function normalizeMeta(meta: Meta): Exclude<Meta, string> {
return typeof meta === 'string' ? { title: meta } : meta
}