microsoft/typespec
Publicmirrored from https://github.com/microsoft/typespecAvailable
packages/http/src/content-types.ts
45lines · modecode
| 1 | import { createDiagnosticCollector, Diagnostic, ModelProperty, Program } from "@typespec/compiler"; |
| 2 | import { getHeaderFieldName } from "./decorators.js"; |
| 3 | import { 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 | */ |
| 11 | export 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 | */ |
| 21 | export 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 | |