|
| 1 | +import type { Schema as ISchema } from "@smithy/types"; |
| 2 | + |
| 3 | +import { ErrorSchema } from "./schemas/ErrorSchema"; |
| 4 | + |
| 5 | +export class TypeRegistry { |
| 6 | + public static active: TypeRegistry | null = null; |
| 7 | + public static readonly registries = new Map<string, TypeRegistry>(); |
| 8 | + |
| 9 | + private constructor( |
| 10 | + public readonly namespace: string, |
| 11 | + private schemas: Map<string, ISchema> = new Map() |
| 12 | + ) {} |
| 13 | + |
| 14 | + /** |
| 15 | + * @param namespace - specifier. |
| 16 | + * @returns the schema for that namespace, creating it if necessary. |
| 17 | + */ |
| 18 | + public static for(namespace: string): TypeRegistry { |
| 19 | + if (!TypeRegistry.registries.has(namespace)) { |
| 20 | + TypeRegistry.registries.set(namespace, new TypeRegistry(namespace)); |
| 21 | + } |
| 22 | + return TypeRegistry.registries.get(namespace)!; |
| 23 | + } |
| 24 | + |
| 25 | + /** |
| 26 | + * The active type registry's namespace is used. |
| 27 | + * @param shapeId - to be registered. |
| 28 | + * @param schema - to be registered. |
| 29 | + */ |
| 30 | + public register(shapeId: string, schema: ISchema) { |
| 31 | + const qualifiedName = this.normalizeShapeId(shapeId); |
| 32 | + const registry = TypeRegistry.for(this.getNamespace(shapeId)); |
| 33 | + registry.schemas.set(qualifiedName, schema); |
| 34 | + } |
| 35 | + |
| 36 | + /** |
| 37 | + * @param shapeId - query. |
| 38 | + * @returns the schema. |
| 39 | + */ |
| 40 | + public getSchema(shapeId: string): ISchema { |
| 41 | + const id = this.normalizeShapeId(shapeId); |
| 42 | + if (!this.schemas.has(id)) { |
| 43 | + throw new Error(`@smithy/core/schema - schema not found for ${id}`); |
| 44 | + } |
| 45 | + return this.schemas.get(id)!; |
| 46 | + } |
| 47 | + |
| 48 | + public getBaseException(): ErrorSchema | undefined { |
| 49 | + for (const [id, schema] of this.schemas.entries()) { |
| 50 | + if (id.startsWith("awssdkjs.synthetic.") && id.endsWith("ServiceException")) { |
| 51 | + return schema as ErrorSchema; |
| 52 | + } |
| 53 | + } |
| 54 | + return undefined; |
| 55 | + } |
| 56 | + |
| 57 | + public find(seeker: (schema: ISchema) => boolean) { |
| 58 | + return [...this.schemas.values()].find(seeker); |
| 59 | + } |
| 60 | + |
| 61 | + public destroy() { |
| 62 | + TypeRegistry.registries.delete(this.namespace); |
| 63 | + this.schemas.clear(); |
| 64 | + } |
| 65 | + |
| 66 | + private normalizeShapeId(shapeId: string) { |
| 67 | + if (shapeId.includes("#")) { |
| 68 | + return shapeId; |
| 69 | + } |
| 70 | + return this.namespace + "#" + shapeId; |
| 71 | + } |
| 72 | + |
| 73 | + private getNamespace(shapeId: string) { |
| 74 | + return this.normalizeShapeId(shapeId).split("#")[0]; |
| 75 | + } |
| 76 | +} |
0 commit comments