-
Notifications
You must be signed in to change notification settings - Fork 56
/
Copy pathrender.ts
57 lines (48 loc) · 1.95 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
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"
import { ContentfulRenderOptions } from "./contentful/options"
interface Options {
localization?: boolean
namespace?: string
linkType?: string
}
export default async function render(
contentTypes: ContentType[],
locales: Locale[],
{ namespace, linkType, localization = false }: Options = {},
) {
const options = { linkType, localization }
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, { linkType, localization }),
renderAllContentTypeIds(sortedContentTypes),
renderAllLocales(sortedLocales),
renderDefaultLocale(sortedLocales),
renderLocalizedTypes(localization),
].join("\n\n")
const source = [renderContentfulImports(options), renderNamespace(typingsSource, namespace)].join(
"\n\n",
)
const prettierConfig = await resolveConfig(process.cwd())
return format(source, { ...prettierConfig, parser: "typescript" })
}
function renderAllContentTypes(
contentTypes: ContentType[],
options: ContentfulRenderOptions,
): 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}'`),
)
}