ParseJSONSchema parses a JSON schema into an OpenAPI schema. Notably, it also extracts the `$defs` from the JSON schema and rewrites its `$ref` paths. This is necessary because OpenAPI 3.0 and JSON schema differ in how they handle definitions. Where JSON schema uses `$defs` inside the schema, OpenA
(namePrefix, jsonSchema string)
| 28 | // |
| 29 | // Since the OpenAPI definitions have global scope, we also prefix the definition names with `namePrefix` to avoid collisions. |
| 30 | func ParseJSONSchema(namePrefix, jsonSchema string) (*openapi3.Schema, map[string]*openapi3.SchemaRef, error) { |
| 31 | // Validate it is a valid JSON schema |
| 32 | _, err := jsonschema.CompileString("schema", jsonSchema) |
| 33 | if err != nil { |
| 34 | return nil, nil, fmt.Errorf("invalid JSON schema: %w", err) |
| 35 | } |
| 36 | |
| 37 | // Parse it into a map |
| 38 | var schemaMap map[string]any |
| 39 | if err := json.Unmarshal([]byte(jsonSchema), &schemaMap); err != nil { |
| 40 | return nil, nil, err |
| 41 | } |
| 42 | |
| 43 | // Extract $defs into components |
| 44 | components := make(map[string]*openapi3.SchemaRef) |
| 45 | if defs, ok := schemaMap["$defs"].(map[string]any); ok { |
| 46 | for defName, defSchema := range defs { |
| 47 | err := rewriteJSONSchemaRefs(namePrefix, defSchema) |
| 48 | if err != nil { |
| 49 | return nil, nil, fmt.Errorf("failed to rewrite refs for def %q: %w", defName, err) |
| 50 | } |
| 51 | |
| 52 | defSchemaMap, ok := defSchema.(map[string]any) |
| 53 | if !ok { |
| 54 | return nil, nil, fmt.Errorf("failed to rewrite def %q: expected map, got %T", defName, defSchema) |
| 55 | } |
| 56 | |
| 57 | openapiSchema, err := mapToSchema(defSchemaMap) |
| 58 | if err != nil { |
| 59 | return nil, nil, fmt.Errorf("failed to convert def %q to OpenAPI: %w", defName, err) |
| 60 | } |
| 61 | |
| 62 | components[namePrefix+defName] = &openapi3.SchemaRef{ |
| 63 | Value: openapiSchema, |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | // Remove $defs from the main schema |
| 68 | delete(schemaMap, "$defs") |
| 69 | } |
| 70 | |
| 71 | // Rewrite $ref paths in the main schema |
| 72 | err = rewriteJSONSchemaRefs(namePrefix, schemaMap) |
| 73 | if err != nil { |
| 74 | return nil, nil, fmt.Errorf("failed to rewrite refs in main schema: %w", err) |
| 75 | } |
| 76 | |
| 77 | // Convert the main schema to OpenAPI format |
| 78 | mainSchema, err := mapToSchema(schemaMap) |
| 79 | if err != nil { |
| 80 | return nil, nil, fmt.Errorf("failed to convert main schema to OpenAPI: %w", err) |
| 81 | } |
| 82 | |
| 83 | return mainSchema, components, nil |
| 84 | } |
| 85 | |
| 86 | // rewriteJSONSchemaRefs recursively rewrites $ref paths from "#/$defs/Name" to "#/components/schemas/<namePrefix>Name". |
| 87 | // This is necessary to convert a JSON schema to an OpenAPI schema. See the docstring for ParseJSONSchema for more details. |