microsoft/typespec

Public

mirrored from https://github.com/microsoft/typespecAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
3040a83d6de0cc6876163b48ec9be61eefa3ebdd

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

packages/http/src/content-types.ts

45lines · modecode

1import { createDiagnosticCollector, Diagnostic, ModelProperty, Program } from "@typespec/compiler";
2import { getHeaderFieldName } from "./decorators.js";
3import { createDiagnostic } from "./lib.js";
4
5/**
6 * Check if the given model property is the content type header.
7 * @param program Program
8 * @param property Model property.
9 * @returns True if the model property is marked as a header and has the name `content-type`(case insensitive.)
10 */
11export function isContentTypeHeader(program: Program, property: ModelProperty): boolean {
12 const headerName = getHeaderFieldName(program, property);
13 return Boolean(headerName && headerName.toLowerCase() === "content-type");
14}
15
16/**
17 * Resolve the content types from a model property by looking at the value.
18 * @property property Model property
19 * @returns List of contnet types and any diagnostics if there was an issue.
20 */
21export function getContentTypes(property: ModelProperty): [string[], readonly Diagnostic[]] {
22 const diagnostics = createDiagnosticCollector();
23 if (property.type.kind === "String") {
24 return [[property.type.value], []];
25 } else if (property.type.kind === "Union") {
26 const contentTypes = [];
27 for (const option of property.type.variants.values()) {
28 if (option.type.kind === "String") {
29 contentTypes.push(option.type.value);
30 } else {
31 diagnostics.add(
32 createDiagnostic({
33 code: "content-type-string",
34 target: property,
35 })
36 );
37 continue;
38 }
39 }
40
41 return diagnostics.wrap(contentTypes);
42 }
43
44 return [[], [createDiagnostic({ code: "content-type-string", target: property })]];
45}
46