-
Notifications
You must be signed in to change notification settings - Fork 51
/
render.ts
67 lines (56 loc) · 2.29 KB
/
render.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
67
import { ContentType, Locale } from "contentful"
import { format, resolveConfig } from "prettier"
import renderAllLocales from "./contentful/renderAllLocales"
import renderContentfulImports from "./contentful/renderContentfulImports"
import renderContentType from "./contentful/renderContentType"
import renderContentTypeId from "./contentful/renderContentTypeId"
import renderDefaultLocale from "./contentful/renderDefaultLocale"
import renderLocalizedTypes from "./contentful/renderLocalizedTypes"
import renderNamespace from "./contentful/renderNamespace"
import renderUnion from "./typescript/renderUnion"
interface Options {
localization?: boolean
namespace?: string
}
export default async function render(
contentTypes: ContentType[],
locales: Locale[],
{ 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, localization),
renderAllContentTypeIds(sortedContentTypes),
renderEntryType(sortedContentTypes),
renderAllLocales(sortedLocales),
renderDefaultLocale(sortedLocales),
renderLocalizedTypes(localization),
].join("\n\n")
const source = [
renderContentfulImports(localization, hasRichText(contentTypes)),
renderNamespace(typingsSource, namespace),
].join("\n\n")
const prettierConfig = await resolveConfig(process.cwd())
return format(source, { ...prettierConfig, parser: "typescript" })
}
function renderAllContentTypes(contentTypes: ContentType[], localization: boolean): string {
return contentTypes.map(contentType => renderContentType(contentType, localization)).join("\n\n")
}
function renderAllContentTypeIds(contentTypes: ContentType[]): string {
return renderUnion(
"CONTENT_TYPE",
contentTypes.map(contentType => `'${contentType.sys.id}'`),
)
}
function renderEntryType(contentTypes: ContentType[]) {
return renderUnion(
"IEntry",
contentTypes.map(contentType => renderContentTypeId(contentType.sys.id)),
)
}
function hasRichText(contentTypes: ContentType[]): boolean {
return contentTypes.some(sortedContentType =>
sortedContentType.fields.some(f => !f.omitted && f.type === "RichText"),
)
}