|
| 1 | +import { |
| 2 | + type DecoratorContext, |
| 3 | + type DecoratorFunction, |
| 4 | + type Namespace, |
| 5 | + type Program, |
| 6 | + validateDecoratorUniqueOnNode, |
| 7 | +} from "@typespec/compiler"; |
| 8 | + |
| 9 | +import { GraphQLKeys, NAMESPACE } from "../lib.js"; |
| 10 | +import { useStateMap } from "./state-map.js"; |
| 11 | + |
| 12 | +// This will set the namespace for decorators implemented in this file |
| 13 | +export const namespace = NAMESPACE; |
| 14 | + |
| 15 | +export interface SchemaDetails { |
| 16 | + name?: string; |
| 17 | +} |
| 18 | + |
| 19 | +export interface Schema extends SchemaDetails { |
| 20 | + type: Namespace; |
| 21 | +} |
| 22 | + |
| 23 | +const [getSchema, setSchema, getSchemaMap] = useStateMap<Namespace, Schema>(GraphQLKeys.schema); |
| 24 | + |
| 25 | +/** |
| 26 | + * List all the schemas defined in the TypeSpec program |
| 27 | + * @param program Program |
| 28 | + * @returns List of schemas. |
| 29 | + */ |
| 30 | +export function listSchemas(program: Program): Schema[] { |
| 31 | + return [...getSchemaMap(program).values()]; |
| 32 | +} |
| 33 | + |
| 34 | +export { |
| 35 | + /** |
| 36 | + * Get the schema information for the given namespace. |
| 37 | + * @param program Program |
| 38 | + * @param namespace Schema namespace |
| 39 | + * @returns Schema information or undefined if namespace is not a schema namespace. |
| 40 | + */ |
| 41 | + getSchema, |
| 42 | +}; |
| 43 | + |
| 44 | +/** |
| 45 | + * Check if the namespace is defined as a schema. |
| 46 | + * @param program Program |
| 47 | + * @param namespace Namespace |
| 48 | + * @returns Boolean |
| 49 | + */ |
| 50 | +export function isSchema(program: Program, namespace: Namespace): boolean { |
| 51 | + return getSchemaMap(program).has(namespace); |
| 52 | +} |
| 53 | + |
| 54 | +/** |
| 55 | + * Mark the given namespace as a schema. |
| 56 | + * @param program Program |
| 57 | + * @param namespace Namespace |
| 58 | + * @param details Schema details |
| 59 | + */ |
| 60 | +export function addSchema( |
| 61 | + program: Program, |
| 62 | + namespace: Namespace, |
| 63 | + details: SchemaDetails = {}, |
| 64 | +): void { |
| 65 | + const schemaMap = getSchemaMap(program); |
| 66 | + const existing = schemaMap.get(namespace) ?? {}; |
| 67 | + setSchema(program, namespace, { ...existing, ...details, type: namespace }); |
| 68 | +} |
| 69 | + |
| 70 | +export const $schema: DecoratorFunction = ( |
| 71 | + context: DecoratorContext, |
| 72 | + target: Namespace, |
| 73 | + options: SchemaDetails = {}, |
| 74 | +) => { |
| 75 | + validateDecoratorUniqueOnNode(context, target, $schema); |
| 76 | + addSchema(context.program, target, options); |
| 77 | +}; |
0 commit comments