-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathrender.ts
More file actions
54 lines (44 loc) · 1.88 KB
/
render.ts
File metadata and controls
54 lines (44 loc) · 1.88 KB
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
import { ContentType, Locale } from "contentful"
import { format, resolveConfig } from "prettier"
import renderContentfulImports from "./contentful/renderContentfulImports"
import renderContentType from "./contentful/renderContentType"
import renderUnion from "./typescript/renderUnion"
import renderAllLocales from "./contentful/renderAllLocales"
import renderDefaultLocale from "./contentful/renderDefaultLocale"
import renderNamespace from "./contentful/renderNamespace"
import renderLocalizedTypes from "./contentful/renderLocalizedTypes"
export interface Options {
localization?: boolean
namespace?: string
prefix?: string
suffix?: string
}
export const defaultOptions: Options = {}
export default async function render(
contentTypes: ContentType[],
locales: Locale[],
options: Options,
) {
const { namespace, localization = false } = options
const sortedContentTypes = contentTypes.sort((a, b) => a.sys.id.localeCompare(b.sys.id))
const sortedLocales = locales.sort((a, b) => a.code.localeCompare(b.code))
const typingsSource = [
renderAllContentTypes(sortedContentTypes, options),
renderAllContentTypeIds(sortedContentTypes),
renderAllLocales(sortedLocales),
renderDefaultLocale(sortedLocales),
renderLocalizedTypes(localization),
].join("\n\n")
const source = [
renderContentfulImports(localization),
renderNamespace(typingsSource, namespace),
].join("\n\n")
const prettierConfig = await resolveConfig(process.cwd())
return format(source, { ...prettierConfig, parser: "typescript" })
}
function renderAllContentTypes(contentTypes: ContentType[], options: Options): string {
return contentTypes.map(contentType => renderContentType(contentType, options)).join("\n\n")
}
function renderAllContentTypeIds(contentTypes: ContentType[]): string {
return renderUnion("CONTENT_TYPE", contentTypes.map(contentType => `'${contentType.sys.id}'`))
}