microsoft/typespec

Public

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

CodeCommitsIssuesPull requestsActionsInsightsSecurity
archive/docusaurus-website

Branches

Tags

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

Clone

HTTPS

Download ZIP

packages/http/src/content-types.ts

48lines · modecode

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