-
Notifications
You must be signed in to change notification settings - Fork 55
Expand file tree
/
Copy pathrender.ts
More file actions
61 lines (52 loc) · 2.02 KB
/
render.ts
File metadata and controls
61 lines (52 loc) · 2.02 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
55
56
57
58
59
60
61
import { ContentType, Locale } from "contentful"
import { format, resolveConfig } from "prettier"
import renderImports from "./renderImports"
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 { OverridenContentTypes } from "../lib/fieldOverrides"
interface Options {
localization?: boolean
namespace?: string
fieldOverrides?: OverridenContentTypes
extraImports?: string[]
}
export default async function render(
contentTypes: ContentType[],
locales: Locale[],
{ namespace, localization = false, fieldOverrides, extraImports }: 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, fieldOverrides),
renderAllContentTypeIds(sortedContentTypes),
renderAllLocales(sortedLocales),
renderDefaultLocale(sortedLocales),
renderLocalizedTypes(localization),
].join("\n\n")
const source = [
renderImports(localization, extraImports),
renderNamespace(typingsSource, namespace),
].join("\n\n")
const prettierConfig = await resolveConfig(process.cwd())
return format(source, { ...prettierConfig, parser: "typescript" })
}
function renderAllContentTypes(
contentTypes: ContentType[],
localization: boolean,
fieldOverrides?: OverridenContentTypes,
): string {
return contentTypes
.map(contentType => renderContentType(contentType, localization, fieldOverrides))
.join("\n\n")
}
function renderAllContentTypeIds(contentTypes: ContentType[]): string {
return renderUnion(
"CONTENT_TYPE",
contentTypes.map(contentType => `'${contentType.sys.id}'`),
)
}