forked from microsoft/typespec
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontent-types.ts
45 lines (41 loc) · 1.62 KB
/
content-types.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
import { createDiagnosticCollector, Diagnostic, ModelProperty, Program } from "@typespec/compiler";
import { getHeaderFieldName } from "./decorators.js";
import { createDiagnostic } from "./lib.js";
/**
* Check if the given model property is the content type header.
* @param program Program
* @param property Model property.
* @returns True if the model property is marked as a header and has the name `content-type`(case insensitive.)
*/
export function isContentTypeHeader(program: Program, property: ModelProperty): boolean {
const headerName = getHeaderFieldName(program, property);
return Boolean(headerName && headerName.toLowerCase() === "content-type");
}
/**
* Resolve the content types from a model property by looking at the value.
* @property property Model property
* @returns List of contnet types and any diagnostics if there was an issue.
*/
export function getContentTypes(property: ModelProperty): [string[], readonly Diagnostic[]] {
const diagnostics = createDiagnosticCollector();
if (property.type.kind === "String") {
return [[property.type.value], []];
} else if (property.type.kind === "Union") {
const contentTypes = [];
for (const option of property.type.variants.values()) {
if (option.type.kind === "String") {
contentTypes.push(option.type.value);
} else {
diagnostics.add(
createDiagnostic({
code: "content-type-string",
target: property,
})
);
continue;
}
}
return diagnostics.wrap(contentTypes);
}
return [[], [createDiagnostic({ code: "content-type-string", target: property })]];
}